我正在尝试重置我的代码中的变量,这是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");
}
}
答案 0 :(得分:1)
您可以创建一个重置变量的新函数。
function resetBoard() {
currentPlayer = 1;
p1Score = 0;
p2Score = 0;
}
然后在您的活动中,您可以调用该功能
onEvent("playAgainBtn", "click", function() {
console.log("playAgainBtn clicked!");
resetBoard();
setScreen("gamePlay_screen");
});
我无法在该网站上进行测试,所以如果这对您不起作用,请告诉我。