Spaces:
Sleeping
Sleeping
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlalchemy.orm import Session | |
| from sqlalchemy import func | |
| from typing import List | |
| from datetime import datetime, timedelta | |
| from database import get_db | |
| from models import User, UserStats, GameSession, GameAction | |
| from schemas import ( | |
| UserStatsResponse, | |
| UserStatsUpdate, | |
| GameSessionCreate, | |
| GameSessionResponse | |
| ) | |
| from auth import get_current_active_user | |
| router = APIRouter(prefix="/api/game", tags=["Game"]) | |
| async def get_user_stats( | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Получение статистики пользователя""" | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if not stats: | |
| # Создаем статистику если не существует | |
| stats = UserStats(user_id=current_user.id) | |
| db.add(stats) | |
| db.commit() | |
| db.refresh(stats) | |
| return stats | |
| async def update_user_stats( | |
| stats_update: UserStatsUpdate, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Обновление статистики пользователя""" | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if not stats: | |
| raise HTTPException(status_code=404, detail="Stats not found") | |
| # Обновление полей | |
| update_data = stats_update.dict(exclude_unset=True) | |
| for field, value in update_data.items(): | |
| setattr(stats, field, value) | |
| # Автоматический расчет уровня на основе опыта | |
| if stats_update.experience is not None: | |
| stats.level = 1 + (stats.experience // 100) | |
| db.commit() | |
| db.refresh(stats) | |
| return stats | |
| async def consume_energy( | |
| amount: float, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Расход энергии""" | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if not stats: | |
| raise HTTPException(status_code=404, detail="Stats not found") | |
| stats.energy = max(0, stats.energy - amount) | |
| db.commit() | |
| return {"energy": stats.energy, "message": f"Consumed {amount} energy"} | |
| async def restore_energy( | |
| amount: float, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Восстановление энергии""" | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if not stats: | |
| raise HTTPException(status_code=404, detail="Stats not found") | |
| stats.energy = min(stats.max_energy, stats.energy + amount) | |
| db.commit() | |
| return {"energy": stats.energy, "message": f"Restored {amount} energy"} | |
| async def consume_hunger( | |
| amount: float, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Расход сытости""" | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if not stats: | |
| raise HTTPException(status_code=404, detail="Stats not found") | |
| stats.hunger = max(0, stats.hunger - amount) | |
| db.commit() | |
| return {"hunger": stats.hunger, "message": f"Consumed {amount} hunger"} | |
| async def restore_hunger( | |
| amount: float, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Восстановление сытости (еда)""" | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if not stats: | |
| raise HTTPException(status_code=404, detail="Stats not found") | |
| stats.hunger = min(stats.max_hunger, stats.hunger + amount) | |
| db.commit() | |
| return {"hunger": stats.hunger, "message": f"Restored {amount} hunger"} | |
| async def start_game_session( | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Начало игровой сессии""" | |
| # Проверка активной сессии | |
| active_session = db.query(GameSession).filter( | |
| GameSession.user_id == current_user.id, | |
| GameSession.ended_at == None | |
| ).first() | |
| if active_session: | |
| return active_session | |
| # Создание новой сессии | |
| session = GameSession(user_id=current_user.id) | |
| db.add(session) | |
| db.commit() | |
| db.refresh(session) | |
| return session | |
| async def end_game_session( | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Завершение игровой сессии""" | |
| session = db.query(GameSession).filter( | |
| GameSession.user_id == current_user.id, | |
| GameSession.ended_at == None | |
| ).first() | |
| if not session: | |
| raise HTTPException(status_code=404, detail="No active session found") | |
| session.ended_at = datetime.utcnow() | |
| session.duration = int((session.ended_at - session.started_at).total_seconds()) | |
| # Обновление общей статистики | |
| stats = db.query(UserStats).filter(UserStats.user_id == current_user.id).first() | |
| if stats: | |
| stats.total_playtime += session.duration | |
| db.commit() | |
| db.refresh(session) | |
| return session | |
| async def get_user_sessions( | |
| limit: int = 10, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Получение истории игровых сессий""" | |
| sessions = db.query(GameSession).filter( | |
| GameSession.user_id == current_user.id | |
| ).order_by(GameSession.started_at.desc()).limit(limit).all() | |
| return sessions | |
| async def log_game_action( | |
| action_type: str, | |
| action_data: str = None, | |
| current_user: User = Depends(get_current_active_user), | |
| db: Session = Depends(get_db) | |
| ): | |
| """Логирование игрового действия""" | |
| action = GameAction( | |
| user_id=current_user.id, | |
| action_type=action_type, | |
| action_data=action_data | |
| ) | |
| db.add(action) | |
| db.commit() | |
| return {"message": "Action logged", "action_type": action_type} | |