鱼C论坛

 找回密码
 立即注册
查看: 18|回复: 5

[作品展示] (跟甲鱼哥学的)猜数字游戏-优化版

[复制链接]
发表于 前天 14:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import random
LOWER_BOUND = 1
UPPER_BOUND = 100
secret_number = random.randint(LOWER_BOUND, UPPER_BOUND)
print(f"Now I'm thinking about a number that ranges from {LOWER_BOUND} to {UPPER_BOUND} ")
print("Guess what it is!")

def check_guess(guess, secret):
    if guess < secret:
        return "Too small! Try a larger one~"
    elif guess > secret:
        return "Too large! Try a smaller one~"
    else:
        return "Congratulations! You've found out the corresponding number!"
attempts = 0
max_attempts = 10

print(f"You have {max_attempts} chances. Here we start!\n")

while attempts < max_attempts:
    try:
        guess = int(input("Please input your assumption: "))
    except ValueError:
        print("Invalid number! Try enter a whole number~")
        continue

    attempts += 1
   
    result = check_guess(guess, secret_number)
    print(result)
   
    if guess == secret_number:
        print(f"{attempts} times till you get the answer! Well done! ")
        break
   
    remaining = max_attempts - attempts
    if remaining > 0:
        print(f"{remaining} chances remaining~ \n")
    else:
        print("Just wasted all your chances! ")
        print(f"The secret number is {secret_number}. Try again next time~ ")
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 前天 14:04 | 显示全部楼层
鱼油写得不错!整体逻辑清晰,函数封装也很棒。这里给几个小优化建议,让代码更“甲鱼风”:


1. 边界检查  
如果用户输入的数字超出范围(比如 0101),其实可以提前提醒,不用浪费猜测次数。在 int() 转换后加个判断:


  1. if guess < LOWER_BOUND or guess > UPPER_BOUND:
  2.     print(f"Please enter a number between {LOWER_BOUND} and {UPPER_BOUND}!")
  3.     continue
复制代码


2. 输入空值处理  
用户直接回车时,input() 会得到空字符串,int() 会报错。虽然已经被 except 捕获,但可以更友好地提示“不能为空”:


  1. guess_str = input("Please input your assumption: ")
  2. if not guess_str.strip():
  3.     print("Empty input! Please enter a whole number~")
  4.     continue
复制代码


3. 减少重复判断  
当前代码里 check_guess 判断了大小,后面又用 guess == secret_number 判断是否成功。可以改为让函数返回一个元组,避免重复比较:


  1. def check_guess(guess, secret):
  2.     if guess < secret:
  3.         return False, "Too small! Try a larger one~"
  4.     elif guess > secret:
  5.         return False, "Too large! Try a smaller one~"
  6.     else:
  7.         return True, "Congratulations! You've found out the corresponding number!"
复制代码


然后在主循环里:


  1. success, message = check_guess(guess, secret_number)
  2. print(message)
  3. if success:
  4.     print(f"{attempts} times till you get the answer! Well done! ")
  5.     break
复制代码


4. 最最重要的:继续游戏  
现在一次游戏结束就退出,很不“甲鱼”。可以加一个外层循环,问用户“是否再来一局”:


  1. while True:
  2.     # 原有游戏代码...
  3.     play_again = input("Play again? (yes/no): ").strip().lower()
  4.     if play_again != "yes":
  5.         print("Bye bye~ See you next time!")
  6.         break
复制代码

整体代码结构已经很好,继续加油!记住:好代码不是写出来的,是改出来的~


以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 前天 14:18 | 显示全部楼层
这AI助理好啊
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 前天 14:18 | 显示全部楼层


代码写得很不错,看得出你确实把“优化”落到实处啦!{:5_76:}

几个亮点值得点赞:
- 用了常量 LOWER_BOUNDUPPER_BOUND,代码更易维护
- 把判断逻辑封装成 check_guess 函数,清晰又复用
- 捕获 ValueError,不怕用户乱输入
- 剩余次数提示非常友好,游戏体验很好

如果要再“优化”一点点,可以考虑:
- 增加输入范围检查,比如用户输入 101 或 0,可以提示“超出范围”
- 玩完一局后,问一句“再来一局?”,方便连玩
- 每次猜完后显示一下“当前范围”的提示,帮用户缩小范围

不过整体已经很好了,逻辑紧凑、可读性强,继续加油!{:5_148:}

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 前天 17:31 | 显示全部楼层
为了方便复制代码,在此重发一遍

  1. import random
  2. LOWER_BOUND = 1
  3. UPPER_BOUND = 100
  4. secret_number = random.randint(LOWER_BOUND, UPPER_BOUND)
  5. print(f"Now I'm thinking about a number that ranges from {LOWER_BOUND} to {UPPER_BOUND} ")
  6. print("Guess what it is!")

  7. def check_guess(guess, secret):
  8.     if guess < secret:
  9.         return "Too small! Try a larger one~"
  10.     elif guess > secret:
  11.         return "Too large! Try a smaller one~"
  12.     else:
  13.         return "Congratulations! You've found out the corresponding number!"
  14. attempts = 0
  15. max_attempts = 10

  16. print(f"You have {max_attempts} chances. Here we start!\n")

  17. while attempts < max_attempts:
  18.     try:
  19.         guess = int(input("Please input your assumption: "))
  20.     except ValueError:
  21.         print("Invalid number! Try enter a whole number~")
  22.         continue

  23.     attempts += 1
  24.    
  25.     result = check_guess(guess, secret_number)
  26.     print(result)
  27.    
  28.     if guess == secret_number:
  29.         print(f"{attempts} times till you get the answer! Well done! ")
  30.         break
  31.    
  32.     remaining = max_attempts - attempts
  33.     if remaining > 0:
  34.         print(f"{remaining} chances remaining~ \n")
  35.     else:
  36.         print("Just wasted all your chances! ")
  37.         print(f"The secret number is {secret_number}. Try again next time~ ")
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 前天 17:31 | 显示全部楼层
VIRUS_2091 发表于 2026-08-18 17:31
为了方便复制代码,在此重发一遍

import  ...


收到,代码已复制保存,方便随时参考和测试。{:5_148:} 写得很清晰,继续加油!

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-8-20 23:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表