制作一个简单的猜拳游戏,你可以使用Python的`random`模块来生成电脑的随机选择,并使用`if-else`语句来判断胜负。以下是一个基本的猜拳游戏实现示例:
import randomdef get_user_choice():while True:user_input = input("请输入你的猜拳数字(石头:1,剪刀:2,布:3): ")if user_input in ['1', '2', '3']:return int(user_input)else:print("无效输入,请重新输入。")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 == 2) or \(user_choice == 2 and computer_choice == 3) or \(user_choice == 3 and computer_choice == 1):return "你赢了"else:return "电脑赢了"def play_game():print("欢迎来到猜拳游戏!")user_choice = get_user_choice()computer_choice = get_computer_choice()print(f"你选择了:{user_choice}")print(f"电脑选择了:{computer_choice}")result = determine_winner(user_choice, computer_choice)print(result)if __name__ == "__main__":play_game()
这个程序首先定义了几个函数来获取用户的输入、生成电脑的随机选择,并判断胜负。然后在`play_game`函数中组织游戏的流程,并调用这些函数来执行游戏。
你可以运行这段代码,与电脑进行一次简单的猜拳游戏。如果需要更复杂的功能,比如多个电脑对手、游戏统计等,你可以在此基础上进行扩展

