我想按照这里的说明创建一个石头剪刀游戏,看看我的代码哪里出错了。
1)使用3个按钮创建表单。所有3个按钮都应该有一个onClick事件,以及与它们相关的函数。
2)当按下任何按钮时,您应该:
1)为代表计算机手的计算机生成一个随机数(1 - 3)
2)将生成的数字与推送的按钮数量进行比较(例如,1表示摇滚,2表示纸张等)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Rock Paper Scissors</title>
<link rel="stylesheet"
<script>
function Random(choice) {
var system = Math.floor((Math.random() * 2) + 1);
display.innerHTML = system == choice ? 'draw' : system;
}
</script>
</head>
<body>
<form>
<input id="rock" type="button" onclick="Random(1)" value="Rock"/>
<input id="paper" type="button" onclick="Random(2)" value="Paper"/>
<input id="scissors" type="button" onclick="Random(3)" value="Scissors"/>
</form>
<span id="display"></span>
</body>
</html>
答案 0 :(得分:8)
为什么要像石头剪刀那样实现微不足道的东西?让我们做一些更有趣的事情。类似于Rock-paper-scissors-lizard-Spock。
首先我们创建一个手势列表:
var gestures = ["rock", "paper", "scissors", "lizard", "spock"];
然后我们写了一堆规则:
var rules = {
rock: { scissors: "breaks", lizard: "crushes" },
paper: { rock: "covers", spock: "disproves" },
scissors: { paper: "cuts", lizard: "decapitates" },
lizard: { paper: "eats", spock: "poisons" },
spock: { scissors: "smashes", rock: "vaporizes" }
};
最后我们实施游戏本身:
function play(index) {
var your = gestures[index];
var mine = gestures[Math.floor(5 * Math.random())];
if (your === mine) return alert("Draw. We both played " + your + ".");
var win = rules[your].hasOwnProperty(mine);
var result = win ? "win" : "lose";
var a = win ? your : mine;
var b = win ? mine : your;
alert("You " + result + ": " + a + " " + rules[a][b] + " " + b + ".");
}
参见演示:
var gestures = ["rock", "paper", "scissors", "lizard", "spock"];
var rules = {
rock: { scissors: "breaks", lizard: "crushes" },
paper: { rock: "covers", spock: "disproves" },
scissors: { paper: "cuts", lizard: "decapitates" },
lizard: { paper: "eats", spock: "poisons" },
spock: { scissors: "smashes", rock: "vaporizes" }
};
function play(index) {
var your = gestures[index];
var mine = gestures[Math.floor(5 * Math.random())];
if (your === mine) return alert("Draw. We both played " + your + ".");
var win = rules[your].hasOwnProperty(mine);
var result = win ? "win" : "lose";
var a = win ? your : mine;
var b = win ? mine : your;
alert("You " + result + ": " + a + " " + rules[a][b] + " " + b + ".");
}
<button onclick="play(0);">Rock</button>
<button onclick="play(1);">Paper</button>
<button onclick="play(2);">Scissors</button>
<button onclick="play(3);">Lizard</button>
<button onclick="play(4);">Spock</button>
当然,如果你想玩摇滚剪刀,那就继续吧,你的生活形式就会低劣。