所以,我正在使用Javascript制作摇滚,纸张,剪刀游戏,我在开始时遇到了一些麻烦。我需要一个文本框和提交按钮,然后用户输入“摇滚”,“纸”,“剪刀”将对着电脑的随机选择。我如何让计算机将输入的内容输入文本字段并针对计算机选择运行?我是一个新手,需要在正确的方向上轻推,因为我不知道如何解决这个问题。
由于
编辑: 所以,一位朋友给我发了一些代码,我添加了一些代码,看起来它会起作用(至少对我来说),但是我不知道将变量“player”设置为等于是什么文本框信息。
var player =
var choices = ["rock","paper","scissors"];
var computer = choices[Math.floor(Math.random()*3)];
var win = "Your "+player+" beats "+computer+". You win.";
var lose = "Your "+player+" loses to "+computer+". You lose.";
var draw = "A draw: "+player+" on "+computer+".";
if(player === "rock"){
if(computer === "scissors"){
result = win;
alert="win";
}
else if(computer === "paper"){
result = lose;
alert="lose";
}
else if(computer === "rock"){
result = draw;
alert="draw";
}
}
else if(player === "paper"){
if(computer === "rock"){
result = win;
alert="win";
}
else if(computer === "scissors"){
result = lose;
alert="lose";
}
else if(computer === "paper"){
result = draw;
alert="draw";
}
}
else if(player === "scissors"){
if(computer === "paper"){
result = win;
alert="win";
}
else if(computer === "rock"){
result = lose;
alert="lose";
}
else if(computer === "scissors"){
result = draw;
alert="draw";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="rockTextInput" size="100" placeholder="Rock, Paper, or Scissors" >
<input type="button" id="Button" value="Play Hand">
</form>
</body>
</html>
答案 0 :(得分:0)
计算机的选择可以像这样生成:
...
var plays = ["rock", "paper", "scissors"];
var rand = Math.round(Math.random() * 2);
alert("Computer played: " + plays[rand]);
//Check to see the winner
...
希望这有助于您开始。
答案 1 :(得分:0)
由于可能性有限,一种方法是使用查找表。您必须使用更多JavaScript将其链接到HTML。为此,您可能希望将document.getElementById
与<input>
的value一起使用,并输出到其他Element。
/*
Usage:
play(player_choice)
player_choice String, 'rock', 'paper' or 'scissors'
returns Object with properties
player String, player's choice
ai String, ai's choice
result Integer, 0 - lose, 1 - draw, 2 - win
resultText String, description of result
*/
var play = (function () {
var options = ['rock', 'paper', 'scissors'],
result_table = {
'rock': {
'rock': 1,
'paper': 0,
'scissors': 2
},
'paper': {
'rock': 2,
'paper': 1,
'scissors': 0
},
'scissors': {
'rock': 0,
'paper': 2,
'scissors': 1
}
},
result_text = ['AI wins', 'Draw', 'Player wins'];
return function (player_choice) {
var ai_choice;
player_choice = player_choice.toLowerCase();
if (!result_table.hasOwnProperty(player_choice)) {
throw '[' + player_choice + '] not a valid choice.';
}
ai_choice = options[Math.floor(Math.random() * options.length)];
return {
'player': player_choice,
'ai': ai_choice,
'result': result_table[player_choice][ai_choice],
'resultText': result_text[result_table[player_choice][ai_choice]]
};
};
}());