function styleElement(styles) {
var el = document.getElementById(styles[0]);
el.style.fontSize = styles[1];
el.style.color = styles[2];
}
function stylize(styles1, styles2, bodyBgColor) {
styleElement(styles1);
styleElement(styles2);
document.body.style.backgroundColor = bodyBgColor;
}
function getRandColor() {
var hex = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"],
color = "#";
for (var i = 0; i < 6; i += 1) {
color += hex[Math.floor(Math.random() * hex.length)];
}
return color;
}
function getRandInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function removeEvents(event, nodelist, f) {
for (var i = 0; i < nodelist.length; i += 1) {
nodelist[i].removeEventListener(event, f);
}
}
var buttons = document.querySelectorAll(".guess"),
len = buttons.length,
rand = Math.floor(Math.random() * len) + 1,
count = 0,
maxAttempts = 3;
function init() {
if (typeof(this.once) !== "undefined") {
alert("Button has already been pressed!");
} else {
this.once = true;
count += 1;
}
var i = +this.innerHTML.replace(/\D/, "");
if (i === rand) {
this.style.color = "green";
stylize(["wrong", "18px", getRandColor()], ["right", "78px",
"green"
], getRandColor());
alert("Yes, this is the right one!");
removeEvents("click", buttons, init);
return;
} else {
this.style.color = "red";
stylize(["wrong", getRandInt(25, 50) + "px", getRandColor()], ["right", getRandInt(18, 25) + "px", getRandColor()], getRandColor());
}
if (count === maxAttempts) {
alert("You lose");
removeEvents("click", buttons, init);
return;
}
}
for (var i = 0; i < buttons.length; i += 1) {
buttons[i].addEventListener("click", init);
}
button.guess {
display: block;
margin: 5px 0;
}
<p>GUESS THE NUMBER BUTTON...</p>
<p>Win by guessing the right number button.</p>
<p>IF YOU GUESSED 3 TIMES... YOU LOSE THE GAME.</p>
<p>Restart if you encounter problems.</p>
<p>IS IT...</p>
<p id="wrong">WRONG</p>
<p>OR</p>
<p id="right">RIGHT</p>
<button class="guess">1?</button>
<button class="guess">2?</button>
<button class="guess">3?</button>
<button class="guess">4?</button>
<button class="guess">5?</button>
<button class="guess">6?</button>
<button class="guess">7?</button>
<button class="guess">8?</button>
<button class="guess">9?</button>
<button class="guess">10?</button>