人机交互石头剪刀布python源代码
时间: 2023-06-28 21:05:51 浏览: 122
以下是一个简单的人机交互石头剪刀布的 Python 源代码:
```python
import random
choices = ["rock", "paper", "scissors"]
while True:
# 让用户输入他们的选择
user_choice = input("Choose rock, paper, or scissors: ")
# 随机选择计算机的选择
computer_choice = random.choice(choices)
# 打印计算机的选择
print("The computer chose", computer_choice)
# 检查谁赢了
if user_choice == computer_choice:
print("Tie!")
elif user_choice == "rock":
if computer_choice == "paper":
print("You lose!")
else:
print("You win!")
elif user_choice == "paper":
if computer_choice == "scissors":
print("You lose!")
else:
print("You win!")
elif user_choice == "scissors":
if computer_choice == "rock":
print("You lose!")
else:
print("You win!")
else:
print("Invalid input. Try again.")
# 询问是否再玩一次
play_again = input("Play again? (y/n): ")
if play_again.lower() != "y":
break
```
此代码循环运行,直到用户选择退出。它要求用户输入他们的选择,然后通过从列表中随机选择计算机的选择来模拟计算机的选择。然后,它检查哪个选择赢得了比赛,并打印出相应的消息。最后,它询问用户是否要再次玩游戏。
阅读全文