编写一个程序模拟剪刀石头布的游戏,程序启动后会随机生成0~2的随机数,分别代表剪刀、石头和布,玩家通过键盘输入剪刀、石头和布,与电脑进行3轮的比赛,赢的次数多的一方为赢家。若三局皆为平局,则最终结果判为平局。
时间: 2024-12-23 13:15:48 浏览: 21
你可以使用Python编写这样的游戏。首先,我们需要导入random库来生成随机数,并定义三个常量表示剪刀、石头和布。然后,我们可以创建一个函数来获取玩家的选择,再创建一个函数来判断胜负。最后,在主循环中进行三次游戏并记录结果。以下是一个简单的示例:
```python
import random
# 定义游戏选项
choices = {'0': '剪刀', '1': '石头', '2': '布'}
def get_player_choice():
while True:
player_input = input("请输入你的选择(0-剪刀, 1-石头, 2-布): ")
if player_input.isdigit() and int(player_input) in choices:
return player_input
print("无效输入,请重新选择。")
def game_round():
# 电脑随机出拳
computer_choice = random.randint(0, 2)
# 打印双方选择
print(f"你选择了{choices[player_choice]}")
print(f"电脑选择了{choices[computer_choice]}")
# 判断胜负
if (player_choice == '0' and computer_choice == '2') or \
(player_choice == '1' and computer_choice == '0') or \
(player_choice == '2' and computer_choice == '1'):
print("你赢了!")
elif player_choice == computer_choice:
print("平局!")
else:
print("电脑赢了!")
def play_three_rounds():
rounds = 3
wins = {player: 0 for player in choices}
for _ in range(rounds):
game_round()
wins[get_player_choice()] += 1
if all(wins.values()):
print("平局!")
else:
winner = max(wins, key=wins.get)
print(f"{winner}赢得了比赛!")
play_three_rounds()
```
阅读全文