js实现猜拳
实现猜拳游戏的步骤
HTML 结构 创建一个简单的HTML页面,包含三个按钮(石头、剪刀、布)和一个显示结果的区域。
<!DOCTYPE html>
<html>
<head>
<title>猜拳游戏</title>
<style>
button { margin: 10px; padding: 8px; }
#result { margin-top: 20px; font-size: 18px; }
</style>
</head>
<body>
<h1>猜拳游戏</h1>
<button id="rock">石头</button>
<button id="scissors">剪刀</button>
<button id="paper">布</button>
<div id="result"></div>
<script src="game.js"></script>
</body>
</html>
JavaScript 逻辑
在game.js中实现游戏逻辑,包括玩家选择、电脑随机选择以及胜负判断。
const buttons = document.querySelectorAll('button');
const resultDiv = document.getElementById('result');
const choices = ['石头', '剪刀', '布'];
buttons.forEach(button => {
button.addEventListener('click', () => {
const playerChoice = button.textContent;
const computerChoice = choices[Math.floor(Math.random() * 3)];
const winner = determineWinner(playerChoice, computerChoice);
resultDiv.textContent = `你选择了 ${playerChoice},电脑选择了 ${computerChoice}。${winner}`;
});
});
function determineWinner(player, computer) {
if (player === computer) return '平局!';
if (
(player === '石头' && computer === '剪刀') ||
(player === '剪刀' && computer === '布') ||
(player === '布' && computer === '石头')
) {
return '你赢了!';
} else {
return '电脑赢了!';
}
}
功能扩展 可以增加计分功能,记录玩家和电脑的胜负次数。
let playerScore = 0;
let computerScore = 0;
function updateScore(winner) {
if (winner.includes('你赢了')) playerScore++;
if (winner.includes('电脑赢了')) computerScore++;
resultDiv.textContent += ` 比分:玩家 ${playerScore} - 电脑 ${computerScore}`;
}
// 在事件监听器中调用
const winner = determineWinner(playerChoice, computerChoice);
updateScore(winner);
优化用户体验 添加动画效果或延迟显示电脑的选择,增强游戏体验。
button.addEventListener('click', () => {
resultDiv.textContent = '电脑正在选择...';
setTimeout(() => {
const computerChoice = choices[Math.floor(Math.random() * 3)];
const winner = determineWinner(playerChoice, computerChoice);
resultDiv.textContent = `你选择了 ${playerChoice},电脑选择了 ${computerChoice}。${winner}`;
updateScore(winner);
}, 1000);
});
注意事项
- 确保HTML和JavaScript文件在同一目录下,或正确引用路径。
- 可以通过CSS进一步美化界面,如添加按钮悬停效果或结果高亮显示。
- 如果需要更复杂的功能,可以添加游戏历史记录或重置比分按钮。







