1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<html>
<body>
<div id='lock'></div>
<script>
const lock = document.getElementById('lock')
function makeLockDigit(changeCallback) {
// Make an input that can be set between 0 and 9.
// This is equivalent to <input type='number' min='0' max='9' />.
const digit = document.createElement('input')
digit.type = 'number'
digit.min = 0
digit.max = 9
// Start it with a random value
digit.value = String(Math.floor(Math.random() * 10))
// When the digit changes, call `changeCallback()`,
// passing the new value of the digit.
// Inputs' values are strings, so we convert them to numbers.
digit.onchange = () => changeCallback(Number(digit.value))
// Add the digit to the lock
lock.appendChild(digit)
}
// The super secret combination
const COMBO = [1, 2, 3, 4]
// The number of correct digits
let correctCount = 0
for (let i = 0; i < COMBO.length; i++) {
// Whether this digit was previously correct
let wasCorrect = false
makeLockDigit(value => {
// Compare the digit's actual value to the correct value
const isCorrect = (value === COMBO[i])
// Update the number of correct digits if this one changed
if (!wasCorrect && isCorrect) correctCount++
else if (wasCorrect && !isCorrect) correctCount--
wasCorrect = isCorrect
// If all digits are now correct, show a message
if (correctCount === COMBO.length) {
alert('You got the combination')
}
})
}
</script>
</body>
</html>