Spaces:
Sleeping
Sleeping
File size: 6,803 Bytes
2f4298a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
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"])
@router.get("/stats", response_model=UserStatsResponse)
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
@router.patch("/stats", response_model=UserStatsResponse)
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
@router.post("/stats/consume-energy")
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"}
@router.post("/stats/restore-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"}
@router.post("/stats/consume-hunger")
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"}
@router.post("/stats/restore-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"}
@router.post("/session/start", response_model=GameSessionResponse)
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
@router.post("/session/end", response_model=GameSessionResponse)
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
@router.get("/sessions", response_model=List[GameSessionResponse])
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
@router.post("/action/{action_type}")
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}
|