Compare commits
29
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
26442db954 | ||
|
|
e3bc3e8456 | ||
|
|
a6fe755fdb | ||
|
|
959f789f24 | ||
|
|
d181e43ee3 | ||
|
|
6f89336a02 | ||
|
|
f78a1fa19f | ||
|
|
2b5ef446c1 | ||
|
|
50c02b7707 | ||
|
|
6e02303ea8 | ||
|
|
22e4eed3f5 | ||
|
|
5e2de6f7e4 | ||
|
|
2dedec5972 | ||
|
|
8b98655716 | ||
|
|
da7182fb6b | ||
|
|
b62311d3ed | ||
|
|
6f341a7f33 | ||
|
|
981e65e57c | ||
|
|
9c975dde79 | ||
|
|
df3d32ecd5 | ||
|
|
437921d9dd | ||
|
|
bcc01a0fe8 | ||
|
|
8338d6b3c8 | ||
|
|
12c6bbca51 | ||
|
|
794daad69c | ||
|
|
5e9cd0c901 | ||
|
|
ea297b2179 | ||
|
|
791adfeee9 | ||
|
|
0a4c0c5d23 |
+11
@@ -1299,6 +1299,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
|
||||
|
||||
+24
-20
@@ -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",
|
||||
}
|
||||
|
||||
|
||||
@@ -356,11 +357,13 @@ async def complete_level(request: Request):
|
||||
|
||||
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 +419,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"] # для обратной совместимости
|
||||
|
||||
@@ -603,7 +608,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"],
|
||||
|
||||
@@ -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"
|
||||
|
||||
+11
-24
@@ -35,15 +35,6 @@ GAMES = ["wordsearch", "choose", "sentence", "bubbles"]
|
||||
# Множитель игры дня
|
||||
FEATURED_MULTIPLIER = 1.5
|
||||
|
||||
# Базовая ставка: 1 звезда = 20 XP
|
||||
POINTS_PER_STAR = 20
|
||||
|
||||
# Максимум звёзд за уровень
|
||||
MAX_STARS = 5
|
||||
|
||||
# Минимум звёзд за пройденный уровень
|
||||
MIN_STARS = 1
|
||||
|
||||
# Коэффициенты баланса (настроить после первых 1000 сессий)
|
||||
# Применяются к base_points ДО множителя игры дня.
|
||||
GAME_XP_COEF: dict[str, float] = {
|
||||
@@ -192,7 +183,7 @@ async def award_xp(
|
||||
conn,
|
||||
user_id: int,
|
||||
game: str,
|
||||
stars: int,
|
||||
points: int,
|
||||
) -> dict:
|
||||
"""
|
||||
Единая функция начисления опыта.
|
||||
@@ -201,11 +192,10 @@ async def award_xp(
|
||||
conn: asyncpg connection (уже acquired)
|
||||
user_id: telegram_id (может быть отрицательным для Pleily)
|
||||
game: 'wordsearch' | 'choose' | 'sentence' | 'bubbles'
|
||||
stars: 1..5
|
||||
points: готовые очки за уровень (20–110), формула считается до вызова
|
||||
|
||||
Returns:
|
||||
{
|
||||
"stars": int,
|
||||
"base_points": int,
|
||||
"multiplier": float,
|
||||
"points": int,
|
||||
@@ -219,18 +209,16 @@ async def award_xp(
|
||||
}
|
||||
"""
|
||||
# 1. Валидация
|
||||
stars = max(MIN_STARS, min(MAX_STARS, int(stars)))
|
||||
if game not in GAME_XP_COEF:
|
||||
raise ValueError(f"Unknown game: {game}")
|
||||
|
||||
# 2. База
|
||||
base = stars * POINTS_PER_STAR
|
||||
base = int(round(base * GAME_XP_COEF.get(game, 1.0)))
|
||||
# 2. База с коэффициентом игры (для баланса)
|
||||
base_points = int(round(points * GAME_XP_COEF.get(game, 1.0)))
|
||||
|
||||
# 3. Множитель игры дня
|
||||
is_featured = (game == featured_game())
|
||||
multiplier = FEATURED_MULTIPLIER if is_featured else 1.0
|
||||
points = int(round(base * multiplier))
|
||||
final_points = int(round(base_points * multiplier))
|
||||
|
||||
# 4. Читаем текущий total_xp
|
||||
row = await conn.fetchrow(
|
||||
@@ -259,11 +247,11 @@ async def award_xp(
|
||||
INSERT INTO xp_log (user_id, game, stars, base_points, multiplier, points)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
""",
|
||||
user_id, game, stars, base, multiplier, points,
|
||||
user_id, game, 0, base_points, multiplier, final_points,
|
||||
)
|
||||
|
||||
# 6. Обновляем user_profile
|
||||
new_total = old_total + points
|
||||
new_total = old_total + final_points
|
||||
await conn.execute(
|
||||
"""
|
||||
UPDATE user_profile
|
||||
@@ -272,7 +260,7 @@ async def award_xp(
|
||||
updated_at = NOW()
|
||||
WHERE user_id = $1
|
||||
""",
|
||||
user_id, points,
|
||||
user_id, final_points,
|
||||
)
|
||||
|
||||
# 7. Считаем новый уровень
|
||||
@@ -287,14 +275,13 @@ async def award_xp(
|
||||
}
|
||||
logger.info(
|
||||
"[xp] user=%s level_up %s → %s (%s), +%s xp",
|
||||
user_id, old_level, new_level, rank_key, points,
|
||||
user_id, old_level, new_level, rank_key, final_points,
|
||||
)
|
||||
|
||||
return {
|
||||
"stars": stars,
|
||||
"base_points": base,
|
||||
"base_points": base_points,
|
||||
"multiplier": multiplier,
|
||||
"points": points,
|
||||
"points": final_points,
|
||||
"featured": is_featured,
|
||||
"level_up": level_up,
|
||||
"total_xp": new_total,
|
||||
|
||||
Reference in New Issue
Block a user