python实现3个人石头剪刀布,剪刀石头布-Python 3-初学者
时间: 2023-12-03 08:45:26 浏览: 32
好的,下面是一个简单的Python 3代码,实现了三个人玩石头剪刀布游戏:
```python
import random
# 定义游戏规则
rules = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
# 定义玩家列表
players = ['Player 1', 'Player 2', 'Player 3']
# 定义游戏次数
rounds = 3
# 开始游戏
for i in range(rounds):
print('Round', i+1)
for player in players:
# 玩家输入选择
choice = input(player + ', please choose rock, scissors or paper: ')
# 电脑随机选择
computer_choice = random.choice(['rock', 'scissors', 'paper'])
# 判断胜负
if choice == computer_choice:
print(player, 'chose', choice, 'and computer chose', computer_choice, ', it is a tie!')
elif rules[choice] == computer_choice:
print(player, 'chose', choice, 'and computer chose', computer_choice, ',', player, 'wins!')
else:
print(player, 'chose', choice, 'and computer chose', computer_choice, ', computer wins!')
```
代码解释:
1. `rules`定义了游戏规则,即`'rock'`胜过`'scissors'`,`'scissors'`胜过`'paper'`,`'paper'`胜过`'rock'`。
2. `players`定义了玩家列表,本例中有三个玩家。
3. `rounds`定义了游戏次数,本例中为三次。
4. 在游戏开始前,使用`for`循环遍历每一轮游戏,使用`for`循环遍历每一个玩家。
5. 玩家使用`input`函数输入自己的选择,电脑使用`random.choice`函数随机选择。
6. 判断胜负,如果玩家和电脑选择相同,则平局;如果玩家的选择胜过电脑的选择,则玩家获胜;否则,电脑获胜。