通过js实现猜拳
实现猜拳游戏的步骤
HTML 结构 创建基础的 HTML 结构,包含玩家选项按钮和结果显示区域。

<!DOCTYPE html>
<html>
<head>
<title>猜拳游戏</title>
<style>
button { margin: 10px; padding: 8px; }
#result { font-size: 20px; margin-top: 20px; }
</style>
</head>
<body>
<h1>猜拳游戏</h1>
<button onclick="playGame('石头')">石头</button>
<button onclick="playGame('剪刀')">剪刀</button>
<button onclick="playGame('布')">布</button>
<div id="result"></div>
<script src="game.js"></script>
</body>
</html>
JavaScript 逻辑 编写游戏逻辑,包括随机生成电脑选择、判断胜负并显示结果。

function playGame(playerChoice) {
const choices = ['石头', '剪刀', '布'];
const computerChoice = choices[Math.floor(Math.random() * 3)];
const result = determineWinner(playerChoice, computerChoice);
document.getElementById('result').innerHTML = `
你选择了: ${playerChoice}<br>
电脑选择了: ${computerChoice}<br>
结果: ${result}
`;
}
function determineWinner(player, computer) {
if (player === computer) return '平局';
const winConditions = {
'石头': '剪刀',
'剪刀': '布',
'布': '石头'
};
return winConditions[player] === computer ? '你赢了!' : '你输了!';
}
扩展功能
增加计分系统 添加全局变量记录胜负次数,并在结果中显示。
let wins = 0, losses = 0, draws = 0;
function playGame(playerChoice) {
const computerChoice = ['石头', '剪刀', '布'][Math.floor(Math.random() * 3)];
const result = determineWinner(playerChoice, computerChoice);
if (result.includes('赢')) wins++;
else if (result.includes('输')) losses++;
else draws++;
document.getElementById('result').innerHTML = `
胜负统计: ${wins}胜 ${losses}负 ${draws}平<br>
本次结果: ${result}
`;
}
添加动画效果 在结果显示前增加简单的选择动画。
function playGame(playerChoice) {
const resultElement = document.getElementById('result');
resultElement.innerHTML = '电脑正在出拳...';
setTimeout(() => {
const computerChoice = ['石头', '剪刀', '布'][Math.floor(Math.random() * 3)];
const result = determineWinner(playerChoice, computerChoice);
resultElement.innerHTML = `电脑选择: ${computerChoice}<br>${result}`;
}, 1000);
}






