Python使用随机数模拟剪刀(1)、石头(2)、布(3)游戏,采用五局三胜制。 提示:使用random.randint(1.3)生成随机数
时间: 2024-10-19 18:05:31 浏览: 22
在Python中,我们可以创建一个简单的函数来模拟石头、剪刀、布游戏。这里我们假设玩家输入的是数字1代表剪刀,2代表石头,3代表布。每轮游戏都会随机选择电脑的选项,并通过`random.randint()`函数生成1到3之间的整数表示电脑的选择。
```python
import random
def game(player_choice):
# 定义电脑随机选择
computer_choices = [1, 2, 3]
for _ in range(5): # 五局三胜制
computer_choice = random.randint(1, 3)
print(f"Player chose {player_choice}, Computer chose {computer_choice}")
if player_choice == computer_choice:
print("It's a tie!")
elif (player_choice == 1 and computer_choice == 3) or \
(player_choice == 2 and computer_choice == 1) or \
(player_choice == 3 and computer_choice == 2):
print("You win this round!")
else:
print("Computer wins this round!")
if sum([1 for _ in range(3) if _ == player_choice]) >= 3: # 玩家赢得三局
print("Congratulations! You win the game!")
return
elif sum([1 for _ in range(3) if _ == computer_choice]) >= 3: # 电脑赢得三局
print("Sorry, you lose.")
return
# 示例玩家输入
play_again = input("Do you want to play again? (y/n): ")
if play_again.lower() == 'y':
game(int(input("Enter your choice (1 for rock, 2 for paper, 3 for scissors): ")))
```
在这个示例中,每次循环代表一局游戏,如果玩家连续赢得三局或电脑连续赢得三局,游戏结束。如果你想继续玩,可以询问用户是否愿意再次开始。
阅读全文