Last active
January 23, 2018 10:55
-
-
Save carbontwelve/f652340f7c6509fc7681bdd2bced5db0 to your computer and use it in GitHub Desktop.
Scratch Card
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style> | |
.box, .winner{ | |
background: #ccc; | |
margin: 10px 5px; | |
width: 30px; | |
height: 30px; | |
text-align: center; | |
float: left; | |
line-height: 30px | |
} | |
.winner{ | |
background: #001f3f; | |
color: white; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="box"></div> | |
<div class="winner"></div> | |
<script> | |
let winner | |
let winnings = [ | |
{content: 'A', count: 0}, | |
{content: 'B', count: 0}, | |
{content: 'C', count: 0}, | |
{content: 'D', count: 0}, | |
] | |
let maxCopies = 3 | |
let getPrize = function () { | |
// 2. Filter out any prizes that have a count >= maxCopies | |
winnings = winnings.filter(item => item.count < maxCopies) | |
// 3. Grab random item from remaining winnings pool, or default if none found | |
if (winnings.length === 0) { | |
return { | |
content: '-', count: 0 | |
} | |
} | |
let k = Math.floor(Math.random() * winnings.length) | |
winnings[k].count++ | |
return winnings[k] | |
} | |
document.querySelectorAll('.box').forEach((el, i) => { | |
let p = getPrize() | |
// Debugging | |
// if (p.count > maxCopies) { | |
// console.error('Prize [' + p.content + '] count [' + p.count + '/' + maxCopies + ']. Prizes left: [' + winnings.length + '] ') | |
// } else { | |
// console.log('Prize [' + p.content + '] count [' + p.count + '/' + maxCopies + ']. Prizes left: [' + winnings.length + '] ') | |
// } | |
el.innerHTML = `${p.content}` | |
// 1. Loop over winnings to check for winner | |
for (let i = 0; i < winnings.length; i++) { | |
if (maxCopies === 3 && !winner && winnings[i].count === maxCopies){ | |
winner = winnings[i] | |
maxCopies = 2 | |
} | |
} | |
}) | |
if (winner) { | |
document.querySelector('.winner').innerHTML = `${winner.content}`; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment