以下是用 Python 写一个经典「猜数字游戏」的完整教学示例,适合 Python 基础课程使用。
我们会从最简单版本开始,一步一步增加功能,最后给出几个进阶练习方向。
版本 1:最基础版(适合第 1~2 次课)
# 猜数字游戏 – 版本1
import random
# 电脑随机生成一个 1~100 的数字
secret_number = random.randint(1, 100)
guess_count = 0
print("欢迎来到猜数字游戏!")
print("我已经想好了一个 1 到 100 之间的整数,你来猜猜看~")
while True:
# 获取玩家输入
guess = input("请输入你猜的数字:")
# 输入检查:必须是数字
if not guess.isdigit():
print("请输入正确的数字哦~")
continue
guess = int(guess)
guess_count += 1
if guess == secret_number:
print(f"恭喜你!猜对了~ 就是 {secret_number}")
print(f"你一共猜了 {guess_count} 次")
break
elif guess < secret_number:
print("太小了,再大一点~")
else:
print("太大了,再小一点~")
特点:
- 使用 while True 无限循环
- 基本的输入验证
- 简单的比较逻辑
- 记录猜测次数
版本 2:增加难度选择 & 猜测次数限制(适合第 3~5 次课)
# 猜数字游戏 – 版本2(难度选择 + 次数限制)
import random
print("=== 猜数字游戏 ===")
print("请选择难度:")
print("1. 简单 (1~50,10次机会)")
print("2. 普通 (1~100,8次机会)")
print("3. 困难 (1~200,6次机会)")
while True:
level = input("请输入难度编号 (1/2/3):")
if level in ['1','2','3']:
level = int(level)
break
print("请输入 1、2 或 3")
if level == 1:
max_num = 50
max_attempts = 10
elif level == 2:
max_num = 100
max_attempts = 8
else:
max_num = 200
max_attempts = 6
secret_number = random.randint(1, max_num)
attempts_left = max_attempts
print(f"\\n游戏开始!我已经想好了一个 1 到 {max_num} 的数字")
print(f"你一共有 {max_attempts} 次机会\\n")
while attempts_left > 0:
guess = input(f"剩余 {attempts_left} 次机会,请输入数字:")
if not guess.isdigit():
print("请输入数字!")
continue
guess = int(guess)
if guess == secret_number:
print(f"\\n太棒了!猜对了~ 就是 {secret_number}")
print(f"你用了 {max_attempts – attempts_left + 1} 次机会")
break
elif guess < secret_number:
print("太小了!")
else:
print("太大了!")
attempts_left -= 1
if attempts_left == 0:
print(f"\\n游戏结束!正确答案是:{secret_number}")
新增内容:
- 难度选择(用 if-elif)
- 次数限制机制
- 剩余次数提示
- 游戏结束两种情况的处理
版本 3:更完整的版本(加入重玩功能、历史记录)
# 猜数字游戏 – 版本3(可重玩 + 历史最佳)
import random
import time
def play_game():
print("\\n" + "="*40)
print(" 猜数字游戏 – 开始新一轮!")
print("="*40)
level = input("选择难度 (1:简单 2:普通 3:困难):")
if level == '1':
max_n, max_t = 50, 10
elif level == '2':
max_n, max_t = 100, 8
else:
max_n, max_t = 200, 6
secret = random.randint(1, max_n)
attempts = 0
start_time = time.time()
print(f"\\n已生成 1~{max_n} 的数字,你有 {max_t} 次机会")
while attempts < max_t:
try:
guess = int(input(f"第 {attempts+1} 次猜测:"))
except ValueError:
print("请输入整数!")
continue
attempts += 1
if guess == secret:
used_time = round(time.time() – start_time, 2)
print(f"\\n★ 恭喜!猜对了!就是 {secret}")
print(f"用时 {used_time} 秒,共 {attempts} 次猜测")
return attempts, used_time
elif guess < secret:
print("太小了 ↑")
else:
print("太大了 ↓")
print(f"\\n很遗憾,次数用完。正确答案是:{secret}")
return None, None
# 主程序 – 支持多轮游戏
best_attempts = float('inf')
best_time = float('inf')
while True:
attempts, used_time = play_game()
if attempts is not None:
if attempts < best_attempts:
best_attempts = attempts
best_time = used_time
print("→ 新纪录!")
elif attempts == best_attempts and used_time < best_time:
best_time = used_time
print("→ 用时新纪录!")
print(f"\\n当前最佳:{best_attempts} 次,{best_time:.2f} 秒")
again = input("\\n再玩一次?(y/n):").lower()
if again != 'y':
print("感谢游玩!再见~")
break
进阶练习方向(可作为课后作业)
你现在想直接运行哪个版本? 或者你希望我帮你把某个版本改成图形界面(tkinter)版本? 也可以告诉我你的教学进度/学生水平,我可以调整难度和讲解重点。
网硕互联帮助中心





评论前必须登录!
注册