下面是一个简单的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 =2024澳门今晚开什么号码07期= 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分别代表),计算机随机选择其中之一,并确定胜负。你可以选择是否再玩一局。