python编写程序实现人与计算机的猜拳游戏
时间: 2024-11-13 09:41:07 浏览: 31
在Python中编写一个人机猜拳游戏可以使用if-elif-else结构来模拟玩家和电脑的选择,并通过随机数生成来模拟电脑的决策。通常,猜拳游戏有三种选择:“石头”、“剪刀”和“布”,规则是这样的:
- 石头打剪刀,剪刀剪布,布包石头。
- 如果双方出同样的选择,则平局。
下面是一个简单的猜拳游戏实现示例:
```python
import random
def computer_choice():
choices = ["石头", "剪刀", "布"]
return random.choice(choices)
def get_player_choice():
player_choice = input("请输入你的选择(石头、剪刀或布):")
while player_choice not in ("石头", "剪刀", "布"):
player_choice = input("无效的选择,请重新输入:")
return player_choice
def play_game(player, computer):
if player == computer:
print(f"平局!你出了{player},电脑也出了{computer}")
elif (player == "石头" and computer == "剪刀") or \
(player == "剪刀" and computer == "布") or \
(player == "布" and computer == "石头"):
print(f"你赢了!你出了{player},电脑出了{computer}")
else:
print(f"电脑赢了!你出了{player},电脑出了{computer}")
# 主循环
while True:
player_choice = get_player_choice()
computer_choice = computer_choice()
print(f"你出了{player_choice},电脑出了{computer_choice}")
play_game(player_choice, computer_choice)
continue_game = input("还想再来一局吗?(y/n): ")
if continue_game.lower() != 'y':
break
```
阅读全文