我需要创建一个新函数,该函数将返回每次胜利,失败和平局结果的数量。使用每个用户的选择(石头,纸张或剪刀),然后单击“开始!”。按钮,它将更新所有计数器和日志。
HTML显示一种按钮形式(每个按钮都用于石头和剪刀选项),以及正在执行的“ GO!”。按钮。
JS仅具有一个功能play()
并执行岩石,纸张,剪刀阵列的随机化,这将决定计算机将选择什么。此函数仅声明每场比赛是胜利,失败还是平局,但不会记录下来(感谢用户@BarMar为我提供帮助):
function play() {
var types = ['Rock', 'Paper', 'Scissors'];
var computer_choice = types[Math.floor(Math.random() * (types.length))];
document.getElementById("choiceDisplay").innerHTML = computer_choice;
var user_button = document.querySelector("input[name=choice]:checked");
if (user_button) {
var user_choice = user_button.value;
} else {
window.alert("You have to choose Rock, Paper, or Scissors first.");
return;
}
if (user_choice == computer_choice) {
document.getElementById("result").textContent = "Tie!";
return;
}
switch (computer_choice) {
case "Rock":
if (user_choice == "Paper") {
document.getElementById("result").textContent = "You Win!";
} else {
document.getElementById("result").textContent = "You Lost.";
}
break;
case "Paper":
if (user_choice == "Scissors") {
document.getElementById("result").textContent = "You Win!";
} else {
document.getElementById("result").textContent = "You Lost.";
}
break;
case "Scissors":
if (user_choice == "Rock") {
document.getElementById("result").textContent = "You Win!";
} else {
document.getElementById("result").textContent = "You Lost.";
}
}
}
<html>
<body>
<div class="stuff">
<h2> Select one: </h2>
<div class="choices">
<p>
<form>
<input type="radio" name="choice" value= "Rock" id="Rock"/>Rock
<br>
<input type="radio" name="choice" value= "Paper" id="Paper"/>Paper
<br>
<input type="radio" name="choice" value="Scissors" id="Scissors"/>Scissors
</form>
</p>
</div>
<div class= "choiceDisplay">
<div class = "ccc">The Computer Chose:</div>
<p id= "choiceDisplay"></p>
<div class = "button"> <button onclick="play()">GO!</button> </div>
<div class= "label"><p id = "result"></p></div>
</div>
</div>
</body>
</html>
最佳答案
我猜这是一个作业问题,因为我已经看过两次了,哈哈;无论如何,执行此操作的一种方法是为结果添加显示并更新它们。
显示
<h4>Wins <span id="wins">0</span></h4>
<h4>Losses <span id="losses">0</span></h4>
<h4>Ties <span id="ties">0</span></h4>
更新结构
var wins = document.getElementById("wins");
wins.innerHTML = parseInt(wins.innerHTML) + 1;
例
https://jsfiddle.net/8qpz9tnx/
关于javascript - 如何记录和更新剪刀石头布游戏的赢,输和绑历史?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58141566/