人机猜拳游戏代码python
时间: 2024-03-16 15:40:15 浏览: 102
python实现人机猜拳小游戏
5星 · 资源好评率100%
当然,我可以给你介绍一下人机猜拳游戏的Python代码。以下是一个简单的示例:
```python
import random
def get_user_choice():
choice = input("请选择(剪刀/石头/布):")
while choice not in ["剪刀", "石头", "布"]:
choice = input("请选择(剪刀/石头/布):")
return choice
def get_computer_choice():
choices = ["剪刀", "石头", "布"]
return random.choice(choices)
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "平局"
elif (user_choice == "剪刀" and computer_choice == "布") or (user_choice == "石头" and computer_choice == "剪刀") or (user_choice == "布" and computer_choice == "石头"):
return "用户胜利"
else:
return "计算机胜利"
def play_game():
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("用户选择:", user_choice)
print("计算机选择:", computer_choice)
winner = determine_winner(user_choice, computer_choice)
print("结果:", winner)
play_game()
```
这个代码实现了一个简单的人机猜拳游戏。用户通过输入选择剪刀、石头或布,计算机随机生成一个选择,然后根据规则判断胜负并输出结果。
阅读全文