实现了剪刀石头布的游戏。在这个游戏中,计算机会随机选择剪刀、石头或布,然后用户会输入他们的选择。之后,程序会决定谁是赢家。
import random
def get_computer_choice():
choices = ['剪刀', '石头', '布']
return random.choice(choices)
def get_user_choice():
choice = input("请输入你的选择(剪刀、石头、布):")
while choice not in ['剪刀', '石头', '布']:
choice = input("无效输入,请输入你的选择(剪刀、石头、布):")
return choice
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 '电脑赢了'
def play_game():
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)
# 开始游戏
play_game()
在这个程序中,我们首先定义了三个函数:get_computer_choice
、get_user_choice
和 determine_winner
。get_computer_choice
函数用于获取电脑的选择,它是从剪刀、石头、布中随机选择的。get_user_choice
函数用于获取用户的选择,它会一直提示用户输入,直到用户输入了一个有效的选择(剪刀、石头或布)。determine_winner
函数用于确定游戏的赢家,它根据剪刀石头布的规则来判断。最后,我们在 play_game
函数中调用了这些函数来玩游戏,并打印出游戏的结果。