我想把一个摇滚,纸张,剪刀游戏作为JavaScript的初学者。
我的游戏计划是:
用户点击选项(摇滚,纸张,剪刀)后,将显示他们的分数和计算机分数。它会显示结果。一旦他们的分数达到一定数量,他们就可以输入他们的名字并将其记录在某处。
有人可以告诉我如何做到这一点,我是初学者,如果有人能告诉我如何做到这一点会很好。请在JS Fiddle网页上查看; l。我正在整合HTML和CSS。
我是在JSFiddle上做的:https://jsfiddle.net/y3qu7pzz/
由于
enter code here: This is the JS
function playgame (x){
var options = ["rock", "paper", "scissors"]
var playerChoice = x
var randomNumber = Math.floor(Math.random()*options.length)
var computerChoice = options[randomNumber]
function determineWinner(){
//
if (playerChoice == computerChoice) {
//
$("#results").html("You selected " + playerChoice + " and the computer selected " + computerChoice + ". Game tied.<br />")
}
//
else if (playerChoice == "rock" && computerChoice == "paper" || playerChoice == "scissors" && computerChoice == "rock" || playerChoice == "paper" && computerChoice == "scissors") {
//
$("#results").html("You selected " + playerChoice + " and the computer selected " + computerChoice + ". You lost. <br />")
}
//
else if (playerChoice == "rock" && computerChoice == "scissors" || playerChoice == "scissors" && computerChoice == "paper" || playerChoice == "paper" && computerChoice == "rock") {
//
$("#results").html("You selected " + playerChoice + " and the computer selected " + computerChoice + ". You won. <br />")
}
//
else {
//
alert("Please enter rock, paper or scissors")
}
}
//
determineWinner()
}
$(".start").click(function (){
var choice = $(this).attr("id")
playgame(choice)
})
答案 0 :(得分:0)
看起来您的代码正在运行。你说你想把分数存储在某个地方。第一部分将包括适当的分数和增量。 您可以存储一个全局变量,其中包含计算机赢得的次数和玩家赢得的次数
var computerWins = 0;
var playerWins = 0;
var draws = 0;
在determineWinner()
//computer wins conditional
computerWins++;
...
//player wins conditional
playerWins++;
//..etc
最终计算得分百分比得分:
var percentageWins = (playerWins / (computerWins + playerWins + draws)) * 100;
向用户显示等。
您可能希望将分数存储在localstorage
中,因此如果用户离开页面并返回,则仍然会持续存在。见https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
您想要从localstorage
设置/获取胜出/抽奖变量。
或者,您可以将数据发布到某个端点并检索它,但这需要额外的服务器。