gpt4 book ai didi

javascript - 剪刀石头布起作用,但未按计划进行

转载 作者:行者123 更新时间:2023-11-29 21:34:21 25 4
gpt4 key购买 nike

我已经为一个简单的剪刀石头布游戏编写了以下代码。它有效,但给出了非常意想不到的结果,我不明白为什么。

html:

<form action="#" id="form">
<input type="text" id="mypick" placeholder="Rock, paper or scissors?">
<input type="submit" value="Pick" id="button">
</form>

JavaScript:

var rock = 0,
paper = 1,
scissors = 2;

function result() {
var computerPick = Math.floor(Math.random() * 3);
console.log(computerPick);

var myPick = document.getElementById('mypick');
if (myPick == "rock") {
myPick = 0;
} else if (myPick == "paper") {
myPick = 1;
} else {
myPick = 2;
}

if (myPick === computerPick) {
alert("The same, try again!");
} else if (myPick === 0 && computerPick === 1) {
alert("You lose! Computer had paper!");
} else if (myPick === 0 && computerPick === 2) {
alert("You win! Computer had scissors!")
} else if (myPick === 1 && computerPick === 0) {
alert("You win! Computer had rock")
} else if (myPick === 1 && computerPick === 2) {
alert("You lose! Computer had scissors")
} else if (myPick === 2 && computerPick === 0) {
alert("You lose! Computer had rock")
} else if (myPick === 2 && computerPick === 1) {
alert("You win! Computer had paper")
}
document.getElementById('form').reset();
};

document.getElementById("button").onclick = result;

最佳答案

这是我认为应该有效的代码。你的错误。

如果您使用提交,那么您的浏览器将在您单击时刷新。

而且也不需要添加表单标签,因为没有任何请求发送到服务器。

document.getElementById('mypick') 将文本框作为对象返回。因此,要获取对象的值,您应该使用 document.getElementById('mypick').value

如果用户键入“bla bla”或“Paper”而不是“paper”怎么办?那么他们将被算作“摇滚”

还有一些其他的东西,比如使用额外的“;”或者使用 var 来定义您将在函数等中使用的变量。

<HTML>
<head>
<title> best browser game and ever</title>
<script>
function result(){
var computerPick = Math.floor(Math.random() * 3);
console.log(computerPick);
var strs=["Rock","Paper","Scissors"];

var myPick = document.getElementById('mypick').value;
if (myPick==-1){
alert('chooooose!');
}else{
var tmp = myPick - computerPick;
if (top==0){
alert("The same, try again!");
}elseif(top==1 || top==-2){
alert('You Won! Computer choosed:'+strs[computerPick]);
}elseif(top==-1 || top==2){
alert('You Lost! Computer choosed:'+strs[computerPick]);
}else{alert('something is wrong with universe');}
}
}
</script>
</head>
<body>
<p>If you win this, all hour dreams will come true.</p>
<select Id="mypick">
<option value="-1">choose</option>
<option value="0">R</option>
<option value="1">P</option>
<option value="2">S</option>
</select>
<input Id="kill" type="button" value="kill" onclick="result" />
</body>
</HTML>

关于javascript - 剪刀石头布起作用,但未按计划进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35248726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com