我正在尝试重置我的代码中的变量,它是 javascript,所以当我按下 playAgainBtn 按钮时,它会重新启动我的变量。现在,当我按下 playAgainBtn 时,游戏继续使用相同的变量值。
代码可以在这个链接查看:https ://studio.code.org/projects/applab/-Nj1Z6FPRpBe5AozECuNfBgHFqIzzt6-I6eJSJwJG-8
onEvent("playAgainBtn", "click", function() {
console.log("playAgainBtn clicked!");
setScreen("gamePlay_screen");
});
var randButtonId;
//var buttonId;
var currentPlayer = 1;
var p1Score=0;
var p2Score=0;
setBoard();
//checkCorrect(randButtonId);
function setBoard() {
var r = (randomNumber(0, 255));
var g = (randomNumber(0, 255));
var b = (randomNumber(0, 255));
var color = rgb(r, g, b);
setProperty("button1", "background-color", color);
setProperty("button2", "background-color", color);
setProperty("button3", "background-color", color);
setProperty("button4", "background-color", color);
var diffColor = rgb(r+40, g+40, b+40);
randButtonId = "button"+randomNumber(1,4);
setProperty(randButtonId, "background-color", diffColor);
console.log("correct one is: " + randButtonId);
}
onEvent("button1", "click", function(){
console.log("Checking: "+randButtonId);
checkCorrect("button1");
});
onEvent("button2", "click", function(){
checkCorrect("button2");
console.log("Checking: "+randButtonId);
});
onEvent("button3", "click", function(){
checkCorrect("button3");
console.log("Checking: "+randButtonId);
});
onEvent("button4", "click", function(){
checkCorrect("button4");
console.log("Checking: "+randButtonId);
});
setBoard();
function checkCorrect(buttonId){
console.log("Checking: "+randButtonId);
if(buttonId == randButtonId ) {
console.log("You got it right!");
updateScoreBy(1);
} else {
console.log("WRONG");
updateScoreBy(-3);
}
checkGameOver();
setBoard();
switchPlayer();
}
function switchPlayer(){
if(currentPlayer==1){
currentPlayer=2;
} else {
currentPlayer=1;
}
console.log("current player is: "+currentPlayer);
if(currentPlayer==1){
showElement("player1_highlight");
hideElement("player2_highlight");
}else{
showElement("player2_highlight");
hideElement("player1_highlight");
}
}
function updateScoreBy(amt){
if(currentPlayer == 1){
p1Score = p1Score + amt;
} else {
p2Score = p2Score + amt;
}
console.log("P1 score: " + p1Score);
console.log("P2 score: " + p2Score);
setText("score1_label", p1Score);
setText("score2_label", p2Score);
}
function checkGameOver(){
if(p1Score == 10){
setScreen("gameOver_screen");
showElement("player1Win_label");
hideElement("player2Win_label");
}
else if(p2Score == 10){
setScreen("gameOver_screen");
showElement("player2Win_label");
hideElement("player1Win_label");
}
}