将html输入链接到JavaScript游戏

时间:2014-07-21 08:49:39

标签: javascript html textfield

我正在尝试制作一个简单的JavaScript游戏,但不知道我做错了什么帮助。

<html>
<head>
<script type="text/javascript">
 function myFunction(form) {
     var input = form.input1.value;
     var input = input.toLowerCase();
     var cpu = Math.floor(Math.random() * 6) + 1

     if (input == "rock") {
         var input = 1;

     }
     elseif(input == "paper") {
         var input = 2;

     }
     elseif(input == "scissors") {
         var input = 3;

     } else {

         alert("Invalid Input!");
     }
     if (input == (1)) and(cpu == (3)) {
         alert("You Win!");

     }
     elseif(input == (2)) and(cpu == (1)) {
         alert("You Win!");

     }
     elseif(input == (3)) and(cpu == (2)) {
         alert("You Win!");

     }
     elseif(input == (1)) and(cpu == (3)) {
         alert("You Win!");

     } else {

         alert("you lose!");
     }

 }
</script>
<body>
rock = 1
paper = 2
scissors = 3
<form name="myform" action="" method="get">
<input type="text" name="input1">

</input>
<button name="button1" onClick="myFunction(form)">Go</button>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的代码中存在很多错误。

我已经修改了您的Javascript和HTML,请对旧版本和新版本进行比较,看看修改后的内容以及您知道自己做错了什么。

<html>
<head>
<script>
function myFunction() {
var shape = document.getElementById("shape");
var input = shape.value;
var cpu = Math.floor(Math.random() * 6) + 1;
if (input == 1 || input == 2 || input == 3){}
else if (input == "rock") {var input = 1;}
else if(input == "paper") {var input = 2;}
else if(input == "scissors") {var input = 3;}
else {alert("Invalid Input!"); return;}

if (input == 1 && cpu == 3) {alert("You Win! Rock Over Paper!");}
else if(input == 2 && cpu == 1) {alert("You Win! Paper Over Rock!");}
else if(input == 3 && cpu == 2) {alert("You Win! Scissors Over Paper");}
else {alert("You lose!");}

}
</script>
</head>
<body>
rock = 1
paper = 2
scissors = 3
<input type="text" name="input1" id="shape">
</input>
<input type="button" name="button1" onclick="myFunction()" value="Go">
</body>
</html>