I create a game in which players can guess the most dominant color in a randomly generated color. I want them to gain one point after one right guess. When they lose, they can choose to restart. You can see how the game works here: https://donguyentung2001.github.io/color-game/. Now, in the source code, I call the runGame function without the parentheses in the replay() function. This works well, but when I add the parentheses to the runGame function, what happens is that when the players loses, the result.textContent does not reset to "" as specified in the replay() function. I don't understand how the difference with and without parentheses affects this outcome. Can someone help me understand this? Thank you a lot!
let green = Math.floor(Math.random() * 256);
let blue = Math.floor(Math.random() * 256);
let score=0;
document.getElementById("sth").style.backgroundColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
let select = document.querySelector('#options');
let result = document.querySelector('.result');
select.addEventListener("change", runGame)
function runGame() {
if ((red===Math.max(red,green,blue) && select.value.localeCompare("red")===0) || (green===Math.max(red,green,blue) && select.value.localeCompare("green")===0)
|| (blue===Math.max(red,green,blue) && select.value.localeCompare("blue")===0)) {
score+=1;
result.textContent="Congratulations! You got this right. Your score is " + score;
select.value="default";
red = Math.floor(Math.random() * 256);
green = Math.floor(Math.random() * 256);
blue = Math.floor(Math.random() * 256);
document.getElementById("sth").style.backgroundColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
select.addEventListener("change",runGame);
}
else {
result.textContent="Oops. You got it wrong. Your score is " + score;
select.value="default";
button=document.createElement("button");
button.textContent="Try again!";
button.id="button-1";
score=0;
document.body.appendChild(button);
button.onclick=replay;
}
}
function replay() {
red = Math.floor(Math.random() * 256);
green = Math.floor(Math.random() * 256);
blue = Math.floor(Math.random() * 256);
score=0;
document.getElementById("sth").style.backgroundColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
result.textContent="";
document.getElementById("button-1").remove();
runGame();
}```
Aucun commentaire:
Enregistrer un commentaire