用python编写用函数来写一个和电脑玩一个剪刀石头布的游戏
时间: 2024-11-30 19:14:34 浏览: 23
当然,我们可以创建一个简单的函数来模拟剪刀、石头、布游戏。这里是一个基本的示例,它接收用户的选择(0代表石头,1代表剪刀,2代表布),然后随机生成计算机的选择,并判断胜负情况:
```python
import random
def play_game():
choices = ['rock', 'paper', 'scissors']
user_choice = int(input("请输入你的选择(0:石头,1:剪刀,2:布):"))
while user_choice not in [0, 1, 2]:
print("无效的选择,请重新输入!")
user_choice = int(input())
computer_choice = random.randint(0, 2)
print("你选择了:", choices[user_choice])
print("电脑选择了:", choices[computer_choice])
if user_choice == computer_choice:
result = "平局"
elif (user_choice == 0 and computer_choice == 2) or \
(user_choice == 1 and computer_choice == 0) or \
(user_choice == 2 and computer_choice == 1):
result = "你赢了!"
else:
result = "你输了!"
print(f"结果是:{result}")
play_game()
```
当你运行这个函数后,它会提示你输入选择,然后根据你的输入和电脑随机的选择决定胜负。如果想继续玩游戏,只需再次调用 `play_game()` 函数。
阅读全文