python 人机猜拳游戏
时间: 2023-06-28 16:06:39 浏览: 130
python实现人机猜拳小游戏
好的,以下是一个简单的Python人机猜拳游戏代码:
```python
import random
def get_computer_choice():
"""随机生成电脑的选择"""
choices = ["rock", "paper", "scissors"]
return random.choice(choices)
def get_user_choice():
"""获取用户的选择"""
choice = input("请出拳(rock/paper/scissors):")
while choice not in ["rock", "paper", "scissors"]:
choice = input("无效的选择,请重新出拳(rock/paper/scissors):")
return choice
def who_wins(user_choice, computer_choice):
"""判断胜负"""
if user_choice == computer_choice:
return "平局!"
elif user_choice == "rock":
if computer_choice == "paper":
return "你输了!"
else:
return "你赢了!"
elif user_choice == "paper":
if computer_choice == "scissors":
return "你输了!"
else:
return "你赢了!"
elif user_choice == "scissors":
if computer_choice == "rock":
return "你输了!"
else:
return "你赢了!"
# 主程序
print("欢迎来到人机猜拳游戏!")
while True:
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("你出了:", user_choice)
print("电脑出了:", computer_choice)
print(who_wins(user_choice, computer_choice))
play_again = input("再来一局吗?(y/n):")
if play_again.lower() != "y":
break
print("游戏结束,谢谢参与!")
```
运行代码,即可开始游戏。
阅读全文