Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f7e7ef8d6 | ||
|
|
e7c512e50e | ||
|
|
0d6b56e5c9 | ||
|
|
4bbaa0030f | ||
|
|
99dd3765d0 | ||
|
|
929420a284 | ||
|
|
3c60cfed31 | ||
|
|
6399d3931c | ||
|
|
07d2d197fd | ||
|
|
1f7ac86ef5 | ||
|
|
16b8956b87 | ||
|
|
959b9c4e3f | ||
|
|
4355b94291 | ||
|
|
bd45071142 | ||
|
|
13fcc8240d | ||
|
|
118345f701 | ||
|
|
4159d6265a | ||
|
|
741d1799e7 | ||
|
|
5644b5be16 | ||
|
|
e65bd5db43 | ||
|
|
6786acb126 | ||
|
|
938d674b09 | ||
|
|
78d40364bf | ||
|
|
26442db954 | ||
|
|
50c02b7707 | ||
|
|
22e4eed3f5 | ||
|
|
8b98655716 |
+40
@@ -898,6 +898,46 @@ async def init_db():
|
|||||||
""")
|
""")
|
||||||
logger.info("Added current_hints_used column to bubble_words_progress")
|
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 ============
|
# ============ wrong_because_explanations ============
|
||||||
await conn.execute("""
|
await conn.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS wrong_because_explanations (
|
CREATE TABLE IF NOT EXISTS wrong_because_explanations (
|
||||||
|
|||||||
+200
-22
@@ -1,5 +1,6 @@
|
|||||||
import random
|
import random
|
||||||
import hashlib # 🔧 НОВОЕ: импорт hashlib для стабильного хэширования
|
import hashlib # 🔧 НОВОЕ: импорт hashlib для стабильного хэширования
|
||||||
|
import json
|
||||||
from fastapi import APIRouter, Request, HTTPException
|
from fastapi import APIRouter, Request, HTTPException
|
||||||
from auth import require_auth
|
from auth import require_auth
|
||||||
from database import get_pool
|
from database import get_pool
|
||||||
@@ -100,7 +101,7 @@ async def get_next_bubble_level(request: Request):
|
|||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
async with pool.acquire() as conn:
|
async with pool.acquire() as conn:
|
||||||
user = await conn.fetchrow(
|
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:
|
if not user:
|
||||||
raise HTTPException(401, "User not registered")
|
raise HTTPException(401, "User not registered")
|
||||||
@@ -162,10 +163,172 @@ async def get_next_bubble_level(request: Request):
|
|||||||
|
|
||||||
random.shuffle(all_parts)
|
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 {
|
return {
|
||||||
"words": result_words,
|
"words": result_words,
|
||||||
"bubbles": all_parts,
|
"bubbles": all_parts,
|
||||||
"level": current_bubble_level,
|
"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 +347,6 @@ async def complete_bubble_level(request: Request):
|
|||||||
body = await request.json()
|
body = await request.json()
|
||||||
words_count = body.get("words_count", 3)
|
words_count = body.get("words_count", 3)
|
||||||
completion_time = body.get("completion_time")
|
completion_time = body.get("completion_time")
|
||||||
list_opened = bool(body.get("list_opened", False))
|
|
||||||
wrong_words = int(body.get("wrong_words", 0) or 0)
|
wrong_words = int(body.get("wrong_words", 0) or 0)
|
||||||
|
|
||||||
pool = await get_pool()
|
pool = await get_pool()
|
||||||
@@ -195,38 +357,55 @@ async def complete_bubble_level(request: Request):
|
|||||||
if not user_exists:
|
if not user_exists:
|
||||||
raise HTTPException(401, "User not registered")
|
raise HTTPException(401, "User not registered")
|
||||||
|
|
||||||
current_level = await conn.fetchval(
|
user = await conn.fetchrow(
|
||||||
"SELECT current_level FROM users WHERE telegram_id = $1", telegram_id
|
"SELECT current_level, difficulty FROM users WHERE telegram_id = $1", telegram_id
|
||||||
) or "A1"
|
)
|
||||||
|
current_level = user["current_level"] or "A1"
|
||||||
|
difficulty = user["difficulty"] or "medium"
|
||||||
|
|
||||||
# Читаем серверный hints_used
|
# Читаем серверные счётчики (не из body)
|
||||||
hints_used = await conn.fetchval(
|
progress = await conn.fetchrow(
|
||||||
"SELECT current_hints_used FROM bubble_words_progress WHERE user_id = $1",
|
"SELECT current_hints_used, current_list_opened "
|
||||||
|
"FROM bubble_words_progress WHERE user_id = $1",
|
||||||
telegram_id
|
telegram_id
|
||||||
) or 0
|
)
|
||||||
|
hints_used = (progress["current_hints_used"] if progress else 0) or 0
|
||||||
hints_used = min(max(0, hints_used), 3)
|
hints_used = min(max(0, hints_used), 3)
|
||||||
|
list_opened = (progress["current_list_opened"] if progress else 0) or 0
|
||||||
|
|
||||||
# 🆕 Расчёт звёзд
|
# 🔧 НОВОЕ (14.10.2026): очки по формуле филворда.
|
||||||
# Старт 5. Штрафы: hints(1) + wrong_words(до 3) + time(1)
|
# Hard — фикс 110. Easy/Medium — 100 − 20×hints − 20×list + bonus.
|
||||||
time_penalty = 1 if (completion_time and completion_time > 60) else 0
|
if difficulty == "hard":
|
||||||
wrong_penalty = min(max(0, wrong_words), 3)
|
if hints_used > 0 or list_opened:
|
||||||
hint_penalty = 1 if hints_used > 0 else 0
|
raise HTTPException(
|
||||||
list_penalty = 1 if list_opened else 0
|
status_code=400,
|
||||||
stars = max(1, 5 - time_penalty - wrong_penalty - hint_penalty - list_penalty)
|
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
|
# Начисляем XP
|
||||||
from services.xp import award_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"]
|
score = xp_result["points"]
|
||||||
|
|
||||||
await conn.execute("""
|
await conn.execute("""
|
||||||
INSERT INTO bubble_words_progress (user_id, levels_completed, total_score, level, current_hints_used)
|
INSERT INTO bubble_words_progress
|
||||||
VALUES ($1, 1, $2, $3, 0)
|
(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
|
ON CONFLICT (user_id) DO UPDATE
|
||||||
SET levels_completed = bubble_words_progress.levels_completed + 1,
|
SET levels_completed = bubble_words_progress.levels_completed + 1,
|
||||||
total_score = bubble_words_progress.total_score + $2,
|
total_score = bubble_words_progress.total_score + $2,
|
||||||
level = $3,
|
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)
|
""", telegram_id, score, current_level)
|
||||||
|
|
||||||
# Данные для достижений
|
# Данные для достижений
|
||||||
@@ -241,7 +420,7 @@ async def complete_bubble_level(request: Request):
|
|||||||
]
|
]
|
||||||
if hints_used == 0:
|
if hints_used == 0:
|
||||||
achievements_to_check.append(("bubble_no_hints", 1))
|
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))
|
achievements_to_check.append(("bubble_perfect", 1))
|
||||||
if completion_time is not None and 0 < completion_time <= 45:
|
if completion_time is not None and 0 < completion_time <= 45:
|
||||||
achievements_to_check.append(("bubble_speed", 45))
|
achievements_to_check.append(("bubble_speed", 45))
|
||||||
@@ -261,7 +440,6 @@ async def complete_bubble_level(request: Request):
|
|||||||
"completion_time": completion_time,
|
"completion_time": completion_time,
|
||||||
"new_achievements": new_achievements,
|
"new_achievements": new_achievements,
|
||||||
# 🆕 XP-поля
|
# 🆕 XP-поля
|
||||||
"stars": xp_result["stars"],
|
|
||||||
"base_points": xp_result["base_points"],
|
"base_points": xp_result["base_points"],
|
||||||
"multiplier": xp_result["multiplier"],
|
"multiplier": xp_result["multiplier"],
|
||||||
"points": xp_result["points"],
|
"points": xp_result["points"],
|
||||||
|
|||||||
Reference in New Issue
Block a user