石头、布和剪刀游戏是一种经典的多人对决游戏,玩家通过选择石头、布或剪刀来决定胜负。下面是在JavaScript上构建石头、布和剪刀游戏的示例代码:
// 定义游戏选项
const options = ["石头", "布", "剪刀"];
// 生成电脑的随机选择
function computerPlay() {
const randomIndex = Math.floor(Math.random() * options.length);
return options[randomIndex];
}
// 判断胜负
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "平局!";
} else if (
(playerSelection === "石头" && computerSelection === "剪刀") ||
(playerSelection === "布" && computerSelection === "石头") ||
(playerSelection === "剪刀" && computerSelection === "布")
) {
return "你赢了!";
} else {
return "你输了!";
}
}
// 运行游戏
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 0; i < 5; i++) {
const playerSelection = prompt("请选择:石头、布或剪刀").toLowerCase();
const computerSelection = computerPlay();
console.log(`你选择了:${playerSelection}`);
console.log(`电脑选择了:${computerSelection}`);
const result = playRound(playerSelection, computerSelection);
console.log(result);
if (result === "你赢了!") {
playerScore++;
} else if (result === "你输了!") {
computerScore++;
}
}
console.log(`最终得分:你 ${playerScore} - ${computerScore} 电脑`);
if (playerScore > computerScore) {
console.log("恭喜你,你赢得了游戏!");
} else if (playerScore < computerScore) {
console.log("很遗憾,你输掉了游戏!");
} else {
console.log("游戏结束,平局!");
}
}
// 运行游戏
game();
这段代码实现了一个简单的石头、布和剪刀游戏。玩家通过命令行输入选择,与电脑进行对决,并最终输出游戏结果。
该游戏的应用场景包括娱乐、教育等领域,可以用于开发小型游戏应用或教学示例。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云