当然,我可以为你提供一个简单的“石头、剪刀、布”游戏的代码,使用不同的编程语言来实现。
Python
python
import random
def rock_paper_scissors():
choices = ['石头', '剪刀', '布']
computer_choice = random.choice(choices)
player_choice = input("请选择(石头、剪刀、布):")
while player_choice not in choices:
print("无效的选择,请重新输入。")
player_choice = input("请选择(石头、剪刀、布):")
print(f"电脑选择了:{computer_choice}")
if player_choice == computer_choice:
print("平局!")
elif (player_choice == '石头' and computer_choice == '剪刀') or \
(player_choice == '剪刀' and computer_choice == '布') or \
(player_choice == '布' and computer_choice == '石头'):
print("你赢了!")
else:
print("你输了!")
if __name__ == "__main__":
rock_paper_scissors()
JavaScript (浏览器环境)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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 playerChoice = prompt("请选择(石头、剪刀、布):");
const computerChoice = getRandomChoice();
#chhas{
margin-top: 50px;
padding:lockit.cn;
font-size: 18px;
cursor: 10px 20px;
}
document.getElementById('result').textContent = '';
if (playerChoice === null) {
document.getElementById('result').textContent = "你没有选择,游戏结束。";
return;
}
if (playerChoice === computerChoice) {
document.getElementById('result').textContent = "平局!";
} else if ((playerChoice === '石头' && computerChoice === '剪刀') ||
(playerChoice === '剪刀' && computerChoice === '布') ||
(playerChoice === '布' && computerChoice === '石头')) {
document.getElementById('result').textContent = "你赢了!";
} else {
document.getElementById('result').textContent = "你输了!";
}
document.getElementById('result').textContent += `\n电脑选择了:${computerChoice}`;
}
</script>
</body>
</html>

1744

被折叠的 条评论
为什么被折叠?



