YAP/db_utils.py
Carlo Ghisolfi c2f76d4222 First commit
2026-10-04 19:17:16 +02:00

112 lines
No EOL
2.4 KiB
Python

import sqlite3
from pathlib import *
import json
def init_db():
conn = sqlite3.connect("progress.db")
cursor = conn.cursor()
for path in Path("./levels").glob("*.json"):
with open(path, "r") as file:
level = json.load(file)
level_id = level["id"]
# Initialize progress on levels not already in the table
cursor.execute(
"""
INSERT OR IGNORE INTO player_progress
(id, unlocked, completed, timer)
VALUES (?, 0, 0, 0)
""",
(level_id,)
)
# For end
# Set the unlocked property for the first level
cursor.execute(
"""
UPDATE player_progress
SET unlocked = TRUE
WHERE id = ?
""",
("001",)
)
conn.commit()
conn.close()
def get_levels():
levels = sorted(Path("./levels").glob("*.json"))
return levels
def reset_db():
conn = sqlite3.connect("progress.db")
cursor = conn.cursor()
cursor.execute(
"""
DELETE FROM player_progress
"""
)
conn.commit()
conn.close()
def get_progress():
conn = sqlite3.connect("progress.db")
cursor = conn.cursor()
# Set the completed property fand timer
cursor.execute(
"""
SELECT unlocked, timer FROM player_progress
ORDER BY id ASC
""",
)
result = cursor.fetchall()
conn.close()
return result
def save_progress(level_state):
conn = sqlite3.connect("progress.db")
cursor = conn.cursor()
level_id = level_state.level.id
# Set the completed property fand timer
cursor.execute(
"""
UPDATE player_progress
SET completed = TRUE, timer = ?
WHERE id = ?
""",
(level_state.final_time, level_id,)
)
unlock_level_id = None
next_level_number = level_state.level.level_number + 1
for path in Path("./levels").glob("*.json"):
if int(path.name.split("_")[0]) == next_level_number:
with open(path, "r") as file:
level = json.load(file)
unlock_level_id = level["id"]
break
if unlock_level_id is not None:
# Set the unlocked property for the next level
cursor.execute(
"""
UPDATE player_progress
SET unlocked = TRUE
WHERE id = ?
""",
(unlock_level_id,)
)
conn.commit()
conn.close()