比大小游戏:石头剪刀布python
时间: 2024-10-15 07:07:10 浏览: 41
"比大小游戏",比如经典的“石头、剪刀、布”(Rock-Paper-Scissors),是一个简单的命令行交互式游戏,通常使用Python编写。在游戏中,用户和计算机随机选择手势,然后根据规则判断胜负:石头砸剪刀,剪刀剪布,布包石头。下面是一个基础版本的Python实现:
```python
import random
# 定义手势列表
gestures = ["石头", "剪刀", "布"]
def player_choice():
while True:
user_input = input("请输入你的选择(石头、剪刀、布):")
if user_input.lower() in gestures:
return user_input
else:
print("无效的选择,请重新输入。")
def computer_choice():
return random.choice(gestures)
def compare_choices(player, computer):
if player == computer:
return "平局"
elif (player == "石头" and computer == "剪刀") or \
(player == "剪刀" and computer == "布") or \
(player == "布" and computer == "石头"):
return "你赢了!"
else:
return "电脑赢了!"
def play_game():
player = player_choice()
computer = computer_choice()
result = compare_choices(player, computer)
print(f"{player} 对 {computer}, 结果是 {result}")
play_game()
```
阅读全文