利用random标准库,完成人机石头剪刀布的游戏,三局两胜
时间: 2024-10-08 14:14:55 浏览: 25
python石头剪刀布小游戏(三局两胜制)
5星 · 资源好评率100%
在Python中,你可以利用`random`库来模拟随机选择石头、剪刀或布的手势。这里是一个简单的例子,展示如何编写一个三局两胜的人机石头剪刀布游戏:
```python
import random
# 定义游戏选项
options = ['rock', 'paper', 'scissors']
def game_round(player_choice):
computer_choice = random.choice(options)
print(f"Player chose: {player_choice}")
print(f"Computer chose: {computer_choice}")
if player_choice == computer_choice:
result = "It's a tie!"
elif (player_choice == 'rock' and computer_choice == 'scissors') or \
(player_choice == 'paper' and computer_choice == 'rock') or \
(player_choice == 'scissors' and computer_choice == 'paper'):
result = "You win!"
else:
result = "Computer wins!"
return result
def play_game():
for round_num in range(1, 4):
print(f"Round {round_num}:")
player_input = input("Enter your choice (rock/paper/scissors): ")
while player_input not in options:
print("Invalid choice! Please try again.")
player_input = input()
outcome = game_round(player_input)
print(outcome)
if round_num == 2:
# 如果已经打完两局,判断胜负
if outcome == "You win!" * 2:
print("Congratulations! You've won the game!")
break
elif outcome == "Computer wins!" * 2:
print("Sorry, you lost. Better luck next time!")
break
else:
print("Let's continue to the final round!")
play_game()
```
在这个程序中,玩家输入他们的选择,电脑随机选择,然后根据规则判断胜负。如果到了第二局结束,会直接宣布结果。
阅读全文