Files
hsbg-ai/hsbg_ai/backend/api/routes/game.py

71 lines
2.3 KiB
Python
Raw Normal View History

2026-03-31 13:10:46 +02:00
"""Routes API — Gestion des sessions de jeu."""
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from backend.database.db import get_db
from backend.database.models import GameSession
router = APIRouter()
@router.post("/start")
async def start_game(hero_id: str = "", player_count: int = 8,
db: AsyncSession = Depends(get_db)):
"""Démarre une nouvelle session de jeu."""
s = GameSession(is_active=True, session_meta={"player_count": player_count, "hero_id": hero_id})
db.add(s)
await db.flush()
return {"session_id": s.id, "started_at": s.started_at.isoformat()}
@router.post("/{session_id}/end")
async def end_game(session_id: int, final_place: int = 4,
db: AsyncSession = Depends(get_db)):
"""Termine une session avec la place finale."""
s = await db.get(GameSession, session_id)
if not s:
raise HTTPException(404, "Session introuvable")
s.is_active = False
s.ended_at = datetime.utcnow()
s.final_place = final_place
return {"status": "ended", "session_id": session_id, "final_place": final_place}
@router.get("/active")
async def get_active(db: AsyncSession = Depends(get_db)):
"""Retourne la session active ou {'active': false}."""
r = await db.execute(select(GameSession).where(GameSession.is_active == True))
s = r.scalar_one_or_none()
if not s:
return {"active": False}
return {
"active": True,
"session_id": s.id,
"started_at": s.started_at.isoformat(),
"total_turns": s.total_turns,
}
@router.get("/history")
async def get_history(limit: int = 10, db: AsyncSession = Depends(get_db)):
"""Historique des parties terminées."""
from sqlalchemy import desc
r = await db.execute(
select(GameSession)
.where(GameSession.is_active == False)
.order_by(desc(GameSession.ended_at))
.limit(limit)
)
sessions = r.scalars().all()
return [
{
"id": s.id,
"started_at": s.started_at.isoformat(),
"ended_at": s.ended_at.isoformat() if s.ended_at else None,
"final_place": s.final_place,
"total_turns": s.total_turns,
}
for s in sessions
]