```python
import random
def get_computer_choice():
计算机随机选择“石头”、“剪刀”或“布”
choices = ['石头', '剪刀', '布']
return random.choice(choices)
def get_user_choice():
用户输入选择
user_input = input("请输入你的选择(石头,剪刀,布):")
while user_input not in ['石头', '剪刀', '布']:
user_input = input("输入无效,请重新输入(石头,剪刀,布):")
return user_input
def determine_winner(user_choice, computer_choice):
判断胜负
if user_choice == computer_choice:
return "平局!"
elif (user_choice == "石头" and computer_choice == "剪刀") or \
(user_choice == "剪刀" and computer_choice == "布") or \
(user_choice == "布" and computer_choice == "石头"):
return "你赢了!"
else:
return "你输了!"
游戏主循环
player_wins = 0
computer_wins = 0
n = 1
while n <= 3:
print(f"第{n}局:")
computer_choice = get_computer_choice()
print(f"计算机出的是: {computer_choice}")
user_choice = get_user_choice()
print(f"你出的是: {user_choice}")
result = determine_winner(user_choice, computer_choice)
print(result)
if result == "你赢了!":
player_wins += 1
elif result == "计算机赢了!":
computer_wins += 1
n += 1
if player_wins == 2:
print("恭喜你赢得了三局两胜制比赛!")
elif computer_wins == 2:
print("很遗憾,计算机赢得了三局两胜制比赛。")
else:
print("比赛平局,需要进行下一局。")
```
代码说明:
导入random模块:
用于生成随机数。
get_computer_choice():
计算机随机选择“石头”、“剪刀”或“布”。
get_user_choice():
用户输入选择,并进行合法性检查。
determine_winner(user_choice, computer_choice):
根据用户和计算机的选择判断胜负。
游戏主循环:
进行三局比赛,记录每局的胜负,最后判断总胜负。
你可以将上述代码复制到Python环境中运行,体验猜拳游戏的三局两胜制。