Gamification increases user engagement by 30โ40%. Achievements are a simple way to implement it.
Base Achievement Class
from datetime import datetime
class Achievement:
"""A single achievement."""
def __init__(self, id, name, description, points, condition):
self.id = id
self.name = name
self.description = description
self.points = points
self.condition = condition # function (user_data) -> bool
self.unlocked = False
self.unlocked_at = None
def check(self, user_data):
"""Check the condition and unlock. Returns True on a new unlock."""
if self.unlocked:
return False
if self.condition(user_data):
self.unlocked = True
self.unlocked_at = datetime.now()
return True
return False
def __str__(self):
status = "unlocked" if self.unlocked else "locked"
return f"[{status}] {self.name} ({self.points} pts)"
Achievement Types
def create_milestone(name, stat_key, threshold, points):
"""For reaching a numeric threshold."""
return Achievement(
id=f"{stat_key}_{threshold}",
name=name,
description=f"Reach {threshold} {stat_key}",
points=points,
condition=lambda data: data.get(stat_key, 0) >= threshold
)
def create_streak(days, points):
"""For consecutive days."""
return Achievement(
id=f"streak_{days}",
name=f"{days}-day streak",
description=f"Log in {days} days in a row",
points=points,
condition=lambda data: data.get("streak", 0) >= days
)
# Example tiers
milestones = [
create_milestone("Beginner", "lessons_finished", 1, 10),
create_milestone("Student", "lessons_finished", 5, 50),
create_milestone("Expert", "lessons_finished", 20, 200),
create_milestone("Master", "lessons_finished", 50, 500),
]
streaks = [
create_streak( 3, 30),
create_streak( 7, 100),
create_streak(30, 500),
create_streak(100, 2000),
]
Tiers
TIERS = [
{"name": "Beginner", "min_points": 0},
{"name": "Student", "min_points": 100},
{"name": "Expert", "min_points": 500},
{"name": "Master", "min_points": 1000},
{"name": "Legend", "min_points": 5000},
]
def get_tier(points):
"""The user's current tier."""
tier = TIERS[0]
for t in TIERS:
if points >= t["min_points"]:
tier = t
return tier
def progress_to_next(points):
"""Progress toward the next tier as a percentage."""
current = get_tier(points)
next_tier = next((t for t in TIERS if t["min_points"] > points), None)
if not next_tier:
return 100
earned = points - current["min_points"]
needed = next_tier["min_points"] - current["min_points"]
return (earned / needed) * 100
Integration: AchievementManager
class AchievementManager:
"""Central achievement management system."""
def __init__(self, achievements):
self.achievements = achievements
self.user_stats = {} # {user_id: stats_dict}
self.user_unlocked = {} # {user_id: [achievement_id, ...]}
def get_stats(self, user_id):
if user_id not in self.user_stats:
self.user_stats[user_id] = {
"logins": 0, "lessons_finished": 0,
"tasks_completed": 0, "streak": 0, "points_earned": 0
}
self.user_unlocked[user_id] = []
return self.user_stats[user_id]
def record_action(self, user_id, action, value=1):
"""Record an action and check achievements."""
stats = self.get_stats(user_id)
if action in stats:
stats[action] += value
newly_unlocked = []
for ach in self.achievements:
if ach.id not in self.user_unlocked[user_id] and ach.check(stats):
self.user_unlocked[user_id].append(ach.id)
stats["points_earned"] += ach.points
newly_unlocked.append(ach)
print(f"Achievement unlocked: {ach.name} (+{ach.points} pts)")
return newly_unlocked
# Usage
all_achievements = milestones + streaks
manager = AchievementManager(all_achievements)
manager.record_action(user_id=1, action="lessons_finished") # -> "Beginner" unlock
manager.record_action(user_id=1, action="lessons_finished")
manager.record_action(user_id=1, action="lessons_finished")
manager.record_action(user_id=1, action="lessons_finished")
manager.record_action(user_id=1, action="lessons_finished") # -> "Student" unlock
stats = manager.get_stats(1)
tier = get_tier(stats["points_earned"])
print(f"Tier: {tier['name']}, points: {stats['points_earned']}")
System Balance
| Type | Difficulty | Points | Goal |
|---|---|---|---|
| First steps | Very easy | 10โ50 | Onboarding |
| Milestone | Medium | 50โ200 | Retention |
| Streak | Requires regularity | 100โ500 | Habit loop |
| Epic | Hard | 500โ2000 | Prestige |
Early achievements should unlock quickly โ otherwise users leave before they get hooked.
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!