Python人机猜拳游戏
时间: 2023-12-25 11:29:11 浏览: 106
以下是一个Python实现的人机猜拳游戏的例子:
```python
import random
def get_user_choice():
print("请选择要出的招式(输入数字):")
print("1、石头 2、剪刀 3、布")
choice = int(input("用户出: "))
return choice
def get_computer_choice():
return random.randint(1, 3)
def get_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "平局"
elif (user_choice == 1 and computer_choice == 2) or (user_choice == 2 and computer_choice == 3) or (user_choice == 3 and computer_choice == 1):
return "用户赢"
else:
return "计算机赢"
def play_game():
user_wins = 0
computer_wins = 0
while user_wins < 2 and computer_wins < 2:
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("用户出:", user_choice)
print("计算机出:", computer_choice)
result = get_winner(user_choice, computer_choice)
if result == "用户赢":
user_wins += 1
elif result == "计算机赢":
computer_wins += 1
print(result)
if user_wins > computer_wins:
print("恭喜用户取得胜利!")
else:
print("恭喜计算机取得胜利!")
play_game()
```
阅读全文