一、游戏规则与开发目标
猜数字游戏是经典的逻辑互动游戏,规则简单易懂:系统随机生成1-100之间的整数,玩家通过输入猜测的数字,系统会根据猜测结果给出"太大"或"太小"的提示,直到猜中正确数字。本教程将带领大家从零开始,用Python实现这个经典游戏,最终目标包含:
- 完整的游戏流程控制
- 友好的人机交互界面
- 输入验证与错误处理
- 猜测次数统计功能
- 重新开始游戏选项
二、开发环境准备
2.1 基础工具清单
Python 3.x 解释器(建议3.6+版本)
代码编辑器(VS Code/PyCharm/Sublime Text任选)
终端(Windows系统可使用CMD/PowerShell,Mac/Linux使用Terminal)
2.2 环境验证代码
新建game_test.py文件,输入以下代码:
lua
print("欢迎来到Python游戏开发世界!")
input("按下回车键继续...")
在终端执行python game_test.py,若看到欢迎语并能通过回车键退出,则表示环境配置成功。
三、核心功能实现
3.1 生成随机数
Python标准库random提供了生成随机数的功能:
scss
import random
secret_number = random.randint(1, 100)
print("(调试用)当前答案:", secret_number) # 开发时用于测试
randint(a, b)函数会生成[a, b]区间内的闭区间整数。
3.2 获取用户输入
使用input()函数接收用户输入,并进行类型转换:
guess = int(input("请输入你猜的数字(1-100):"))
需要处理非数字输入的情况,后续会完善错误处理机制。
3.3 核心比较逻辑
通过if-elif-else结构实现判断:
bash
if guess > secret_number:
print("太大了!")
elif guess < secret_number:
print("太小了!")
else:
print("恭喜你,猜中了!")
四、游戏流程控制
4.1 添加循环结构
使用while循环实现持续猜测:
ini
attempts = 0
max_attempts = 10
while attempts < max_attempts:
guess = int(input("..."))
# 比较逻辑
attempts += 1
4.2 输入验证增强
添加异常处理防止程序崩溃:
python
try:
guess = int(input("请输入数字:"))
if guess < 1 or guess > 100:
print("请输入1-100之间的数字!")
continue
except ValueError:
print("请输入有效数字!")
continue
4.3 完整游戏循环
整合后的核心游戏循环:
python
import random
secret_number = random.randint(1, 100)
attempts = 0
max_attempts = 10
print("欢迎来到猜数字游戏!")
print(f"数字范围1-100,你共有{max_attempts}次机会")
while attempts < max_attempts:
try:
guess = int(input("\n请输入你猜的数字:"))
if guess < 1 or guess > 100:
print("数字超出范围!")
continue
attempts += 1
remaining = max_attempts - attempts
if guess > secret_number:
print(f"太大了!剩余次数:{remaining}")
elif guess < secret_number:
print(f"太小了!剩余次数:{remaining}")
else:
print(f"恭喜!你用了{attempts}次猜中数字{secret_number}!")
break
if remaining == 0:
print(f"\n次数用尽!正确答案是:{secret_number}")
except ValueError:
print("请输入有效数字!")
五、用户体验优化
5.1 添加颜色输出
使用ANSI转义码实现彩色提示:
ini
RED = "\033[31m"
GREEN = "\033[32m"
RESET = "\033[0m"
print(f"{RED}太大了!{RESET}剩余次数:{remaining}")
5.2 难度选择功能
通过函数封装实现难度切换:
python
def set_difficulty():
print("请选择难度:")
print("1. 简单(1-100,15次)")
print("2. 普通(1-50,10次)")
print("3. 困难(1-20,5次)")
while True:
choice = input("请输入选项(1-3):")
if choice == '1':
return (1, 100, 15)
elif choice == '2':
return (1, 50, 10)
elif choice == '3':
return (1, 20, 5)
print("无效输入,请重新选择!")
# 使用示例
min_num, max_num, max_attempts = set_difficulty()
secret_number = random.randint(min_num, max_num)
5.3 游戏历史记录
使用文件存储游戏记录:
scss
import json
from pathlib import Path
def load_history():
history_file = Path("game_history.json")
if history_file.exists():
return json.loads(history_file.read_text())
return {"best_score": 999, "total_games": 0}
def save_history(best_score, total_games):
history = {
"best_score": min(best_score, load_history()["best_score"]),
"total_games": total_games + 1
}
Path("game_history.json").write_text(json.dumps(history))
# 在游戏结束后调用
save_history(attempts, history["total_games"])
六、完整游戏代码
python
import random
import json
from pathlib import Path
# 配置颜色常量
RED = "\033[31m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
RESET = "\033[0m"
def set_difficulty():
print("""
{YELLOW}请选择难度等级:{RESET}
1. 简单模式(1-100,15次机会)
2. 普通模式(1-50,10次机会)
3. 困难模式(1-20,5次机会)
""".format(YELLOW=YELLOW, RESET=RESET))
while True:
choice = input("请输入选项(1-3):").strip()
if choice == '1':
return (1, 100, 15)
elif choice == '2':
return (1, 50, 10)
elif choice == '3':
return (1, 20, 5)
print(f"{RED}无效输入,请重新选择!{RESET}")
def load_history():
history_file = Path("game_history.json")
if history_file.exists():
return json.loads(history_file.read_text())
return {"best_score": 999, "total_games": 0}
def save_history(attempts, total_games):
history = load_history()
new_record = {
"best_score": min(attempts, history["best_score"]),
"total_games": total_games + 1
}
Path("game_history.json").write_text(json.dumps(new_record))
def main():
history = load_history()
print(f"""
{GREEN}欢迎来到终极猜数字游戏!{RESET}
{YELLOW}历史最佳记录:{history['best_score']}次 | 总游戏次数:{history['total_games']}{RESET}
""")
min_num, max_num, max_attempts = set_difficulty()
secret_number = random.randint(min_num, max_num)
attempts = 0
remaining = max_attempts
print(f"\n{YELLOW}数字已生成({min_num}-{max_num}),开始挑战吧!{RESET}")
while attempts < max_attempts:
try:
guess = int(input(f"\n{YELLOW}剩余次数:{remaining} | 请输入数字:{RESET}"))
if guess < min_num or guess > max_num:
print(f"{RED}数字超出范围!请输入{min_num}-{max_num}之间的数{RESET}")
continue
attempts += 1
remaining = max_attempts - attempts
if guess > secret_number:
print(f"{RED}太大了!{RESET}剩余次数:{remaining}")
elif guess < secret_number:
print(f"{RED}太小了!{RESET}剩余次数:{remaining}")
else:
print(f"""
{GREEN}
★★★ 恭 喜 猜 中 ★★★
数字:{secret_number}
用时:{attempts}次
★★★ 新 纪 录 ★★★
{RESET}
""")
save_history(attempts, history["total_games"])
break
if remaining == 0:
print(f"""
{RED}
✘ 次数用尽 ✘
正确答案:{secret_number}
当前最佳:{history['best_score']}次
✘ 挑 战 失 败 ✘
{RESET}
""")
except ValueError:
print(f"{RED}请输入有效数字!{RESET}")
play_again = input("\n是否再战一局?(y/n):").lower().strip()
if play_again == 'y':
main()
if __name__ == "__main__":
main()
七、扩展功能建议
- 图形界面:使用Tkinter或PyQt将游戏转换为窗口程序
- 网络对战:通过socket编程实现双人联机对战
- 成就系统:添加"十连中"等特殊成就奖励
- 数据可视化:用matplotlib绘制游戏成绩趋势图
- AI对手:实现简单的数字猜测算法作为电脑对手
通过本教程的学习,你已经掌握了Python游戏开发的核心流程。可以从修改现有代码开始,尝试添加新功能或优化用户体验,逐步打造属于自己的特色游戏版本。