利用HTML做一个网页版的石头剪刀布游戏
HTML 代码示例:
<!DOCTYPE html>
<html>
<head>
<title>石头剪刀布游戏</title>
<style>
body { font-family: Arial, sans-serif; }
.game { text-align: center; }
.options { margin-bottom: 10px; }
.options label { display: inline-block; width: 100px; margin: 5px; }
.result { font-size: 20px; }
</style>
</head>
<body>
<div class="game">
<h1>石头剪刀布游戏</h1>
<div class="options">
<label>
石头
<input type="radio" name="player" value="rock">
</label>
<label>
剪刀
<input type="radio" name="player" value="scissors">
</label>
<label>
布
<input type="radio" name="player" value="paper">
</label>
</div>
<button id="play">出招</button>
<div class="result"></div>
</div>
<script>
function getComputerChoice() {
const choices = ['rock', 'paper', 'scissors'];
const randomIndex = Math.floor(Math.random() * 3);
return choices[randomIndex];
}
function determineWinner(playerChoice, computerChoice) {
if (playerChoice === computerChoice) {
return "平局";
} else if (
(playerChoice === 'rock' && computerChoice === 'scissors') ||
(playerChoice === 'paper' && computerChoice === 'rock') ||
(playerChoice === 'scissors' && computerChoice === 'paper')
) {
return "你赢了!";
} else {
return "电脑赢了!";
}
}
document.getElementById('play').addEventListener('click', function() {
const playerChoice = document.querySelector('input[name="player"]:checked').value;
const computerChoice = getComputerChoice();
const result = determineWinner(playerChoice, computerChoice);
document.querySelector('.result').textContent = result;
});
</script>
</body>
</html>
这段代码实现了一个简单的石头剪刀布游戏。用户通过点击页面上的“出招”按钮开始游戏,并从三个选项(石头、剪刀和布)中选择。随后,计算机会随机选择一个选项,并比较双方的选择以决定输赢。结果会立即显示在页面上。
评论已关闭