[英]Need help in my rock paper and scissors game javascript
當用戶和計算機綁定時,它一直告訴我我輸了而不是被綁定。
<html>
<head>
<title>Rock, Paper and Scissors</title>
</head>
<body>
<p>Rock, Paper and Scissors!</p>
<input type="text" id ="textChoice">
<button id="submit">Submit</button>
<p id="paragraphChoice"></p>
<script type="text/javascript">
document.getElementById("submit").onclick = function() {
var computerChoice = ["rock", "paper", "scissors"];
var computerGuess =
computerChoice[Math.floor(Math.random() * computerChoice.length)];
var userGuess = document.getElementById("textChoice").value;
if (userGuess === computerGuess) {
document.getElementById("paragraphChoice").innerHTML =
"You tied! The computer choose "+ computerGuess; //Both tied!
}
if (userGuess === "rock") {
if (computerGuess === "scissors") {
//rock wins
document.getElementById("paragraphChoice").innerHTML =
"You won! The computer choose "+ computerGuess;
} else {
//paper wins
document.getElementById("paragraphChoice").innerHTML =
"You lost! The computer choose "+ computerGuess;
}
}
if (userGuess === "paper") {
if (computerGuess === "rock") {
//rock wins
document.getElementById("paragraphChoice").innerHTML =
"You won! The computer choose "+ computerGuess;
} else {
//scissors wins
document.getElementById("paragraphChoice").innerHTML =
"You lost! The computer choose "+ computerGuess;
}
}
if (userGuess === "scissors") {
if (computerGuess === "paper") {
document.getElementById("paragraphChoice").innerHTML =
"You won! The computer choose "+ computerGuess;
} else {
document.getElementById("paragraphChoice").innerHTML =
"You lost! The computer choose "+ computerGuess;
}
}
};
</script>
</body>
</html>
到目前為止我還沒有學習過函數,if 語句非常混亂(這就是我的想法)。
非常感謝您的幫助!
當您得到答案時,您就完成了: if 2===2 then finished 。 不要檢查其他可能性。 所以
if (userGuess === computerGuess) {
document.getElementById("paragraphChoice").innerHTML =
"You tied! The computer choose "+ computerGuess; //Both tied!
// you are done. return.
return;
}
如果你不告訴程序你完成了,它會繼續檢查所有其他的if-then
塊,最后一個將打印到頁面上。 您必須在每個if then
塊中添加一個return
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.