-3

我想创建一个石头剪刀布游戏,按照这里的说明,查看我的代码哪里出错了。

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>
4

1 回答 1

8

为什么要实现像石头剪刀布这样微不足道的东西?让我们做一些更有趣的事情。有点像,石头剪刀布蜥蜴斯波克

首先我们创建一个手势列表:

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>

当然,如果你想玩剪刀石头布,那就去吧,你是劣等生命体。

于 2013-07-20T10:42:11.610 回答