Python实现猜拳游戏(用函数)
时间: 2024-05-24 10:07:54 浏览: 91
好的,下面是Python实现猜拳游戏的示例代码,其中使用了函数实现猜拳过程:
```
import random
def get_computer_choice():
"""电脑随机出拳"""
choices = ['石头', '剪刀', '布']
return random.choice(choices)
def get_user_choice():
"""用户输入出拳"""
while True:
choice = input('请输入你的出拳(石头/剪刀/布):')
if choice in ['石头', '剪刀', '布']:
return choice
else:
print('输入错误,请重新输入!')
def judge(user_choice, computer_choice):
"""判断胜负"""
if user_choice == computer_choice:
return 0 # 平局
elif (user_choice == '石头' and computer_choice == '剪刀') or \
(user_choice == '剪刀' and computer_choice == '布') or \
(user_choice == '布' and computer_choice == '石头'):
return 1 # 用户胜利
else:
return -1 # 用户失败
def play_game():
"""主函数,用于控制游戏流程"""
win_count = 0
lose_count = 0
draw_count = 0
while True:
# 获取用户和电脑的出拳
user_choice = get_user_choice()
computer_choice = get_computer_choice()
# 输出结果
print(f'你出了{user_choice},电脑出了{computer_choice}。')
result = judge(user_choice, computer_choice)
if result == 1:
print('恭喜你,你赢了!')
win_count += 1
elif result == -1:
print('很遗憾,你输了。')
lose_count += 1
else:
print('平局。')
draw_count += 1
# 输出统计信息
print(f'当前成绩:{win_count}胜{lose_count}负{draw_count}平。')
# 是否继续游戏
if input('是否继续游戏?(Y/N)').lower() != 'y':
break
# 开始游戏
play_game()
```
阅读全文