Compare commits
48
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8918309501 | ||
|
|
1afc7a1654 | ||
|
|
5fc49d086d | ||
|
|
5a6b81da1d | ||
|
|
7c43812475 | ||
|
|
e7c512e50e | ||
|
|
0d6b56e5c9 | ||
|
|
99dd3765d0 | ||
|
|
929420a284 | ||
|
|
6399d3931c | ||
|
|
07d2d197fd | ||
|
|
1f7ac86ef5 | ||
|
|
16b8956b87 | ||
|
|
959b9c4e3f | ||
|
|
4355b94291 | ||
|
|
bd45071142 | ||
|
|
13fcc8240d | ||
|
|
4159d6265a | ||
|
|
741d1799e7 | ||
|
|
5644b5be16 | ||
|
|
e65bd5db43 | ||
|
|
6786acb126 | ||
|
|
6fc8c83322 | ||
|
|
bffcb4387c | ||
|
|
01ce5dfa2d | ||
|
|
ec9108f2a3 | ||
|
|
938d674b09 | ||
|
|
556c11fc95 | ||
|
|
aa7679c49b | ||
|
|
9db00df88f | ||
|
|
4333aa62a6 | ||
|
|
bd743e4c48 | ||
|
|
f83fcc0e1c | ||
|
|
78d40364bf | ||
|
|
20b1cdc464 | ||
|
|
26442db954 | ||
|
|
e3bc3e8456 | ||
|
|
a6fe755fdb | ||
|
|
959f789f24 | ||
|
|
d181e43ee3 | ||
|
|
6f89336a02 | ||
|
|
f78a1fa19f | ||
|
|
2b5ef446c1 | ||
|
|
50c02b7707 | ||
|
|
6e02303ea8 | ||
|
|
22e4eed3f5 | ||
|
|
5e2de6f7e4 | ||
|
|
2dedec5972 |
+66
@@ -229,6 +229,21 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added current_streak column to user_progress")
|
||||
|
||||
# ============ Авто-миграция: добавляем wave в user_progress ============
|
||||
# 🔧 НОВОЕ (13.10.2026): wave — номер волны, к которой относится
|
||||
# пройденный уровень. Нужен для подсчёта wave_points (сумма очков
|
||||
# за 10 уровней волны) в модалке итогов волны.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'user_progress' AND column_name = 'wave'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE user_progress
|
||||
ADD COLUMN wave INTEGER
|
||||
""")
|
||||
logger.info("Added wave column to user_progress")
|
||||
|
||||
# ============ sentences ============
|
||||
await conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sentences (
|
||||
@@ -883,6 +898,46 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added current_hints_used column to bubble_words_progress")
|
||||
|
||||
# 🔧 НОВОЕ (14.10.2026): current_list_opened — серверный счётчик
|
||||
# «показать слова» для текущего уровня пузырей. Medium — 1 раз.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'bubble_words_progress' AND column_name = 'current_list_opened'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE bubble_words_progress
|
||||
ADD COLUMN current_list_opened INT DEFAULT 0
|
||||
""")
|
||||
logger.info("Added current_list_opened column to bubble_words_progress")
|
||||
|
||||
# 🔧 НОВОЕ (14.10.2026): current_level_words — состояние текущего
|
||||
# уровня пузырей (слова + части + переводы). Нужно для подсказок,
|
||||
# т.к. уровень генерируется на лету в /next и нигде не хранится.
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'bubble_words_progress' AND column_name = 'current_level_words'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE bubble_words_progress
|
||||
ADD COLUMN current_level_words JSONB DEFAULT '[]'::jsonb
|
||||
""")
|
||||
logger.info("Added current_level_words column to bubble_words_progress")
|
||||
|
||||
# 🔧 НОВОЕ (14.10.2026): hinted_words — какие слова уже получили
|
||||
# подсказку «первая часть» (для «каждый раз разное слово»).
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'bubble_words_progress' AND column_name = 'hinted_words'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE bubble_words_progress
|
||||
ADD COLUMN hinted_words TEXT[] DEFAULT '{}'
|
||||
""")
|
||||
logger.info("Added hinted_words column to bubble_words_progress")
|
||||
|
||||
# ============ wrong_because_explanations ============
|
||||
await conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS wrong_because_explanations (
|
||||
@@ -1299,6 +1354,17 @@ async def init_db():
|
||||
""")
|
||||
logger.info("Added apple_id column to users (Pleily)")
|
||||
|
||||
# difficulty
|
||||
col_exists = await conn.fetchval("""
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name = 'users' AND column_name = 'difficulty'
|
||||
""")
|
||||
if not col_exists:
|
||||
await conn.execute("""
|
||||
ALTER TABLE users ADD COLUMN difficulty TEXT DEFAULT 'medium'
|
||||
""")
|
||||
logger.info("Added difficulty column to users (Pleily)")
|
||||
|
||||
# app_user_id_seq — sequence для отрицательных user_id
|
||||
await conn.execute("""
|
||||
CREATE SEQUENCE IF NOT EXISTS app_user_id_seq
|
||||
|
||||
@@ -523,6 +523,7 @@
|
||||
| last_completed_level | integer | YES | 0 |
|
||||
| id | integer | NO | nextval('users_id_seq'::regclass) |
|
||||
| current_level | text | YES | 'A1'::text |
|
||||
| difficulty | text | YES | 'medium'::text |
|
||||
|
||||
## voice_usage
|
||||
|
||||
|
||||
+16
-37
@@ -8,7 +8,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/achievements", tags=["achievements"])
|
||||
|
||||
# ============ Данные 52 достижений ============
|
||||
# ============ Данные 55 достижений ============
|
||||
ACHIEVEMENTS_DATA = [
|
||||
# ===== Word Search (11) =====
|
||||
{"code": "first_level", "category": "wordsearch", "icon": "🔰",
|
||||
@@ -245,7 +245,7 @@ ACHIEVEMENTS_DATA = [
|
||||
"desc_pl": "Ukończ poziom w mniej niż 30 sekund", "desc_ru": "Пройти уровень быстрее 30 секунд", "desc_uk": "Пройти рівень швидше 30 секунд", "desc_en": "Complete a level in under 30 seconds",
|
||||
"type": "bubble_speed", "value": 30},
|
||||
|
||||
# ===== General (15) =====
|
||||
# ===== General (9) =====
|
||||
{"code": "score_1000", "category": "general", "icon": "🌟",
|
||||
"name_pl": "Wschodząca gwiazda", "name_ru": "Восходящая звезда", "name_uk": "Висхідна зірка", "name_en": "Rising Star",
|
||||
"desc_pl": "Zdobądź 1000 punktów", "desc_ru": "Набрать 1000 очков", "desc_uk": "Набрати 1000 балів", "desc_en": "Earn 1000 points",
|
||||
@@ -291,42 +291,7 @@ ACHIEVEMENTS_DATA = [
|
||||
"desc_pl": "Zmień język interfejsu", "desc_ru": "Сменить язык интерфейса", "desc_uk": "Змінити мову інтерфейсу", "desc_en": "Change interface language",
|
||||
"type": "language_changed", "value": 1},
|
||||
|
||||
# 🔧 ИСПРАВЛЕНО: Заменено достижение "Открой Грамматику" на "Открой меню учителя"
|
||||
{"code": "open_teacher_menu", "category": "general", "icon": "🎓",
|
||||
"name_pl": "Uczeń", "name_ru": "Ученик", "name_uk": "Учень", "name_en": "Student",
|
||||
"desc_pl": "Otwórz menu nauczyciela", "desc_ru": "Открыть меню учителя", "desc_uk": "Відкрити меню вчителя", "desc_en": "Open the teacher menu",
|
||||
"type": "teacher_menu_opened", "value": 1},
|
||||
|
||||
{"code": "open_cheatsheets", "category": "general", "icon": "📝",
|
||||
"name_pl": "Ciekawski", "name_ru": "Любознательный", "name_uk": "Допитливий", "name_en": "Curious",
|
||||
"desc_pl": "Otwórz sekcję Ściągi", "desc_ru": "Открыть раздел Шпаргалки", "desc_uk": "Відкрити розділ Шпаргалки", "desc_en": "Open the Cheatsheets section",
|
||||
"type": "cheatsheets_opened", "value": 1},
|
||||
|
||||
{"code": "open_pronunciation", "category": "general", "icon": "🔊",
|
||||
"name_pl": "Słuchacz", "name_ru": "Слушатель", "name_uk": "Слухач", "name_en": "Listener",
|
||||
"desc_pl": "Otwórz sekcję Wymowa", "desc_ru": "Открыть раздел Произношение", "desc_uk": "Відкрити розділ Вимова", "desc_en": "Open the Pronunciation section",
|
||||
"type": "pronunciation_opened", "value": 1},
|
||||
|
||||
{"code": "open_ai_assistant", "category": "general", "icon": "🤖",
|
||||
"name_pl": "Asystent AI", "name_ru": "AI-помощник", "name_uk": "AI-помічник", "name_en": "AI Assistant",
|
||||
"desc_pl": "Otwórz Asystenta AI", "desc_ru": "Открыть AI-помощника", "desc_uk": "Відкрити AI-помічника", "desc_en": "Open the AI Assistant",
|
||||
"type": "ai_assistant_opened", "value": 1},
|
||||
|
||||
{"code": "open_alphabet", "category": "general", "icon": "🔤",
|
||||
"name_pl": "Alfabetysta", "name_ru": "Алфавитист", "name_uk": "Алфавітист", "name_en": "Alphabetist",
|
||||
"desc_pl": "Otwórz sekcję Alfabet", "desc_ru": "Открыть раздел Алфавит", "desc_uk": "Відкрити розділ Алфавіт", "desc_en": "Open the Alphabet section",
|
||||
"type": "alphabet_opened", "value": 1},
|
||||
|
||||
{"code": "open_rules", "category": "general", "icon": "📐",
|
||||
"name_pl": "Gramatyk", "name_ru": "Грамматик", "name_uk": "Граматик", "name_en": "Grammarian",
|
||||
"desc_pl": "Otwórz sekcję Zasady", "desc_ru": "Открыть раздел Правила", "desc_uk": "Відкрити розділ Правила", "desc_en": "Open the Rules section",
|
||||
"type": "rules_opened", "value": 1},
|
||||
|
||||
# 🔧 НОВОЕ: Достижение за открытие Прогресса
|
||||
{"code": "open_progress", "category": "general", "icon": "📊",
|
||||
"name_pl": "Planista", "name_ru": "Планировщик", "name_uk": "Планувальник", "name_en": "Planner",
|
||||
"desc_pl": "Otwórz sekcję Postęp", "desc_ru": "Открыть раздел Прогресс", "desc_uk": "Відкрити розділ Прогрес", "desc_en": "Open the Progress section",
|
||||
"type": "progress_opened", "value": 1},
|
||||
]
|
||||
|
||||
|
||||
@@ -369,6 +334,20 @@ async def init_achievements():
|
||||
requirement_value = EXCLUDED.requirement_value
|
||||
""", rows)
|
||||
|
||||
# 🔧 Удаление осиротевших достижений (которых больше нет в ACHIEVEMENTS_DATA)
|
||||
await conn.execute("""
|
||||
DELETE FROM user_achievements
|
||||
WHERE achievement_id IN (
|
||||
SELECT id FROM achievements
|
||||
WHERE code NOT IN (SELECT unnest($1::text[]))
|
||||
)
|
||||
""", [a["code"] for a in ACHIEVEMENTS_DATA])
|
||||
|
||||
await conn.execute("""
|
||||
DELETE FROM achievements
|
||||
WHERE code NOT IN (SELECT unnest($1::text[]))
|
||||
""", [a["code"] for a in ACHIEVEMENTS_DATA])
|
||||
|
||||
logger.info(f"[achievements] init: upserted {len(rows)} achievements")
|
||||
|
||||
|
||||
|
||||
+203
-29
@@ -1,5 +1,6 @@
|
||||
import random
|
||||
import hashlib # 🔧 НОВОЕ: импорт hashlib для стабильного хэширования
|
||||
import json
|
||||
from fastapi import APIRouter, Request, HTTPException
|
||||
from auth import require_auth
|
||||
from database import get_pool
|
||||
@@ -100,7 +101,7 @@ async def get_next_bubble_level(request: Request):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT app_language, current_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
"SELECT app_language, current_level, difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
if not user:
|
||||
raise HTTPException(401, "User not registered")
|
||||
@@ -114,13 +115,9 @@ async def get_next_bubble_level(request: Request):
|
||||
)
|
||||
current_bubble_level = (progress["levels_completed"] if progress else 0) + 1
|
||||
|
||||
# Прогрессия по количеству слов на уровне
|
||||
if current_bubble_level <= 10:
|
||||
num_words = random.choice([3, 4])
|
||||
elif current_bubble_level <= 25:
|
||||
num_words = random.choice([5, 6])
|
||||
else:
|
||||
num_words = random.choice([7, 8])
|
||||
# Количество слов по сложности
|
||||
difficulty = user["difficulty"] if "difficulty" in user.keys() else "medium"
|
||||
num_words = {"easy": 3, "medium": 4, "hard": 5}.get(difficulty, 4)
|
||||
|
||||
# 🔧 ФИКС (30.09.2026): csv_words_source —
|
||||
# источник слов переехал с level_words (старая схема level_id IS NULL)
|
||||
@@ -162,10 +159,172 @@ async def get_next_bubble_level(request: Request):
|
||||
|
||||
random.shuffle(all_parts)
|
||||
|
||||
# 🔧 НОВОЕ (14.10.2026): сохраняем состояние уровня для подсказок
|
||||
# и сбрасываем счётчики подсказок/списка при новом уровне.
|
||||
level_state = [
|
||||
{
|
||||
"word_pl": w["word_pl"],
|
||||
"translation": w["translation"],
|
||||
"parts": w["parts"],
|
||||
}
|
||||
for w in result_words
|
||||
]
|
||||
await conn.execute("""
|
||||
INSERT INTO bubble_words_progress
|
||||
(user_id, levels_completed, total_score, level,
|
||||
current_hints_used, current_list_opened, current_level_words, hinted_words)
|
||||
VALUES ($1, 0, 0, $2, 0, 0, $3::jsonb, '{}')
|
||||
ON CONFLICT (user_id) DO UPDATE
|
||||
SET current_hints_used = 0,
|
||||
current_list_opened = 0,
|
||||
current_level_words = $3::jsonb,
|
||||
hinted_words = '{}'
|
||||
""", telegram_id, current_level, json.dumps(level_state))
|
||||
|
||||
return {
|
||||
"words": result_words,
|
||||
"bubbles": all_parts,
|
||||
"level": current_bubble_level,
|
||||
"difficulty": user["difficulty"] or "medium",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/first-part-hint")
|
||||
async def first_part_hint(request: Request):
|
||||
"""Подсказка «первая часть слова» — возвращает первый пузырь одного из несобранных слов.
|
||||
|
||||
🔧 НОВОЕ (14.10.2026): аналог GET /hints/first-letter/{level_id} из филворда.
|
||||
Лимит 3 подсказки, штраф −20 (учитывается в /complete через current_hints_used).
|
||||
Hard — запрещено (400).
|
||||
"""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
body = await request.json()
|
||||
found_words = set(body.get("found_words", []) or [])
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
if not user:
|
||||
raise HTTPException(401, "User not registered")
|
||||
|
||||
difficulty = user["difficulty"] or "medium"
|
||||
if difficulty == "hard":
|
||||
raise HTTPException(400, "Hints are disabled on Hard difficulty")
|
||||
|
||||
progress = await conn.fetchrow(
|
||||
"SELECT current_hints_used, current_level_words, hinted_words "
|
||||
"FROM bubble_words_progress WHERE user_id = $1",
|
||||
telegram_id
|
||||
)
|
||||
if not progress:
|
||||
raise HTTPException(404, "No active level")
|
||||
|
||||
hints_used = progress["current_hints_used"] or 0
|
||||
if hints_used >= 3:
|
||||
raise HTTPException(400, "All hints used")
|
||||
|
||||
raw = progress["current_level_words"]
|
||||
if isinstance(raw, str):
|
||||
level_words = json.loads(raw) if raw else []
|
||||
else:
|
||||
level_words = raw or []
|
||||
|
||||
raw_hinted = progress["hinted_words"]
|
||||
if isinstance(raw_hinted, str):
|
||||
hinted = set(json.loads(raw_hinted)) if raw_hinted else set()
|
||||
else:
|
||||
hinted = set(raw_hinted or [])
|
||||
|
||||
# Слова, которые ещё не собраны и которым ещё не давали подсказку
|
||||
candidates = [
|
||||
w for w in level_words
|
||||
if w.get("word_pl") not in found_words and w.get("word_pl") not in hinted
|
||||
]
|
||||
|
||||
if not candidates:
|
||||
raise HTTPException(400, "All words already hinted")
|
||||
|
||||
chosen = random.choice(candidates)
|
||||
word_pl = chosen["word_pl"]
|
||||
parts = chosen.get("parts") or []
|
||||
first_part = parts[0] if parts else word_pl
|
||||
|
||||
new_hints = hints_used + 1
|
||||
new_hinted = sorted(hinted | {word_pl})
|
||||
|
||||
await conn.execute("""
|
||||
UPDATE bubble_words_progress
|
||||
SET current_hints_used = $2,
|
||||
hinted_words = $3
|
||||
WHERE user_id = $1
|
||||
""", telegram_id, new_hints, new_hinted)
|
||||
|
||||
return {
|
||||
"word_pl": word_pl,
|
||||
"first_part": first_part,
|
||||
"hints_used_total": new_hints,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/show-words")
|
||||
async def show_words(request: Request):
|
||||
"""Подсказка «показать слова» — возвращает все загаданные слова с переводами.
|
||||
|
||||
🔧 НОВОЕ (14.10.2026): аналог show-words из филворда.
|
||||
Easy — без лимита. Medium — 1 раз (−20). Hard — запрещено (400).
|
||||
"""
|
||||
telegram_id, _ = await require_auth(request)
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
if not user:
|
||||
raise HTTPException(401, "User not registered")
|
||||
|
||||
difficulty = user["difficulty"] or "medium"
|
||||
if difficulty == "hard":
|
||||
raise HTTPException(400, "Word list is disabled on Hard difficulty")
|
||||
|
||||
progress = await conn.fetchrow(
|
||||
"SELECT current_list_opened, current_level_words "
|
||||
"FROM bubble_words_progress WHERE user_id = $1",
|
||||
telegram_id
|
||||
)
|
||||
if not progress:
|
||||
raise HTTPException(404, "No active level")
|
||||
|
||||
list_opened = progress["current_list_opened"] or 0
|
||||
|
||||
# Medium — список можно открыть только 1 раз
|
||||
if difficulty == "medium" and list_opened >= 1:
|
||||
raise HTTPException(400, "Word list already used on Medium difficulty")
|
||||
|
||||
raw = progress["current_level_words"]
|
||||
if isinstance(raw, str):
|
||||
level_words = json.loads(raw) if raw else []
|
||||
else:
|
||||
level_words = raw or []
|
||||
|
||||
words = [
|
||||
{"word_pl": w.get("word_pl"), "translation": w.get("translation")}
|
||||
for w in level_words
|
||||
]
|
||||
|
||||
# Инкремент счётчика для Easy и Medium (Hard сюда не доходит)
|
||||
new_list_opened = list_opened + 1
|
||||
await conn.execute("""
|
||||
UPDATE bubble_words_progress
|
||||
SET current_list_opened = $2
|
||||
WHERE user_id = $1
|
||||
""", telegram_id, new_list_opened)
|
||||
|
||||
return {
|
||||
"words": words,
|
||||
"list_opened_total": new_list_opened,
|
||||
}
|
||||
|
||||
|
||||
@@ -184,7 +343,6 @@ async def complete_bubble_level(request: Request):
|
||||
body = await request.json()
|
||||
words_count = body.get("words_count", 3)
|
||||
completion_time = body.get("completion_time")
|
||||
list_opened = bool(body.get("list_opened", False))
|
||||
wrong_words = int(body.get("wrong_words", 0) or 0)
|
||||
|
||||
pool = await get_pool()
|
||||
@@ -195,38 +353,55 @@ async def complete_bubble_level(request: Request):
|
||||
if not user_exists:
|
||||
raise HTTPException(401, "User not registered")
|
||||
|
||||
current_level = await conn.fetchval(
|
||||
"SELECT current_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
) or "A1"
|
||||
user = await conn.fetchrow(
|
||||
"SELECT current_level, difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
current_level = user["current_level"] or "A1"
|
||||
difficulty = user["difficulty"] or "medium"
|
||||
|
||||
# Читаем серверный hints_used
|
||||
hints_used = await conn.fetchval(
|
||||
"SELECT current_hints_used FROM bubble_words_progress WHERE user_id = $1",
|
||||
# Читаем серверные счётчики (не из body)
|
||||
progress = await conn.fetchrow(
|
||||
"SELECT current_hints_used, current_list_opened "
|
||||
"FROM bubble_words_progress WHERE user_id = $1",
|
||||
telegram_id
|
||||
) or 0
|
||||
)
|
||||
hints_used = (progress["current_hints_used"] if progress else 0) or 0
|
||||
hints_used = min(max(0, hints_used), 3)
|
||||
list_opened = (progress["current_list_opened"] if progress else 0) or 0
|
||||
|
||||
# 🆕 Расчёт звёзд
|
||||
# Старт 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)
|
||||
# 🔧 НОВОЕ (14.10.2026): очки по формуле филворда.
|
||||
# Hard — фикс 110. Easy/Medium — 100 − 20×hints − 20×list + bonus.
|
||||
if difficulty == "hard":
|
||||
if hints_used > 0 or list_opened:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Hints and word list are disabled on Hard difficulty"
|
||||
)
|
||||
points = 110
|
||||
else:
|
||||
bonus = 10 if hints_used == 0 else 0
|
||||
penalty_hints = 20 * hints_used
|
||||
penalty_list = 0 if difficulty == "easy" else 20 * (1 if list_opened else 0)
|
||||
points = max(20, min(110, 100 - penalty_hints - penalty_list + bonus))
|
||||
|
||||
# Начисляем XP
|
||||
from services.xp import award_xp
|
||||
xp_result = await award_xp(conn, telegram_id, "bubbles", stars)
|
||||
xp_result = await award_xp(conn, telegram_id, "bubbles", points)
|
||||
score = xp_result["points"]
|
||||
|
||||
await conn.execute("""
|
||||
INSERT INTO bubble_words_progress (user_id, levels_completed, total_score, level, current_hints_used)
|
||||
VALUES ($1, 1, $2, $3, 0)
|
||||
INSERT INTO bubble_words_progress
|
||||
(user_id, levels_completed, total_score, level,
|
||||
current_hints_used, current_list_opened, current_level_words, hinted_words)
|
||||
VALUES ($1, 1, $2, $3, 0, 0, '[]'::jsonb, '{}')
|
||||
ON CONFLICT (user_id) DO UPDATE
|
||||
SET levels_completed = bubble_words_progress.levels_completed + 1,
|
||||
total_score = bubble_words_progress.total_score + $2,
|
||||
level = $3,
|
||||
current_hints_used = 0
|
||||
current_hints_used = 0,
|
||||
current_list_opened = 0,
|
||||
current_level_words = '[]'::jsonb,
|
||||
hinted_words = '{}'
|
||||
""", telegram_id, score, current_level)
|
||||
|
||||
# Данные для достижений
|
||||
@@ -241,7 +416,7 @@ async def complete_bubble_level(request: Request):
|
||||
]
|
||||
if hints_used == 0:
|
||||
achievements_to_check.append(("bubble_no_hints", 1))
|
||||
if stars == 5:
|
||||
if hints_used == 0 and not list_opened and wrong_words == 0:
|
||||
achievements_to_check.append(("bubble_perfect", 1))
|
||||
if completion_time is not None and 0 < completion_time <= 45:
|
||||
achievements_to_check.append(("bubble_speed", 45))
|
||||
@@ -261,7 +436,6 @@ async def complete_bubble_level(request: Request):
|
||||
"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"],
|
||||
|
||||
+78
-34
@@ -73,7 +73,7 @@ async def get_level(request: Request, level_number: int):
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT app_language, current_level, last_completed_level, last_completed_by_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
"SELECT app_language, current_level, last_completed_level, last_completed_by_level, difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||
)
|
||||
|
||||
if not user:
|
||||
@@ -208,6 +208,7 @@ async def get_level(request: Request, level_number: int):
|
||||
# 🆕 (10.10.2026): волна и позиция в волне.
|
||||
"wave": wave,
|
||||
"position_in_wave": pos_in_wave,
|
||||
"difficulty": user["difficulty"] or "medium",
|
||||
}
|
||||
|
||||
|
||||
@@ -353,14 +354,23 @@ async def complete_level(request: Request):
|
||||
fast_streak = 0
|
||||
no_hints_streak = 0
|
||||
words_found = 0
|
||||
# 🆕 (13.10.2026): итоги волны для модалки.
|
||||
wave_completed = False
|
||||
wave_points = 0
|
||||
wave_max_points = 0
|
||||
wave_medal_result = "none"
|
||||
current_wave = 1
|
||||
current_position_in_wave = 1
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
user = await conn.fetchrow(
|
||||
"SELECT id, telegram_id, last_completed_level, current_level FROM users WHERE telegram_id = $1",
|
||||
"SELECT id, telegram_id, last_completed_level, current_level, difficulty FROM users WHERE telegram_id = $1",
|
||||
telegram_id
|
||||
)
|
||||
if not user:
|
||||
raise HTTPException(401, "User not registered")
|
||||
|
||||
difficulty = user["difficulty"] or "medium"
|
||||
|
||||
level = await conn.fetchrow(
|
||||
"SELECT id, level_number, grid_size, level FROM levels WHERE id = $1", level_id
|
||||
@@ -416,29 +426,31 @@ async def complete_level(request: Request):
|
||||
hints_used = min(max(0, hints_used), 3)
|
||||
|
||||
# 🆕 Штрафы (филворд):
|
||||
# -1 за открытие списка слов (один раз за уровень)
|
||||
# -1 за использование подсказки (один раз за уровень)
|
||||
# -1 за превышение времени
|
||||
# -20 за открытие списка слов (один раз за уровень)
|
||||
# -20 за каждую подсказку
|
||||
list_opened = bool(body.get("list_opened", False))
|
||||
|
||||
# Лимит времени по размеру сетки
|
||||
grid_size = level["grid_size"]
|
||||
time_limits = {5: 45, 6: 60, 7: 90, 8: 120}
|
||||
time_limit = time_limits.get(grid_size, 60)
|
||||
# 🔧 НОВОЕ (13.10.2026): на Hard подсказки и список слов недоступны.
|
||||
if difficulty == "hard" and (hints_used > 0 or list_opened):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Hints and word list are disabled on Hard difficulty"
|
||||
)
|
||||
|
||||
completion_time_val = completion_time or 0
|
||||
time_penalty = 1 if (completion_time_val > time_limit) else 0
|
||||
hint_penalty = 1 if hints_used > 0 else 0
|
||||
list_penalty = 1 if list_opened else 0
|
||||
|
||||
stars = max(
|
||||
1,
|
||||
5 - time_penalty - hint_penalty - list_penalty
|
||||
)
|
||||
# Очки в зависимости от сложности
|
||||
if difficulty == "hard":
|
||||
# Hard: фикс 110 (без подсказок и списка)
|
||||
points = 110
|
||||
else:
|
||||
# Easy / Medium
|
||||
bonus = 10 if hints_used == 0 else 0
|
||||
penalty_hints = 20 * hints_used
|
||||
penalty_list = 0 if difficulty == "easy" else 20 * (1 if list_opened else 0)
|
||||
points = max(20, min(110, 100 - penalty_hints - penalty_list + bonus))
|
||||
|
||||
# Начисляем XP через единую функцию
|
||||
from services.xp import award_xp
|
||||
xp_result = await award_xp(conn, telegram_id, "wordsearch", stars)
|
||||
xp_result = await award_xp(conn, telegram_id, "wordsearch", points)
|
||||
|
||||
score = xp_result["points"] # для обратной совместимости
|
||||
|
||||
@@ -447,17 +459,41 @@ async def complete_level(request: Request):
|
||||
# уже была создана hints.py (юзер взял подсказку → уровень не завершится).
|
||||
# Теперь UPSERT с ON CONFLICT DO UPDATE.
|
||||
# hints_used уже прочитан из БД выше (не доверяем клиенту).
|
||||
# 🔧 ФИКС (13.10.2026): wave_off_by_one —
|
||||
# session_level_number хранит позицию СЛЕДУЮЩЕГО уровня
|
||||
# (уже увеличенную при выдаче), поэтому модалка волны
|
||||
# срабатывала на 9-м уровне. Читаем current_wave /
|
||||
# current_position_in_wave — позицию именно завершаемого уровня.
|
||||
wave_row = await conn.fetchrow(
|
||||
"SELECT current_wave, current_position_in_wave FROM user_game_progress WHERE user_id = $1",
|
||||
telegram_id,
|
||||
)
|
||||
if wave_row and wave_row["current_wave"] and wave_row["current_position_in_wave"]:
|
||||
current_wave = int(wave_row["current_wave"])
|
||||
current_position_in_wave = int(wave_row["current_position_in_wave"])
|
||||
else:
|
||||
# Fallback для старых записей без current_* полей.
|
||||
global_level = await conn.fetchval(
|
||||
"SELECT global_level_number FROM user_game_progress WHERE user_id = $1",
|
||||
telegram_id,
|
||||
)
|
||||
global_level = int(global_level or 1)
|
||||
from services.waves import wave_for_level, level_in_wave
|
||||
current_wave = wave_for_level(global_level)
|
||||
current_position_in_wave = level_in_wave(global_level)
|
||||
|
||||
await conn.execute("""
|
||||
INSERT INTO user_progress
|
||||
(user_id, level_id, completed_at, hints_used, score, level, current_streak)
|
||||
VALUES ($1, $2, NOW(), $3, $4, $5, 0)
|
||||
(user_id, level_id, completed_at, hints_used, score, level, current_streak, wave)
|
||||
VALUES ($1, $2, NOW(), $3, $4, $5, 0, $6)
|
||||
ON CONFLICT (user_id, level_id) DO UPDATE
|
||||
SET completed_at = NOW(),
|
||||
hints_used = $3,
|
||||
score = $4,
|
||||
level = $5,
|
||||
current_streak = 0
|
||||
""", telegram_id, level_id, hints_used, score, level_name)
|
||||
current_streak = 0,
|
||||
wave = $6
|
||||
""", telegram_id, level_id, hints_used, score, level_name, current_wave)
|
||||
|
||||
# 🔧 ОБНОВЛЕНО (07.10.2026): единый счётчик progress.
|
||||
# Обновляем только users.last_completed_level — глобальный.
|
||||
@@ -509,19 +545,22 @@ async def complete_level(request: Request):
|
||||
"SELECT COUNT(*) FROM level_words WHERE level_id = $1", level_id
|
||||
) or 0
|
||||
|
||||
wave_row = await conn.fetchrow(
|
||||
"SELECT session_number, session_level_number FROM user_game_progress WHERE user_id = $1",
|
||||
telegram_id,
|
||||
)
|
||||
session_number = int(wave_row["session_number"] or 1) if wave_row else 1
|
||||
session_level_number = int(wave_row["session_level_number"] or 1) if wave_row else 1
|
||||
|
||||
# Пройдено волн = session_number - 1; если только что завершили
|
||||
# Пройдено волн = current_wave - 1; если только что завершили
|
||||
# 10-й уровень волны — волна пройдена (+1).
|
||||
waves_completed = session_number - 1
|
||||
if session_level_number == 10:
|
||||
waves_completed = current_wave - 1
|
||||
if current_position_in_wave == 10:
|
||||
waves_completed += 1
|
||||
|
||||
# 🆕 (13.10.2026): итоги волны для модалки.
|
||||
from services.waves import max_points_for_wave, wave_medal
|
||||
wave_completed = (current_position_in_wave == 10)
|
||||
wave_points = await conn.fetchval(
|
||||
"SELECT COALESCE(SUM(score), 0) FROM user_progress WHERE user_id = $1 AND wave = $2",
|
||||
telegram_id, current_wave,
|
||||
) or 0
|
||||
wave_max_points = max_points_for_wave()
|
||||
wave_medal_result = wave_medal(wave_points, wave_max_points)
|
||||
|
||||
# XP филворда = сумма score по user_progress (уже посчитана как total_score).
|
||||
wordsearch_xp = total_score
|
||||
|
||||
@@ -603,7 +642,6 @@ async def complete_level(request: Request):
|
||||
"already_completed": False,
|
||||
"new_achievements": new_achievements,
|
||||
# 🆕 XP-поля
|
||||
"stars": xp_result["stars"],
|
||||
"base_points": xp_result["base_points"],
|
||||
"multiplier": xp_result["multiplier"],
|
||||
"points": xp_result["points"],
|
||||
@@ -614,6 +652,12 @@ async def complete_level(request: Request):
|
||||
"rank_key": xp_result["rank_key"],
|
||||
"xp_in_level": xp_result["xp_in_level"],
|
||||
"xp_needed": xp_result["xp_needed"],
|
||||
# 🆕 (13.10.2026): итоги волны для модалки.
|
||||
"wave_completed": wave_completed,
|
||||
"wave_number": current_wave,
|
||||
"wave_points": wave_points,
|
||||
"wave_max_points": wave_max_points,
|
||||
"wave_medal": wave_medal_result,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -76,6 +76,26 @@ async def set_language(request: Request):
|
||||
}
|
||||
|
||||
|
||||
@router.post("/set-difficulty")
|
||||
async def set_difficulty(request: Request):
|
||||
"""Устанавливает уровень сложности (easy/medium/hard)."""
|
||||
user_id, _ = await require_auth(request)
|
||||
body = await request.json()
|
||||
difficulty = body.get("difficulty", "medium")
|
||||
|
||||
if difficulty not in {"easy", "medium", "hard"}:
|
||||
raise HTTPException(400, "Unsupported difficulty")
|
||||
|
||||
pool = await get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
await conn.execute(
|
||||
"UPDATE users SET difficulty = $1 WHERE telegram_id = $2",
|
||||
difficulty, user_id,
|
||||
)
|
||||
|
||||
return {"status": "ok", "difficulty": difficulty}
|
||||
|
||||
|
||||
@router.post("/set-level")
|
||||
async def set_level(request: Request):
|
||||
"""Устанавливает текущий уровень пользователя (A1, A2, B1, B2, C1, C2)"""
|
||||
|
||||
+9
-13
@@ -45,22 +45,18 @@ def grid_size_for(global_level: int) -> int:
|
||||
return sizes[0] if pos <= HALF_WAVE else sizes[1]
|
||||
|
||||
|
||||
def max_stars_for_wave() -> int:
|
||||
"""Максимум звёзд за волну (10 уровней × 5 звёзд)."""
|
||||
return WAVE_SIZE * 5
|
||||
def max_points_for_wave() -> int:
|
||||
"""Максимум очков за волну: 10 уровней × 110 = 1100."""
|
||||
return 10 * 110
|
||||
|
||||
|
||||
def wave_medal(stars_earned: int) -> str:
|
||||
"""
|
||||
Медаль волны по доле звёзд.
|
||||
Пороги: gold >= 90%, silver >= 70%, bronze >= 50%, else 'none'.
|
||||
"""
|
||||
total = max_stars_for_wave()
|
||||
pct = stars_earned / total if total > 0 else 0
|
||||
if pct >= 0.90:
|
||||
def wave_medal(points: int, max_points: int) -> str:
|
||||
"""Медаль за волну: gold ≥90%, silver ≥70%, bronze ≥50%, иначе none."""
|
||||
pct = 100 * points / max_points if max_points > 0 else 0
|
||||
if pct >= 90:
|
||||
return "gold"
|
||||
if pct >= 0.70:
|
||||
if pct >= 70:
|
||||
return "silver"
|
||||
if pct >= 0.50:
|
||||
if pct >= 50:
|
||||
return "bronze"
|
||||
return "none"
|
||||
|
||||
Reference in New Issue
Block a user