Python写剪刀石头布随机生成简单代码
时间: 2024-06-14 08:02:14 浏览: 161
在Python中,你可以使用`random`模块来实现剪刀-石头-布游戏的随机选择。这是一个简单的代码示例:
```python
import random
def game():
options = ["rock", "paper", "scissors"] # 定义游戏选项
player_choice = input("Choose (rock, paper, scissors): ").lower() # 获取玩家输入并转换为小写
if player_choice not in options:
print("Invalid choice! Please try again.")
return game()
computer_choice = random.choice(options) # 电脑随机选择
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!"
print(result)
# 开始游戏
game()
```
阅读全文