feat: XP foundation + waves + featured game + profile + leaderboard by total_xp

- services/xp.py: award_xp, level_for, RANKS (48), featured_game
- services/waves.py: wave_plan, grid_size_for, wave_medal
- routers/featured.py: GET /featured (игра дня ×1.5)
- routers/users.py: POST /set-nickname, POST /set-avatar
- routers/app_auth.py: /auth/me с XP-полями (level, rank_key, rank_name, xp)
- routers/game.py: award_xp + 3 штрафа + POST /game/next (волны)
- routers/wordquiz.py: award_xp + серии в choose_progress
- routers/bubblewords.py: award_xp + 4 штрафа
- routers/sentences.py: award_xp по длине предложения
- routers/leaderboard.py: сортировка по total_xp, XP-поля в ответе
- database.py: миграции user_profile, xp_log, choose_progress, user_seen_levels, user_game_progress, wave_results, bubble_levels, user_word_stats
- main.py: подключение routers/featured

Проверено:
- /auth/me отдаёт level=1, rank_00, xp_in_level
- /featured отдаёт wordsearch + seconds_left
- /game/complete-level начисляет XP через award_xp
- xp_log, user_profile заполняются
- /game/next выдаёт уровень по волнам
- /leaderboard сортирует по total_xp
This commit is contained in:
2026-10-09 08:12:19 +00:00
parent a3f7d9521f
commit 84927b063f
13 changed files with 1800 additions and 278 deletions
+44 -30
View File
@@ -171,13 +171,21 @@ async def get_next_bubble_level(request: Request):
@router.post("/complete")
async def complete_bubble_level(request: Request):
"""Завершение уровня пузырей, начисление очков и проверка достижений"""
"""Завершение уровня пузырей, начисление XP и проверка достижений.
🔧 НОВОЕ (08.10.2026): XP-система.
Штрафы:
-1 за открытие списка слов (один раз за уровень)
-1 за каждое неправильно собранное слово (макс 3)
-1 если time_ms > 60 сек
Минимум 1 звезда.
"""
telegram_id, _ = await require_auth(request)
body = await request.json()
words_count = body.get("words_count", 3)
completion_time = body.get("completion_time")
# 🔧 ФИКС (24.09.2026): client_controlled_hints_bubblewords —
# hints_used больше НЕ берём от клиента. Читаем из bubble_words_progress.current_hints_used.
list_opened = bool(body.get("list_opened", False))
wrong_words = int(body.get("wrong_words", 0) or 0)
pool = await get_pool()
async with pool.acquire() as conn:
@@ -187,19 +195,29 @@ async def complete_bubble_level(request: Request):
if not user_exists:
raise HTTPException(401, "User not registered")
# Получаем current_level пользователя
current_level = await conn.fetchval(
"SELECT current_level FROM users WHERE telegram_id = $1", telegram_id
) or "A1"
# 🔧 ФИКС (24.09.2026): client_controlled_hints_bubblewords —
# читаем серверный hints_used.
# Читаем серверный hints_used
hints_used = await conn.fetchval(
"SELECT current_hints_used FROM bubble_words_progress WHERE user_id = $1",
telegram_id
) or 0
hints_used = min(max(0, hints_used), 3)
score = max(10, 100 - hints_used * 10)
# 🆕 Расчёт звёзд
# Старт 5. Штрафы: hints(1) + wrong_words(до 3) + time(1)
time_penalty = 1 if (completion_time and completion_time > 60) else 0
wrong_penalty = min(max(0, wrong_words), 3)
hint_penalty = 1 if hints_used > 0 else 0
list_penalty = 1 if list_opened else 0
stars = max(1, 5 - time_penalty - wrong_penalty - hint_penalty - list_penalty)
# Начисляем XP
from services.xp import award_xp
xp_result = await award_xp(conn, telegram_id, "bubbles", stars)
score = xp_result["points"]
await conn.execute("""
INSERT INTO bubble_words_progress (user_id, levels_completed, total_score, level, current_hints_used)
@@ -211,42 +229,26 @@ async def complete_bubble_level(request: Request):
current_hints_used = 0
""", telegram_id, score, current_level)
# 🔧 ФИКС (23.09.2026): achievements_nested_pool_acquire_bubblewords —
# вызовы достижений вынесены за async with pool.acquire() (паттерн game.py).
# Данные для достижений
total_levels = await conn.fetchval(
"SELECT levels_completed FROM bubble_words_progress WHERE user_id = $1",
telegram_id
) or 0
wordsearch_score = await conn.fetchval(
"SELECT COALESCE(SUM(score), 0) FROM user_progress WHERE user_id = $1 AND completed_at IS NOT NULL",
telegram_id
) or 0
sentence_score = await conn.fetchval(
"SELECT COALESCE(SUM(score), 0) FROM sentence_progress WHERE user_id = $1 AND completed_at IS NOT NULL",
telegram_id
) or 0
wordquiz_score = await conn.fetchval(
"SELECT COALESCE(total_score, 0) FROM word_quiz_progress WHERE user_id = $1",
telegram_id
) or 0
bubblewords_score = await conn.fetchval(
"SELECT COALESCE(total_score, 0) FROM bubble_words_progress WHERE user_id = $1",
telegram_id
) or 0
grand_total = wordsearch_score + sentence_score + wordquiz_score + bubblewords_score
achievements_to_check = [
("bubble_levels", total_levels),
("total_score", grand_total),
("total_score", xp_result["total_xp"]),
]
if hints_used == 0:
achievements_to_check.append(("bubble_no_hints", 1))
if score == 100:
if stars == 5:
achievements_to_check.append(("bubble_perfect", 1))
if completion_time is not None and completion_time > 0 and int(completion_time) <= 45:
if completion_time is not None and 0 < completion_time <= 45:
achievements_to_check.append(("bubble_speed", 45))
if completion_time is not None and 0 < completion_time <= 30:
achievements_to_check.append(("bubble_speed_30", 30))
# 🔧 ФИКС (23.09.2026): вызовы достижений ВНЕ блока async with pool.acquire()
# Достижения — вне транзакции
from routers.achievements import check_and_award_achievements
new_achievements = []
for ach_type, value in achievements_to_check:
@@ -258,6 +260,18 @@ async def complete_bubble_level(request: Request):
"score": score,
"completion_time": completion_time,
"new_achievements": new_achievements,
# 🆕 XP-поля
"stars": xp_result["stars"],
"base_points": xp_result["base_points"],
"multiplier": xp_result["multiplier"],
"points": xp_result["points"],
"featured": xp_result["featured"],
"level_up": xp_result["level_up"],
"total_xp": xp_result["total_xp"],
"level": xp_result["level"],
"rank_key": xp_result["rank_key"],
"xp_in_level": xp_result["xp_in_level"],
"xp_needed": xp_result["xp_needed"],
}