๐Ÿ“ Python

Achievements System in Python

P
Author
PyLand Team
๐Ÿ“…
Published
03.04.2026
โฑ๏ธ
Reading time
2 min
๐Ÿ‘๏ธ
Views
399
๐ŸŒฑ
Level
Beginner

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.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

if __name__ == "__main__": the Python entry point

The if name == "main" guard defines a Python program's entry point: it distinguishes direct...

๐Ÿ“… 14.08.2026 ๐Ÿ‘๏ธ 44
๐Ÿ“

strip() and lower(): Preparing User Text ๐Ÿงน

A user may enter the correct word with extra spaces or different letter case. Python...

๐Ÿ“… 11.08.2026 ๐Ÿ‘๏ธ 50
๐Ÿ“

ord(), chr(), and Cyclic Letter Shifts in Python ๐Ÿ”

A string contains characters, but a computer stores every character as a numeric code. Python...

๐Ÿ“… 09.08.2026 ๐Ÿ‘๏ธ 89

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!