|
|
这个优化版确实比基础版强了不少,咱们来一起看看它“优化”在哪里~
- 增加了上下限常量:用LOWER_BOUND和UPPER_BOUND来定义范围,改起来方便,代码也更清晰。
- 把判断逻辑封装成函数check_guess,主逻辑更简洁,也便于复用。
- 限制了猜测次数max_attempts = 10,让游戏更有挑战性,不会无限猜下去。
- 加入了try...except处理输入异常,输字母或小数不会直接报错崩溃,提示用户重新输入。
- 每次猜完都会提示剩余次数,最后还会公布正确答案,用户体验更好。
- 使用了f-string格式化输出,代码更简洁,字符串拼接更直观。
所以说,这个版本在代码结构、输入健壮性、游戏体验三个方面都做了优化,已经是一个完整又好玩的小项目啦!
- 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~ ")
复制代码
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|