python人机猜拳游戏代码
时间: 2023-07-09 14:42:41 浏览: 124
好的,以下是一个简单的Python人机猜拳游戏代码:
```python
import random
print("欢迎来到猜拳游戏!")
# 定义猜拳中的手势
hands = ["石头", "剪刀", "布"]
# 定义玩家胜利次数和电脑胜利次数
player_wins = 0
computer_wins = 0
while True:
# 玩家选择手势
player_hand = input("请输入石头、剪刀或布,或者输入 q 退出游戏:")
if player_hand == "q":
break
elif player_hand not in hands:
print("请输入有效的指令!")
continue
# 电脑随机选择手势
computer_hand = random.choice(hands)
print("电脑选择了:", computer_hand)
# 判断胜负
if player_hand == computer_hand:
print("平局!")
elif (player_hand == "石头" and computer_hand == "剪刀") or (player_hand == "剪刀" and computer_hand == "布") or (player_hand == "布" and computer_hand == "石头"):
print("恭喜你,你赢了!")
player_wins += 1
else:
print("很遗憾,你输了。")
computer_wins += 1
# 游戏结束,输出结果
print("游戏结束,你赢了", player_wins, "局,电脑赢了", computer_wins, "局。")
```
这个代码通过循环不断进行猜拳游戏,直到玩家输入 q 退出游戏。玩家和电脑随机选择手势,然后比较胜负,统计胜利次数,最后输出结果。
阅读全文