我剛剛在codecademy上完成了一個rps遊戲,並且還有一些額外的任務,包括如果用戶輸入錯誤的信息會產生結果。基本上,如果你不寫一個「搖滾」,「紙」或「剪刀」的輸入,它會再次問你,直到你把它放在正確的一個。岩石紙,剪刀遊戲
我怎麼能調用userChoice變量,直到它得到正確的答案。我試過這樣,但它只是問了2次,然後發佈你寫的任何東西。
var userChoice = prompt("Do you choose rock, paper or scissors?");
if (userChoice != "rock", "paper", "scissors") {
userChoice = prompt("Do you choose rock, paper or scissors?");
}
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}
else if(choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";
}
}
else if(choice1 === "paper") {
if(choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";
}
}
else if(choice1 === "scissors") {
if(choice2 === "rock") {
return "rock wins";
}
else {
return "scissors wins";
}
}
}
console.log("Human: " + userChoice);
console.log("Computer: " + computerChoice);
compare(userChoice, computerChoice);
使用做... while循環 – Robert
你可以大量簡化這一點 - 我有一個小樂趣。看看這個,我已經添加了評論來解釋快捷鍵:http://jsfiddle.net/svArtist/12nLz7nb/ –
明天我會研究它,謝謝你的建議 –