【发布时间】:2021-03-26 08:48:45
【问题描述】:
我正在尝试使计算机与人类玩家的石头剪刀布比赛。我有函数computerplay(); 从三个可能的字符串(“Rock”、“Paper”、“Scissors”)中生成随机值作为游戏匹配值的计算机选择。使用第三个函数save(); 我允许玩家将他的选择输入到 HTML 表单中并尝试将其保存到 round();功能。
作为结果,我希望变量 c 或 p 递增或打印字符串“draw”,以指示 round(); 获取存储在 x 中的计算机选择和作为变量播放器的播放器选择。似乎 x 和 player 都附加了它们的值,但 round(); 函数没有收到它。感谢您帮助解决它。
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return 'Rock';
}
if (number % 3 === 1) {
return 'Paper';
}
return 'Scissors';
}
var p = 0;
var c = 0;
var x = computerPlay();
var player;
player = document.getElementById("player").value;
document.write(x);
function round ( playerSelection = player, computerSelection = x ) {
document.write(player);
document.write(x);
if (playerSelection == 'Rock' && computerSelection == 'Rock') {
document.write (p);
document.write (c);
document.write("draw");
}
else if (playerSelection == 'Rock' && computerSelection == 'Paper') {
c++;
document.write (p);
document.write (c);
document.write("comp");
}
else if (playerSelection == 'Rock' && computerSelection == 'Scissors') {
p++;
document.write (p);
document.write (c);
document.write("player");
}
else if (playerSelection == 'Scissors' && computerSelection == 'Rock') {
c++;
document.write (p);
document.write (c);
document.write("comp");
}
else if (playerSelection == 'Scissors' && computerSelection == 'Paper') {
p++;
document.write (p);
document.write (c);
document.write("player");
}
else if (playerSelection == 'Scissors' && computerSelection == 'Scissors') {
document.write (p);
document.write (c);
document.write("draw");
}
else if (playerSelection == 'Paper' && computerSelection == 'Rock') {
p++;
document.write (p);
document.write (c);
document.write("player");
}
else if (playerSelection == 'Paper' && computerSelection == 'Scissors') {
c++;
document.write (p);
document.write (c);
document.write("computer");
}
else if (playerSelection == 'Paper' && computerSelection == 'Paper') {
document.write (p);
document.write (c);
document.write("draw");
}
}
function save() {
var player;
player = document.getElementById("player").value;
document.write (player);
document.write(x);
computerPlay();
var x = computerPlay();
round();
}
document.write (p);
document.write (c);
if ( c == 5 ) {
document.write (c);
document.write ('computer win');
}
else if ( p == 5 ) {
document.write ('player win');
}
<p id="demo"></p>
<form id="form">
<input id="player" type="text" min="1" name="player">
<button type="button" onclick="save();">Get Value</button>
</form>
【问题讨论】:
-
嗨,好吧,我想我在这里看到了问题,您正在为 playerSelection 和 computerSelection 设置默认值,但这些值是在加载时设置的,那时玩家选择将为空。您需要在 save() 中的 round() 中传递玩家,这可以解决问题
标签: javascript html