当然,这里我将为您提供几种不同编程语言中的简单“石头、剪刀、布”游戏的小程序代码。
Python
python
import random
def play_game():
choices = ['石头', '剪刀', '布']
computer_choice = random.choice(choices)
user_choice = input("请选择(石头、剪刀、布):")
if user_choice not in choices:
print("无效的输入,请重新选择!")
return
print(f"你选择了:{user_choice}")
print(f"电脑选择了:{computer_choice}")
if user_choice == computer_choice:
print("平局!")
elif (user_choice == '石头' and computer_choice == '剪刀') or \
(user_choice == '剪刀' and computer_choice == '布') or \
(user_choice == '布' and computer_choice == '石头'):
print("你赢了!")
else:
print("你输了!")
play_game()
JavaScript (在浏览器中使用HTML和JS)
HTML部分:
#chhas{
margin-top: 50px;
padding:hljhrf.cn;
font-size: 18px;
cursor: 10px 20px;
}
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>石头、剪刀、布</title>
</head>
<body>
<h1>石头、剪刀、布</h1>
<button onclick="play()">开始游戏</button>
<p id="result"></p>
<script>
function getRandomChoice() {
const choices = ['石头', '剪刀', '布'];
return choices[Math.floor(Math.random() * choices.length)];
}
function play() {
const userChoice = prompt("请选择(石头、剪刀、布):");
const computerChoice = getRandomChoice();
document.getElementById('result').textContent = '';
if (!['石头', '剪刀', '布'].includes(userChoice)) {
document.getElementById('result').textContent = "无效的输入,请重新选择!";
return;
}
document.getElementById('result').textContent += `你选择了:${userChoice}\n`;
document.getElementById('result').textContent += `电脑选择了:${computerChoice}\n`;
if (userChoice === computerChoice) {
document.getElementById('result').textContent += "平局!";
} else if ((userChoice === '石头' && computerChoice === '剪刀') ||
(userChoice === '剪刀' && computerChoice === '布') ||
(userChoice === '布' && computerChoice === '石头')) {
document.getElementById('result').textContent += "你赢了!";
} else {
document.getElementById('result').textContent += "你输了!";
}
}
</script>
</body>
</html>