用python写一个猜数字游戏
- User
用python写一个猜数字游戏
Assistant
这里是一个简单的猜数字游戏的Python实现:
import random def guess_number_game(): print("欢迎来到猜数字游戏!") print("我已经想好了一个1到100之间的数字,你来猜猜看吧!") # 生成1到100之间的随机数 secret_number = random.randint(1, 100) attempts = 0 max_attempts = 7 # 最大猜测次数 while attempts < max_attempts: try: # 获取用户输入 guess = int(input(f"\n第{attempts + 1}次猜测,请输入你的数字(1-100):")) attempts += 1 # 检查输入范围 if guess < 1 or guess > 100: print("请输入1到100之间的数字!") attempts -= 1 # 不计入错误输入的次数 continue # 判断猜测结果 if guess == secret_number: print(f"🎉 恭喜你!猜对了!答案就是{secret_number}") print(f"你总共猜了{attempts}次") break elif guess < secret_number: print("太小了!试试更大的数字") else: print("太大了!试试更小的数字") # 显示剩余次数 remaining = max_attempts - attempts if remaining > 0: print(f"还剩{remaining}次机会") except ValueError: print("请输入一个有效的数字!") attempts -= 1 # 不计入错误输入的次数 # 游戏结束 if attempts >= max_attempts and guess != secret_number: print(f"\n游戏结束!你已经用完了所有{max_attempts}次机会") print(f"正确答案是:{secret_number}") # 询问是否再玩一次 play_again = input("\n想再玩一次吗?(y/n): ").lower() if play_again == 'y' or play_again == 'yes': guess_number_game() else: print("谢谢游戏!再见!") # 启动游戏 if __name__ == "__main__": guess_number_game()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.