Python贪吃蛇游戏小型数据存储:SQLite3是否属于过度设计?
贪吃蛇游戏:最佳得分存储方案选择
文本文件(JSON/CSV/纯文本):适合简单场景
如果你的需求仅仅是存储单用户的单条最佳得分及耗时,文本文件是完全够用的选择,优势很明显:
- 实现简单,代码量极少,不需要额外依赖
- 读写速度快,适合小数据量场景
- 格式直观,直接打开就能查看数据
用JSON格式的示例代码:
import json def save_best_score(score, time_spent): data = {"best_score": score, "time_spent": time_spent} with open("best_score.json", "w") as f: json.dump(data, f) def load_best_score(): try: with open("best_score.json", "r") as f: return json.load(f) except FileNotFoundError: # 首次运行返回初始值 return {"best_score": 0, "time_spent": 0}
缺点也很明确:如果未来要扩展功能(比如多用户得分、历史记录排行榜、数据筛选),文本文件的维护成本会急剧上升,容易出现格式错误或数据冲突。
SQLite3:适合有扩展需求的场景
如果你的需求只是单条记录,用SQLite确实有点“过度设计”,但如果有潜在的功能扩展计划,SQLite是更稳妥的选择:
- 它是Python内置的轻量级文件型数据库,不需要单独的服务器,部署成本为0
- 结构化存储数据,避免文本文件的格式混乱问题
- 支持事务、查询、排序等操作,方便后续扩展功能(比如保存多条历史得分、做排行榜)
示例代码:
import sqlite3 def init_db(): conn = sqlite3.connect("snake_scores.db") cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS best_scores (id INTEGER PRIMARY KEY AUTOINCREMENT, score INTEGER NOT NULL, time_spent INTEGER NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''') conn.commit() conn.close() def save_best_score(score, time_spent): conn = sqlite3.connect("snake_scores.db") cursor = conn.cursor() # 仅当新得分更高时保存 cursor.execute("SELECT MAX(score) FROM best_scores") current_max = cursor.fetchone()[0] if current_max is None or score > current_max: cursor.execute("INSERT INTO best_scores (score, time_spent) VALUES (?, ?)", (score, time_spent)) conn.commit() conn.close() def load_best_score(): conn = sqlite3.connect("snake_scores.db") cursor = conn.cursor() cursor.execute("SELECT score, time_spent FROM best_scores ORDER BY score DESC LIMIT 1") result = cursor.fetchone() conn.close() return {"best_score": result[0], "time_spent": result[1]} if result else {"best_score": 0, "time_spent": 0}
最终建议
- 若仅需单用户单条记录:优先用JSON文本文件,简单高效,完全够用,SQLite属于过度设计。
- 若有扩展计划(比如排行榜、多用户):直接用SQLite,前期多写几行代码,后续扩展不用重构,性价比很高。
内容的提问来源于stack exchange,提问作者Harsith R
相关产品推荐
相关产品推荐

