Javascript阵列迷你游戏



我正在尝试一个非常简单的游戏版本"石头、纸或剪刀";使用javascript。(主要是为了学习函数,尽管我认为我的代码是有意义的,它应该在控制台中打印每个If-Else语句的输出,但它不会打印任何内容

有什么提示吗?

下方的代码

const startGame = document.getElementById('start-game-btn');
const choicePlayer = ["Rock" , "Scissor", "Paper"];
const defaultChoise = "Rock";

function startTheGame(choicePlayer,defaultChoise) {
alert("Choose Rock , Scissor or Paper");
prompt(choicePlayer[0], choicePlayer[1]);
for (var i=0; i<choicePlayer.length; i++)  {
if(choicePlayer[i]===choicePlayer[0] || choicePlayer[i] === choicePlayer[1] || choicePlayer[i] === choicePlayer[2]) {
console.log("asdf");
return choicePlayer[i];
}
else  {
console.log("we choose for you");
return defaultChoise;
}
}
}

startGame.addEventListener('click' , startTheGame);

prompt的工作原理是返回一个值,这意味着您应该这样使用它:

choicePlayer[0] = prompt("Player 1 - Choose Rock , Scissor or Paper", choicePlayer[0]);
choicePlayer[1] = prompt("Player 2 - Choose Rock , Scissor or Paper", choicePlayer[1]);

另外,有一个名为choicePlayer的函数参数将覆盖全局变量choicePlayer,这意味着函数中的choicePlayer包含event参数。

为了保存来自prompt函数的用户输入,您应该将其保存在一个变量中,如下所示:const result = prompt("text that will show in the prompt");您可以查看我添加的片段以获得其他一些修复的解决方案。

const startGame = document.getElementById('start-game-btn');
const choices = ["rock" , "scissor", "paper"];
const defaultChoice = "rock";
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
function gameInit() {
const playerChoice = prompt("Choose Rock , Scissor or Paper");
if(choices.includes(playerChoice.toLowerCase())) {
//return playerChoice;
console.log(capitalizeFirstLetter(playerChoice));
} else  {
console.log("we choose for you");
//return defaultChoice;
console.log(capitalizeFirstLetter(defaultChoice));
}
}

startGame.addEventListener('click' , gameInit);
<button id="start-game-btn">Start</button>

最新更新