Spaces:
Paused

MathematicsApps / gamification.py
jobinv's picture
Upload 16 files
f78142c verified
Raw History Blame Contribute Delete
4.7 kB
"""Small, session-local progression system for M1 Mechanics Quest."""
from __future__ import annotations
from copy import deepcopy
from html import escape
TOPIC_NAMES = {
"vertical": "Vertical motion",
"speed_time": "Speed–time graphs",
"collision": "Momentum",
"beam": "Moments",
"friction": "Friction",
"connected": "Connected particles",
"vectors": "Vectors",
"equilibrium": "Equilibrium",
}
def new_profile() -> dict:
return {
"xp": 0,
"level": 1,
"streak": 0,
"hearts": 3,
"correct": 0,
"attempts": 0,
"hints": 0,
"awarded_ids": [],
"badges": [],
"mastery": {key: {"correct": 0, "attempts": 0} for key in TOPIC_NAMES},
}
def _normalise(profile: dict | None) -> dict:
base = new_profile()
if not isinstance(profile, dict):
return base
for key in base:
if key in profile:
base[key] = deepcopy(profile[key])
for topic in TOPIC_NAMES:
base["mastery"].setdefault(topic, {"correct": 0, "attempts": 0})
return base
def record_hint(profile: dict | None) -> dict:
result = _normalise(profile)
result["hints"] += 1
return result
def apply_result(profile: dict | None, question: dict, correct: bool, score_ratio: float) -> tuple[dict, str]:
p = _normalise(profile)
topic = question.get("topic", "vertical")
p["attempts"] += 1
p["mastery"].setdefault(topic, {"correct": 0, "attempts": 0})
p["mastery"][topic]["attempts"] += 1
if correct:
p["correct"] += 1
p["mastery"][topic]["correct"] += 1
p["streak"] += 1
p["hearts"] = min(3, p["hearts"] + (1 if p["streak"] % 5 == 0 else 0))
else:
p["streak"] = 0
p["hearts"] = max(0, p["hearts"] - 1)
qid = question.get("id", "")
first_award = bool(qid and qid not in p["awarded_ids"])
difficulty_multiplier = {"Foundation": 1.0, "Exam standard": 1.35, "Challenge": 1.7}.get(question.get("difficulty"), 1.0)
xp_gain = 0
if first_award:
xp_gain = round((18 + 32 * max(0.0, min(score_ratio, 1.0))) * difficulty_multiplier)
if correct:
xp_gain += min(25, p["streak"] * 2)
p["xp"] += xp_gain
p["awarded_ids"].append(qid)
p["awarded_ids"] = p["awarded_ids"][-200:]
p["level"] = 1 + p["xp"] // 250
unlocked = []
if p["correct"] >= 1 and "First Principle" not in p["badges"]:
p["badges"].append("First Principle")
unlocked.append("First Principle")
if p["streak"] >= 3 and "Momentum Streak" not in p["badges"]:
p["badges"].append("Momentum Streak")
unlocked.append("Momentum Streak")
if sum(1 for v in p["mastery"].values() if v["correct"] > 0) >= 4 and "M1 Explorer" not in p["badges"]:
p["badges"].append("M1 Explorer")
unlocked.append("M1 Explorer")
if p["correct"] >= 10 and "Force Master" not in p["badges"]:
p["badges"].append("Force Master")
unlocked.append("Force Master")
note = f"+{xp_gain} XP" if xp_gain else "Practice replay · XP already awarded"
if unlocked:
note += " · Badge unlocked: " + ", ".join(unlocked)
return p, note
def profile_html(profile: dict | None) -> str:
p = _normalise(profile)
level_progress = p["xp"] % 250
hearts = "".join("❤" if i < p["hearts"] else "♡" for i in range(3))
badges = "".join(f'<span class="badge-chip">🏅 {escape(b)}</span>' for b in p["badges"]) or '<span class="muted-chip">Badges unlock as you practise</span>'
return f"""
<div class="profile-card">
<div class="profile-level"><span>LEVEL {p['level']}</span><strong>{p['xp']} XP</strong></div>
<div class="xp-track"><div class="xp-fill" style="width:{level_progress/2.5:.1f}%"></div></div>
<div class="profile-stats">
<div><b>{p['streak']}</b><span>🔥 streak</span></div>
<div><b>{p['correct']}/{p['attempts']}</b><span>missions</span></div>
<div><b class="heart-text">{hearts}</b><span>focus</span></div>
</div>
<div class="badge-row">{badges}</div>
</div>
"""
def mastery_markdown(profile: dict | None) -> str:
p = _normalise(profile)
rows = ["| Skill zone | Attempts | Mastery |", "|---|---:|---:|"]
for key, name in TOPIC_NAMES.items():
data = p["mastery"][key]
pct = round(100 * data["correct"] / data["attempts"]) if data["attempts"] else 0
icon = "🟢" if pct >= 75 and data["attempts"] else "🟡" if pct >= 40 else "⚪"
rows.append(f"| {icon} {name} | {data['attempts']} | {pct}% |")
return "## Skill constellation\n\n" + "\n".join(rows) + "\n\n*Progress is stored for this browser session.*"