运用python书写一个石头剪刀布游戏的代码
时间: 2024-09-18 17:01:54 浏览: 42
当然可以,下面是一个简单的Python代码示例,用于创建一个石头、剪刀、布(Rock-Paper-Scissors)的游戏:
```python
import random
def game():
choices = ['石头', '剪刀', '布']
player_choice = input("请输入你的选择 (石头, 剪刀, 布): ")
if player_choice not in choices:
print("无效的选择,请重新输入!")
return game()
computer_choice = random.choice(choices)
print(f"你选择了: {player_choice}, 计算机选择了: {computer_choice}.")
if player_choice == computer_choice:
result = "平局!"
elif (player_choice == '石头' and computer_choice == '剪刀') or \
(player_choice == '剪刀' and computer_choice == '布') or \
(player_choice == '布' and computer_choice == '石头'):
result = "你赢了!"
else:
result = "计算机赢了!"
print(result)
game()
```
在这个程序中,玩家通过输入选择他们的选项,然后电脑随机生成一个选择。程序会判断胜负并显示结果。如果你想要玩一轮游戏,只需运行`game()`函数即可。
阅读全文