为什么要实现像石头剪刀布这样微不足道的东西?让我们做一些更有趣的事情。有点像,石头剪刀布蜥蜴斯波克。
首先我们创建一个手势列表:
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>
当然,如果你想玩剪刀石头布,那就去吧,你是劣等生命体。