石头-剪刀-布(Rock-Paper-Scissors,简称RPS)是一种简单的手势游戏,通常在两个人之间进行。每个玩家同时选择一个手势:石头、剪刀或布。游戏规则如下:
以下是一个简单的HTML和JavaScript示例,展示如何通过按钮提示用户输入某些轮次的石头-剪刀-布游戏。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock-Paper-Scissors Game</title>
</head>
<body>
<h1>Rock-Paper-Scissors Game</h1>
<p>Choose your move:</p>
<button onclick="playRound('rock')">Rock</button>
<button onclick="playRound('paper')">Paper</button>
<button onclick="playRound('scissors')">Scissors</button>
<p id="result"></p>
<script>
function playRound(playerChoice) {
const choices = ['rock', 'paper', 'scissors'];
const computerChoice = choices[Math.floor(Math.random() * choices.length)];
let result;
if (playerChoice === computerChoice) {
result = "It's a tie!";
} else if (
(playerChoice === 'rock' && computerChoice === 'scissors') ||
(playerChoice === 'scissors' && computerChoice === 'paper') ||
(playerChoice === 'paper' && computerChoice === 'rock')
) {
result = "You win!";
} else {
result = "You lose!";
}
document.getElementById('result').innerText = `You chose ${playerChoice}, Computer chose ${computerChoice}. ${result}`;
}
</script>
</body>
</html>
Math.random()
来生成随机数。通过以上示例和解释,你应该能够实现一个基本的石头-剪刀-布游戏,并解决常见的技术问题。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云