用python写一个剪刀石头布小游戏
时间: 2023-07-18 18:46:59 浏览: 99
好的,下面是一个简单的剪刀石头布小游戏的Python代码:
```python
import random
# 定义游戏规则
rules = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
while True:
# 获取用户输入
user_choice = input("Please choose rock, scissors, or paper: ")
# 判断用户输入是否合法
if user_choice not in rules:
print("Invalid input, please try again.")
continue
# 电脑随机出拳
computer_choice = random.choice(['rock', 'scissors', 'paper'])
# 输出电脑出拳结果
print(f"The computer chooses {computer_choice}.")
# 判断胜负
if user_choice == computer_choice:
print("Tie!")
elif rules[user_choice] == computer_choice:
print("You win!")
else:
print("You lose!")
# 询问用户是否继续游戏
play_again = input("Do you want to play again? (y/n) ")
if play_again.lower() != 'y':
break
```
运行代码后,你可以选择剪刀、石头或布,电脑也会随机出拳,然后判断胜负,最后询问你是否继续游戏。
阅读全文