python猜拳游戏简单代码
作者:野牛程序员:2023-07-25 12:46:03python阅读 2776
下面是一个简单的Python猜拳游戏代码,可以与计算机进行猜拳比赛:
import random
def get_user_choice():
user_choice = input("请选择:剪刀(1) 石头(2) 布(3): ")
while user_choice not in ['1', '2', '3']:
print("请选择有效的选项!")
user_choice = input("请选择:剪刀(1) 石头(2) 布(3): ")
return int(user_choice)
def get_computer_choice():
return random.randint(1, 3)
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return "平局"
elif (user_choice == 1 and computer_choice == 3) or (user_choice == 2 and computer_choice == 1) or (user_choice == 3 and computer_choice == 2):
return "你赢了!"
else:
return "计算机赢了!"
def main():
print("欢迎来到猜拳游戏!")
while True:
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print(f"你的选择: {user_choice}, 计算机的选择: {computer_choice}")
result = determine_winner(user_choice, computer_choice)
print(result)
play_again = input("再玩一局?(y/n): ")
if play_again.lower() != 'y':
break
if __name__ == "__main__":
main()运行代码后,可以根据提示输入你的选择,然后与计算机进行比较,看看谁赢得了这一局。玩家选择剪刀、石头或布(1、2、3分别代表),计算机随机选择其中之一,并确定胜负。你可以选择是否再玩一局。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:python输入身份证号输出出生年月
- 下一篇:python定义一个求阶乘的递归函数
