help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
fitness-coach-bot
/
utils
RSK World
fitness-coach-bot
Fitness Coach Bot - Python + Flask + SQLAlchemy + Workout Plans + Exercise Guidance + Health Tracking + AI Fitness Coach
utils
  • __pycache__
  • __init__.py965 B
  • ai_workout_generator.py18 KB
  • analytics_engine.py27.8 KB
  • fitness_coach.py13.3 KB
  • gamification_system.py30.4 KB
  • nutrition_ai.py23.8 KB
  • smart_recovery.py11 KB
  • social_features.py19.4 KB
  • voice_coach.py10 KB
  • wearable_integration.py27 KB
  • workout_buddy_matcher.py9.5 KB
gamification_system.py
utils/gamification_system.py
Raw Download
Find: Go to:
"""
Advanced Gamification System for Fitness Coach Bot
Author: RSK World (https://rskworld.in)
Founded by: Molla Samser
Designer & Tester: Rima Khatun
Contact: help@rskworld.in, +91 93305 39277
Year: 2026
"""

import json
import random
import math
from datetime import datetime, timedelta
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from enum import Enum

class AchievementType(Enum):
    WORKOUT_STREAK = "workout_streak"
    CALORIE_BURN = "calorie_burn"
    STRENGTH_GAIN = "strength_gain"
    CONSISTENCY = "consistency"
    SOCIAL = "social"
    MILESTONE = "milestone"
    CHALLENGE = "challenge"
    PERSONAL_BEST = "personal_best"

class RewardType(Enum):
    POINTS = "points"
    BADGE = "badge"
    TITLE = "title"
    AVATAR = "avatar"
    CHALLENGE_ENTRY = "challenge_entry"
    FEATURE_UNLOCK = "feature_unlock"

@dataclass
class Achievement:
    id: str
    name: str
    description: str
    type: AchievementType
    points: int
    badge_icon: str
    rarity: str  # common, rare, epic, legendary
    requirements: Dict[str, Any]
    rewards: List[Dict]
    unlocked_at: Optional[datetime] = None
    progress: float = 0.0

@dataclass
class UserLevel:
    level: int
    title: str
    points_required: int
    rewards: List[str]
    benefits: List[str]

@dataclass
class Challenge:
    id: str
    name: str
    description: str
    type: str
    difficulty: str
    duration_days: int
    participants: List[str]
    rewards: Dict[str, Any]
    start_date: datetime
    end_date: datetime

class GamificationSystem:
    """Comprehensive gamification system for fitness motivation"""
    
    def __init__(self):
        self.user_profiles = {}
        self.achievements = self._load_achievements()
        self.levels = self._load_levels()
        self.challenges = {}
        self.leaderboards = {}
        self.rewards_shop = self._load_rewards_shop()
        
    def _load_achievements(self) -> Dict[str, Achievement]:
        """Load all available achievements"""
        return {
            # Workout Streak Achievements
            "first_workout": Achievement(
                id="first_workout",
                name="First Steps",
                description="Complete your first workout",
                type=AchievementType.WORKOUT_STREAK,
                points=10,
                badge_icon="🎯",
                rarity="common",
                requirements={"workouts_completed": 1},
                rewards=[{"type": "points", "value": 10}]
            ),
            
            "week_warrior": Achievement(
                id="week_warrior",
                name="Week Warrior",
                description="Work out for 7 consecutive days",
                type=AchievementType.WORKOUT_STREAK,
                points=100,
                badge_icon="🔥",
                rarity="rare",
                requirements={"consecutive_days": 7},
                rewards=[{"type": "points", "value": 100}, {"type": "title", "value": "Dedicated"}]
            ),
            
            "month_champion": Achievement(
                id="month_champion",
                name="Month Champion",
                description="Work out for 30 consecutive days",
                type=AchievementType.WORKOUT_STREAK,
                points=500,
                badge_icon="👑",
                rarity="epic",
                requirements={"consecutive_days": 30},
                rewards=[{"type": "points", "value": 500}, {"type": "badge", "value": "champion"}]
            ),
            
            # Calorie Burn Achievements
            "calorie_rookie": Achievement(
                id="calorie_rookie",
                name="Calorie Rookie",
                description="Burn 1,000 total calories",
                type=AchievementType.CALORIE_BURN,
                points=50,
                badge_icon="⚡",
                rarity="common",
                requirements={"total_calories": 1000},
                rewards=[{"type": "points", "value": 50}]
            ),
            
            "calorie_master": Achievement(
                id="calorie_master",
                name="Calorie Master",
                description="Burn 10,000 total calories",
                type=AchievementType.CALORIE_BURN,
                points=200,
                badge_icon="💥",
                rarity="rare",
                requirements={"total_calories": 10000},
                rewards=[{"type": "points", "value": 200}, {"type": "avatar", "value": "fire_avatar"}]
            ),
            
            # Strength Achievements
            "strength_beginner": Achievement(
                id="strength_beginner",
                name="Strength Beginner",
                description="Increase total weight lifted by 100kg",
                type=AchievementType.STRENGTH_GAIN,
                points=75,
                badge_icon="💪",
                rarity="common",
                requirements={"strength_improvement": 100},
                rewards=[{"type": "points", "value": 75}]
            ),
            
            "strength_beast": Achievement(
                id="strength_beast",
                name="Strength Beast",
                description="Increase total weight lifted by 500kg",
                type=AchievementType.STRENGTH_GAIN,
                points=300,
                badge_icon="🦁",
                rarity="epic",
                requirements={"strength_improvement": 500},
                rewards=[{"type": "points", "value": 300}, {"type": "badge", "value": "beast_mode"}]
            ),
            
            # Consistency Achievements
            "consistent_week": Achievement(
                id="consistent_week",
                name="Consistent Week",
                description="Complete all planned workouts for a week",
                type=AchievementType.CONSISTENCY,
                points=80,
                badge_icon="📅",
                rarity="rare",
                requirements={"weekly_completion": 100},
                rewards=[{"type": "points", "value": 80}]
            ),
            
            # Social Achievements
            "team_player": Achievement(
                id="team_player",
                name="Team Player",
                description="Join a fitness team",
                type=AchievementType.SOCIAL,
                points=30,
                badge_icon="🤝",
                rarity="common",
                requirements={"team_joined": True},
                rewards=[{"type": "points", "value": 30}]
            ),
            
            "challenge_winner": Achievement(
                id="challenge_winner",
                name="Challenge Winner",
                description="Win a fitness challenge",
                type=AchievementType.CHALLENGE,
                points=250,
                badge_icon="🏆",
                rarity="epic",
                requirements={"challenge_won": True},
                rewards=[{"type": "points", "value": 250}, {"type": "title", "value": "Champion"}]
            ),
            
            # Milestone Achievements
            "level_10": Achievement(
                id="level_10",
                name="Rising Star",
                description="Reach level 10",
                type=AchievementType.MILESTONE,
                points=150,
                badge_icon="⭐",
                rarity="rare",
                requirements={"level": 10},
                rewards=[{"type": "points", "value": 150}, {"type": "feature_unlock", "value": "advanced_analytics"}]
            ),
            
            "level_25": Achievement(
                id="level_25",
                name="Fitness Elite",
                description="Reach level 25",
                type=AchievementType.MILESTONE,
                points=500,
                badge_icon="🌟",
                rarity="legendary",
                requirements={"level": 25},
                rewards=[{"type": "points", "value": 500}, {"type": "badge", "value": "elite_fitness"}]
            )
        }
    
    def _load_levels(self) -> List[UserLevel]:
        """Load user level progression system"""
        levels = []
        
        # Define level progression
        level_data = [
            (1, "Fitness Novice", 0, ["Basic Profile"], ["Track workouts"]),
            (2, "Fitness Beginner", 100, ["Workout History"], ["Basic analytics"]),
            (3, "Fitness Enthusiast", 250, ["Achievement System"], ["Unlock achievements"]),
            (4, "Fitness Athlete", 500, ["Social Features"], ["Join challenges"]),
            (5, "Fitness Expert", 1000, ["Advanced Analytics"], ["Detailed insights"]),
            (6, "Fitness Master", 2000, ["Custom Workouts"], ["Create routines"]),
            (7, "Fitness Champion", 3500, ["Leaderboard Access"], ["Compete globally"]),
            (8, "Fitness Elite", 5000, ["Premium Avatars"], ["Exclusive rewards"]),
            (9, "Fitness Legend", 7500, ["Mentor Status"], ["Guide others"]),
            (10, "Fitness God", 10000, ["All Features"], ["Complete access"])
        ]
        
        for i, (level, title, points, rewards, benefits) in enumerate(level_data, 1):
            levels.append(UserLevel(
                level=level,
                title=title,
                points_required=points,
                rewards=rewards,
                benefits=benefits
            ))
        
        return levels
    
    def _load_rewards_shop(self) -> Dict[str, Any]:
        """Load rewards shop with unlockable items"""
        return {
            "avatars": [
                {"id": "warrior", "name": "Warrior", "cost": 500, "icon": "⚔️"},
                {"id": "ninja", "name": "Ninja", "cost": 750, "icon": "🥷"},
                {"id": "superhero", "name": "Superhero", "cost": 1000, "icon": "🦸"},
                {"id": "robot", "name": "Robot", "cost": 1500, "icon": "🤖"},
                {"id": "dragon", "name": "Dragon", "cost": 2000, "icon": "🐉"}
            ],
            "titles": [
                {"id": "beast_mode", "name": "Beast Mode", "cost": 300, "icon": "💪"},
                {"id": "machine", "name": "Machine", "cost": 500, "icon": "🤖"},
                {"id": "legend", "name": "Legend", "cost": 800, "icon": "👑"},
                {"id": "unstoppable", "name": "Unstoppable", "cost": 1200, "icon": "🚀"}
            ],
            "badges": [
                {"id": "fire", "name": "Fire Badge", "cost": 200, "icon": "🔥"},
                {"id": "lightning", "name": "Lightning Badge", "cost": 400, "icon": "⚡"},
                {"id": "rainbow", "name": "Rainbow Badge", "cost": 600, "icon": "🌈"},
                {"id": "diamond", "name": "Diamond Badge", "cost": 1000, "icon": "💎"}
            ],
            "features": [
                {"id": "advanced_analytics", "name": "Advanced Analytics", "cost": 1000, "icon": "📊"},
                {"id": "custom_workouts", "name": "Custom Workouts", "cost": 1500, "icon": "📝"},
                {"id": "premium_challenges", "name": "Premium Challenges", "cost": 2000, "icon": "🏆"},
                {"id": "personal_coaching", "name": "Personal Coaching", "cost": 5000, "icon": "👨‍🏫"}
            ]
        }
    
    def get_user_profile(self, user_id: str) -> Dict:
        """Get or create user gamification profile"""
        if user_id not in self.user_profiles:
            self.user_profiles[user_id] = {
                "user_id": user_id,
                "level": 1,
                "total_points": 0,
                "current_streak": 0,
                "longest_streak": 0,
                "last_workout_date": None,
                "achievements_unlocked": [],
                "rewards_purchased": [],
                "challenges_completed": 0,
                "workout_count": 0,
                "total_calories_burned": 0,
                "total_workout_time": 0,
                "strength_improvement": 0,
                "social_points": 0,
                "created_at": datetime.now().isoformat(),
                "stats": {
                    "workouts_this_week": 0,
                    "workouts_this_month": 0,
                    "points_this_week": 0,
                    "achievements_this_month": 0
                }
            }
        
        return self.user_profiles[user_id]
    
    def update_user_activity(self, user_id: str, activity_data: Dict) -> Dict:
        """Update user activity and check for achievements"""
        profile = self.get_user_profile(user_id)
        updates = {"points_earned": 0, "achievements_unlocked": [], "level_up": False}
        
        # Update basic stats
        activity_type = activity_data.get("type", "workout")
        
        if activity_type == "workout":
            profile["workout_count"] += 1
            profile["total_workout_time"] += activity_data.get("duration", 0)
            profile["total_calories_burned"] += activity_data.get("calories", 0)
            
            # Update streak
            today = datetime.now().date()
            last_workout = datetime.fromisoformat(profile["last_workout_date"]).date() if profile["last_workout_date"] else None
            
            if last_workout == today - timedelta(days=1):
                profile["current_streak"] += 1
            elif last_workout != today:
                profile["current_streak"] = 1
            
            profile["last_workout_date"] = datetime.now().isoformat()
            profile["longest_streak"] = max(profile["longest_streak"], profile["current_streak"])
            
            # Award points for workout
            workout_points = self._calculate_workout_points(activity_data)
            profile["total_points"] += workout_points
            updates["points_earned"] = workout_points
            
        elif activity_type == "strength":
            profile["strength_improvement"] += activity_data.get("improvement", 0)
            
        elif activity_type == "social":
            profile["social_points"] += activity_data.get("points", 0)
            profile["total_points"] += activity_data.get("points", 0)
            updates["points_earned"] = activity_data.get("points", 0)
        
        # Check for new achievements
        new_achievements = self._check_achievements(user_id, profile)
        for achievement in new_achievements:
            if achievement["id"] not in profile["achievements_unlocked"]:
                profile["achievements_unlocked"].append(achievement["id"])
                profile["total_points"] += achievement["points"]
                updates["achievements_unlocked"].append(achievement)
                updates["points_earned"] += achievement["points"]
        
        # Check for level up
        old_level = profile["level"]
        new_level = self._calculate_user_level(profile["total_points"])
        if new_level > old_level:
            profile["level"] = new_level
            updates["level_up"] = True
            updates["new_level"] = new_level
            updates["level_rewards"] = self.levels[new_level - 1].rewards
        
        # Update weekly/monthly stats
        self._update_periodic_stats(profile)
        
        return updates
    
    def _calculate_workout_points(self, activity_data: Dict) -> int:
        """Calculate points for workout activity"""
        base_points = 10
        
        # Duration bonus
        duration = activity_data.get("duration", 0)
        if duration > 60:
            base_points += 20
        elif duration > 45:
            base_points += 15
        elif duration > 30:
            base_points += 10
        
        # Intensity bonus
        intensity = activity_data.get("intensity", "moderate")
        intensity_bonus = {"low": 0, "moderate": 5, "high": 15, "extreme": 25}
        base_points += intensity_bonus.get(intensity, 5)
        
        # Calorie bonus
        calories = activity_data.get("calories", 0)
        if calories > 500:
            base_points += 20
        elif calories > 300:
            base_points += 10
        
        # Streak bonus
        # This would be calculated based on current streak
        
        return base_points
    
    def _check_achievements(self, user_id: str, profile: Dict) -> List[Dict]:
        """Check for newly unlocked achievements"""
        new_achievements = []
        
        for achievement_id, achievement in self.achievements.items():
            if achievement_id in profile["achievements_unlocked"]:
                continue
            
            # Check achievement requirements
            unlocked = False
            
            if achievement.type == AchievementType.WORKOUT_STREAK:
                if "consecutive_days" in achievement.requirements:
                    if profile["current_streak"] >= achievement.requirements["consecutive_days"]:
                        unlocked = True
                elif "workouts_completed" in achievement.requirements:
                    if profile["workout_count"] >= achievement.requirements["workouts_completed"]:
                        unlocked = True
            
            elif achievement.type == AchievementType.CALORIE_BURN:
                if profile["total_calories_burned"] >= achievement.requirements["total_calories"]:
                    unlocked = True
            
            elif achievement.type == AchievementType.STRENGTH_GAIN:
                if profile["strength_improvement"] >= achievement.requirements["strength_improvement"]:
                    unlocked = True
            
            elif achievement.type == AchievementType.MILESTONE:
                if profile["level"] >= achievement.requirements["level"]:
                    unlocked = True
            
            elif achievement.type == AchievementType.SOCIAL:
                if "team_joined" in achievement.requirements:
                    # This would be checked based on actual team membership
                    pass
                elif "challenge_won" in achievement.requirements:
                    if profile["challenges_completed"] >= 1:
                        unlocked = True
            
            if unlocked:
                achievement.unlocked_at = datetime.now()
                new_achievements.append({
                    "id": achievement.id,
                    "name": achievement.name,
                    "description": achievement.description,
                    "points": achievement.points,
                    "badge_icon": achievement.badge_icon,
                    "rarity": achievement.rarity,
                    "rewards": achievement.rewards
                })
        
        return new_achievements
    
    def _calculate_user_level(self, total_points: int) -> int:
        """Calculate user level based on total points"""
        for level in reversed(self.levels):
            if total_points >= level.points_required:
                return level.level
        return 1
    
    def _update_periodic_stats(self, profile: Dict):
        """Update weekly and monthly statistics"""
        today = datetime.now()
        week_start = today - timedelta(days=today.weekday())
        month_start = today.replace(day=1)
        
        # This would be calculated from actual workout history
        # For now, using sample calculations
        profile["stats"]["workouts_this_week"] = min(profile["workout_count"], 4)
        profile["stats"]["workouts_this_month"] = profile["workout_count"]
        profile["stats"]["points_this_week"] = min(profile["total_points"], 150)
        profile["stats"]["achievements_this_month"] = len(profile["achievements_unlocked"])
    
    def get_leaderboard(self, leaderboard_type: str = "global", limit: int = 50) -> List[Dict]:
        """Get leaderboard rankings"""
        if leaderboard_type not in self.leaderboards:
            self.leaderboards[leaderboard_type] = []
        
        # Sort users by total points
        all_users = []
        for user_id, profile in self.user_profiles.items():
            all_users.append({
                "user_id": user_id,
                "total_points": profile["total_points"],
                "level": profile["level"],
                "workout_count": profile["workout_count"],
                "current_streak": profile["current_streak"]
            })
        
        sorted_users = sorted(all_users, key=lambda x: x["total_points"], reverse=True)
        
        # Add rank
        for i, user in enumerate(sorted_users, 1):
            user["rank"] = i
        
        return sorted_users[:limit]
    
    def create_challenge(self, challenge_data: Dict) -> Dict:
        """Create a new fitness challenge"""
        challenge = Challenge(
            id=f"challenge_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            name=challenge_data.get("name"),
            description=challenge_data.get("description"),
            type=challenge_data.get("type", "individual"),
            difficulty=challenge_data.get("difficulty", "medium"),
            duration_days=challenge_data.get("duration_days", 30),
            participants=[],
            rewards=challenge_data.get("rewards", {}),
            start_date=datetime.now(),
            end_date=datetime.now() + timedelta(days=challenge_data.get("duration_days", 30))
        )
        
        self.challenges[challenge.id] = challenge
        
        return {
            "success": True,
            "challenge_id": challenge.id,
            "challenge": challenge
        }
    
    def join_challenge(self, user_id: str, challenge_id: str) -> Dict:
        """Join a fitness challenge"""
        if challenge_id not in self.challenges:
            return {"success": False, "error": "Challenge not found"}
        
        challenge = self.challenges[challenge_id]
        
        if user_id in challenge.participants:
            return {"success": False, "error": "Already joined this challenge"}
        
        challenge.participants.append(user_id)
        
        return {
            "success": True,
            "message": f"Successfully joined challenge: {challenge.name}"
        }
    
    def purchase_reward(self, user_id: str, reward_type: str, reward_id: str) -> Dict:
        """Purchase reward from rewards shop"""
        profile = self.get_user_profile(user_id)
        
        if reward_type not in self.rewards_shop:
            return {"success": False, "error": "Invalid reward type"}
        
        reward_items = self.rewards_shop[reward_type]
        reward = next((item for item in reward_items if item["id"] == reward_id), None)
        
        if not reward:
            return {"success": False, "error": "Reward not found"}
        
        if profile["total_points"] < reward["cost"]:
            return {"success": False, "error": "Insufficient points"}
        
        # Deduct points and add reward
        profile["total_points"] -= reward["cost"]
        if "rewards_purchased" not in profile:
            profile["rewards_purchased"] = []
        
        profile["rewards_purchased"].append({
            "type": reward_type,
            "id": reward_id,
            "name": reward["name"],
            "cost": reward["cost"],
            "purchased_at": datetime.now().isoformat()
        })
        
        return {
            "success": True,
            "message": f"Successfully purchased {reward['name']}",
            "remaining_points": profile["total_points"]
        }
    
    def get_user_achievements(self, user_id: str) -> Dict:
        """Get user's achievements with progress"""
        profile = self.get_user_profile(user_id)
        user_achievements = []
        
        for achievement_id, achievement in self.achievements.items():
            user_achievement = {
                "id": achievement.id,
                "name": achievement.name,
                "description": achievement.description,
                "badge_icon": achievement.badge_icon,
                "rarity": achievement.rarity,
                "points": achievement.points,
                "unlocked": achievement_id in profile["achievements_unlocked"],
                "progress": 0.0,
                "requirements": achievement.requirements
            }
            
            # Calculate progress
            if not user_achievement["unlocked"]:
                user_achievement["progress"] = self._calculate_achievement_progress(achievement, profile)
            
            user_achievements.append(user_achievement)
        
        return {
            "total_achievements": len(user_achievements),
            "unlocked_count": len(profile["achievements_unlocked"]),
            "achievements": user_achievements
        }
    
    def _calculate_achievement_progress(self, achievement: Achievement, profile: Dict) -> float:
        """Calculate progress percentage for achievement"""
        if achievement.type == AchievementType.WORKOUT_STREAK:
            if "consecutive_days" in achievement.requirements:
                return min(1.0, profile["current_streak"] / achievement.requirements["consecutive_days"])
            elif "workouts_completed" in achievement.requirements:
                return min(1.0, profile["workout_count"] / achievement.requirements["workouts_completed"])
        
        elif achievement.type == AchievementType.CALORIE_BURN:
            return min(1.0, profile["total_calories_burned"] / achievement.requirements["total_calories"])
        
        elif achievement.type == AchievementType.STRENGTH_GAIN:
            return min(1.0, profile["strength_improvement"] / achievement.requirements["strength_improvement"])
        
        elif achievement.type == AchievementType.MILESTONE:
            return min(1.0, profile["level"] / achievement.requirements["level"])
        
        return 0.0
    
    def get_user_level_info(self, user_id: str) -> Dict:
        """Get user level information"""
        profile = self.get_user_profile(user_id)
        current_level = profile["level"]
        current_level_data = self.levels[current_level - 1]
        next_level_data = self.levels[current_level] if current_level < len(self.levels) else None
        
        points_to_next = 0
        if next_level_data:
            points_to_next = next_level_data.points_required - profile["total_points"]
        
        return {
            "current_level": current_level,
            "current_title": current_level_data.title,
            "current_points": profile["total_points"],
            "points_to_next": points_to_next,
            "progress_to_next": (profile["total_points"] - current_level_data.points_required) / (next_level_data.points_required - current_level_data.points_required) if next_level_data else 1.0,
            "next_level": next_level_data.title if next_level_data else None,
            "rewards": current_level_data.rewards,
            "benefits": current_level_data.benefits
        }
    
    def get_daily_missions(self, user_id: str) -> List[Dict]:
        """Get daily missions for user"""
        missions = []
        
        # Generate dynamic daily missions
        base_missions = [
            {
                "id": "daily_workout",
                "name": "Daily Workout",
                "description": "Complete any workout today",
                "type": "workout",
                "target": 1,
                "reward_points": 25,
                "difficulty": "easy"
            },
            {
                "id": "calorie_burn",
                "name": "Calorie Burner",
                "description": f"Burn 300 calories today",
                "type": "calories",
                "target": 300,
                "reward_points": 50,
                "difficulty": "medium"
            },
            {
                "id": "step_goal",
                "name": "Step Master",
                "description": "Reach 10,000 steps today",
                "type": "steps",
                "target": 10000,
                "reward_points": 30,
                "difficulty": "medium"
            }
        ]
        
        # Add some randomness
        selected_missions = random.sample(base_missions, min(3, len(base_missions)))
        
        for mission in selected_missions:
            missions.append({
                **mission,
                "progress": 0,
                "completed": False,
                "expires_at": (datetime.now() + timedelta(days=1)).isoformat()
            })
        
        return missions
    
    def get_user_stats_summary(self, user_id: str) -> Dict:
        """Get comprehensive user statistics summary"""
        profile = self.get_user_profile(user_id)
        
        return {
            "user_id": user_id,
            "level_info": self.get_user_level_info(user_id),
            "points": {
                "total": profile["total_points"],
                "this_week": profile["stats"]["points_this_week"],
                "rank": self._get_user_rank(user_id)
            },
            "streaks": {
                "current": profile["current_streak"],
                "longest": profile["longest_streak"]
            },
            "workouts": {
                "total": profile["workout_count"],
                "this_week": profile["stats"]["workouts_this_week"],
                "this_month": profile["stats"]["workouts_this_month"],
                "total_time": profile["total_workout_time"],
                "total_calories": profile["total_calories_burned"]
            },
            "achievements": {
                "total": len(self.achievements),
                "unlocked": len(profile["achievements_unlocked"]),
                "completion_percentage": (len(profile["achievements_unlocked"]) / len(self.achievements)) * 100
            },
            "social": {
                "challenges_completed": profile["challenges_completed"],
                "social_points": profile["social_points"]
            }
        }
    
    def _get_user_rank(self, user_id: str) -> int:
        """Get user's global rank"""
        leaderboard = self.get_leaderboard("global", 1000)
        
        for user in leaderboard:
            if user["user_id"] == user_id:
                return user["rank"]
        
        return len(leaderboard) + 1
749 lines•30.4 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer