如何在Python中编写一个简单的实现这个规则的程序?
时间: 2024-09-27 08:02:33 浏览: 28
在Python中,你可以使用random模块来生成随机数,并通过条件语句来判断胜负。以下是一个简单的实现示例:
```python
import random
def play_game(player_choice):
choices = [0, 1, 2] # 列出所有可能的选择
computer_choice = random.choice(choices) # 计算机随机选择
if player_choice == computer_choice:
result = "平局"
elif (player_choice == 0 and computer_choice == 2) or \
(player_choice == 1 and computer_choice == 0) or \
(player_choice == 2 and computer_choice == 1): # 判断胜负
result = "你赢了"
else:
result = "你输了"
print(f"你选择了{choices[player_choice]}, 电脑选择了{choices[computer_choice]}, 结果是{result}")
# 用户输入他们的选择
player_input = int(input("请输入你的选择(0剪刀,1石头,2布):"))
play_game(player_input)
```
运行这个程序,每次都会模拟一次石头-剪刀-布游戏,根据用户的输入和电脑的随机选择显示结果。
阅读全文