feat: add resumable sudoku game
This commit is contained in:
1 parent
010871474b
commit
83e958e840
12 files changed
+399
-3
No files matched your search
@@ -5,6 +5,8 @@ VK_API_VERSION=5.199
|
|||||||
|
|
||||||
# PostgreSQL is the production history store. Leave empty for local SQLite fallback.
|
# PostgreSQL is the production history store. Leave empty for local SQLite fallback.
|
||||||
BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki
|
BELKI_DATABASE_URL=postgresql://belki:change-me@postgres:5432/belki
|
||||||
|
# Local Sudoku-game fallback when PostgreSQL is unavailable. Production reuses BELKI_DATABASE_URL.
|
||||||
|
SUDOKU_DB=data/sudoku.sqlite3
|
||||||
# SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty.
|
# SQLite fallback/runtime identity database when BELKI_DATABASE_URL is empty.
|
||||||
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
BELKI_IDENTITIES_DB=data/belki.sqlite3
|
||||||
# Required to access /admin and /api/admin/calculations.
|
# Required to access /admin and /api/admin/calculations.
|
||||||
|
|||||||
@@ -59,3 +59,7 @@
|
|||||||
# 2026-08-25: production container architecture
|
# 2026-08-25: production container architecture
|
||||||
|
|
||||||
Production Belki images and Kubernetes workloads require `linux/amd64`. CI sets `DOCKER_DEFAULT_PLATFORM` and passes `--platform linux/amd64`; Dockerfiles and workload node selectors carry the same constraint. The previous private Python base tag `py312-d6c42c4497ce` was published only for arm64 and must not be used for the application image.
|
Production Belki images and Kubernetes workloads require `linux/amd64`. CI sets `DOCKER_DEFAULT_PLATFORM` and passes `--platform linux/amd64`; Dockerfiles and workload node selectors carry the same constraint. The previous private Python base tag `py312-d6c42c4497ce` was published only for arm64 and must not be used for the application image.
|
||||||
|
|
||||||
|
# 2026-08-25: standalone Sudoku
|
||||||
|
|
||||||
|
`/sudoku` is a separate public route, backed by `app/sudoku.py` and `web/sudoku.html`. A supplied nickname (case-insensitive) is intentionally only a resume key, not authentication; never present it as private storage. Games persist in `sudoku_games` through `BELKI_DATABASE_URL` in production or `SUDOKU_DB` locally. The public API must never return the saved solution, and it must keep original clues immutable. The generator is the explicitly requested `dokusan==0.1.0`; it is GPL-3.0-only, Alpha, and last released in 2023, so retain the `NOTICE`/README license disclosure and revalidate it before future runtime upgrades.
|
||||||
@@ -6,3 +6,11 @@ This repository includes legacy CatWar userscript assets and bundled third-party
|
|||||||
- `web/data/jquery-3.4.1.min.js`, `web/data/jquery-ui.js`, and `web/data/jquery.scrollintoview.min.js` are third-party files with retained upstream notices.
|
- `web/data/jquery-3.4.1.min.js`, `web/data/jquery-ui.js`, and `web/data/jquery.scrollintoview.min.js` are third-party files with retained upstream notices.
|
||||||
|
|
||||||
The MIT license in [`LICENSE`](./LICENSE) applies to this project's original code and documentation. It does not replace notices or grant rights beyond the licenses of third-party and legacy files.
|
The MIT license in [`LICENSE`](./LICENSE) applies to this project's original code and documentation. It does not replace notices or grant rights beyond the licenses of third-party and legacy files.
|
||||||
|
# Third-party runtime dependency for /sudoku
|
||||||
|
|
||||||
|
The Sudoku generator and solver uses dokusan 0.1.0 by Aleksei Maslakov
|
||||||
|
(https://github.com/unmade/dokusan), licensed under GNU GPL version 3.0.
|
||||||
|
It is installed as a runtime dependency; its source and licence are available
|
||||||
|
from the upstream project and PyPI. This dependency introduces GPL-3.0-only
|
||||||
|
terms for the distributed application image; review those obligations before
|
||||||
|
redistributing an image containing it.
|
||||||
@@ -39,6 +39,14 @@ python3 -m app.belki.vk_bot
|
|||||||
|
|
||||||
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их через API `https://nyan.nyan404.ru` и сохраняет ссылки вместе с отчётом. Пользовательский интерфейс image-host доступен на `https://img.nyan404.ru`. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же API. Google Sheets пока не подключён.
|
Фотографии из сообщений VK, отправленные во время сценария, сохраняются вместе с подтверждённым расчётом. Веб-калькулятор `/belki` позволяет выбрать несколько скриншотов; сервер загружает их через API `https://nyan.nyan404.ru` и сохраняет ссылки вместе с отчётом. Пользовательский интерфейс image-host доступен на `https://img.nyan404.ru`. Если задан `BELKI_IMAGE_HOST_API_URL`, бот использует тот же API. Google Sheets пока не подключён.
|
||||||
|
|
||||||
|
## Судоку
|
||||||
|
|
||||||
|
`/sudoku` — отдельная публичная игра. Ник служит ключом к партии: с тем же ником незавершённое поле откроется на другом устройстве. Это не учётная запись и не пароль, поэтому в нике нельзя указывать личные данные. Сервер хранит исходные цифры, ход, время и факт завершения; новое поле не удаляет предыдущую партию.
|
||||||
|
|
||||||
|
Сложность задаётся рангом логических техник генератора `dokusan`: лёгкая использует в основном одиночные кандидаты, а сложные уровни допускают более сложные техники. Ответ хранится только на сервере, поэтому клиент не может получить решение через API.
|
||||||
|
|
||||||
|
Для генерации используется `dokusan==0.1.0` под GNU GPL-3.0-only. Это осознанно вводит GPL-3.0-only зависимость в распространяемый образ; подробная оговорка и ссылка на исходники приведены в [`NOTICE`](./NOTICE). Последний релиз пакета датирован 2023 годом и имеет статус Alpha, поэтому при обновлении Python или сборочного образа его нужно отдельно перепроверить.
|
||||||
|
|
||||||
## Заявки
|
## Заявки
|
||||||
|
|
||||||
`/applications` — открытая форма для пожертвования перьев, бельчонка, белки-летяги и куратора; эти же формы находятся на вкладке «Заявки» в `/belki`. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка`: виртуальная клавиатура проводит через выбор типа, пропуск VK-ссылки, ответы «да/нет», «готово» и отмену; вручную вводятся только свободные данные, например ссылки и источники перьев.
|
`/applications` — открытая форма для пожертвования перьев, бельчонка, белки-летяги и куратора; эти же формы находятся на вкладке «Заявки» в `/belki`. Она сохраняет структурированные данные в очередь модерации, а не генерирует форумную отпись. В VK используйте `/заявка`: виртуальная клавиатура проводит через выбор типа, пропуск VK-ссылки, ответы «да/нет», «готово» и отмену; вручную вводятся только свободные данные, например ссылки и источники перьев.
|
||||||
@@ -58,12 +66,14 @@ python3 -m app.belki.vk_bot
|
|||||||
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
|
- `app/belki/domain.py` — расчётное ядро без инфраструктурных зависимостей;
|
||||||
- `app/belki/reports.py` — шаблоны сообщений;
|
- `app/belki/reports.py` — шаблоны сообщений;
|
||||||
- `app/belki/api.py` — JSON API;
|
- `app/belki/api.py` — JSON API;
|
||||||
|
- `app/sudoku.py` — генерация, валидация и PostgreSQL/SQLite-хранилище партий Sudoku;
|
||||||
- `app/belki/applications.py` — валидация и хранилище заявок;
|
- `app/belki/applications.py` — валидация и хранилище заявок;
|
||||||
- `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды;
|
- `app/belki/vk_bot.py` — VK Bots Long Poll и текстовые команды;
|
||||||
- `app/main.py` — веб-сервис и раздача сайта/userscript-файлов;
|
- `app/main.py` — веб-сервис и раздача сайта/userscript-файлов;
|
||||||
- `web/calculator.html` — форма калькулятора;
|
- `web/calculator.html` — форма калькулятора;
|
||||||
- `web/applications.html` — форма подачи заявок;
|
- `web/applications.html` — форма подачи заявок;
|
||||||
- `web/admin.html` — парольная история расчётов для администраторской проверки;
|
- `web/admin.html` — парольная история расчётов для администраторской проверки;
|
||||||
|
- `web/sudoku.html` — адаптивная игра и восстановление партий по нику;
|
||||||
- `tests/` — unit-тесты.
|
- `tests/` — unit-тесты.
|
||||||
|
|
||||||
Спецификация и план находятся в `docs/staging/`.
|
Спецификация и план находятся в `docs/staging/`.
|
||||||
|
|||||||
+54
-3
@@ -18,6 +18,7 @@ from .belki.applications import ApplicationError, ApplicationStore, validate_app
|
|||||||
from .belki.google_sheets_export import GoogleSheetsExportService
|
from .belki.google_sheets_export import GoogleSheetsExportService
|
||||||
from .belki.identity import IdentityDirectory
|
from .belki.identity import IdentityDirectory
|
||||||
from .belki.image_host import ImageHostClient, ImageHostError
|
from .belki.image_host import ImageHostClient, ImageHostError
|
||||||
|
from .sudoku import SudokuError, SudokuStore
|
||||||
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
@@ -25,6 +26,7 @@ WEB_ROOT = ROOT / "web"
|
|||||||
_HISTORY_STORE: CalculationStore | None = None
|
_HISTORY_STORE: CalculationStore | None = None
|
||||||
_IDENTITY_DIR: IdentityDirectory | None = None
|
_IDENTITY_DIR: IdentityDirectory | None = None
|
||||||
_APPLICATION_STORE: ApplicationStore | None = None
|
_APPLICATION_STORE: ApplicationStore | None = None
|
||||||
|
_SUDOKU_STORE: SudokuStore | None = None
|
||||||
_ADMIN_SESSIONS: dict[str, float] = {}
|
_ADMIN_SESSIONS: dict[str, float] = {}
|
||||||
_ADMIN_SESSIONS_LOCK = threading.Lock()
|
_ADMIN_SESSIONS_LOCK = threading.Lock()
|
||||||
_ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {}
|
_ISSUED_WEB_UPLOAD_URLS: dict[str, float] = {}
|
||||||
@@ -166,6 +168,19 @@ def history_store() -> CalculationStore:
|
|||||||
return _HISTORY_STORE
|
return _HISTORY_STORE
|
||||||
|
|
||||||
|
|
||||||
|
def sudoku_store() -> SudokuStore:
|
||||||
|
"""Return the lazily initialized store for resumable Sudoku games."""
|
||||||
|
global _SUDOKU_STORE
|
||||||
|
if _SUDOKU_STORE is None:
|
||||||
|
_SUDOKU_STORE = SudokuStore.from_environment()
|
||||||
|
return _SUDOKU_STORE
|
||||||
|
|
||||||
|
|
||||||
|
def public_sudoku_game(game: dict) -> dict:
|
||||||
|
"""Keep the answer key on the server while returning a playable game."""
|
||||||
|
return {key: value for key, value in game.items() if key != "solution"}
|
||||||
|
|
||||||
|
|
||||||
def identity_dir() -> IdentityDirectory:
|
def identity_dir() -> IdentityDirectory:
|
||||||
"""Лениво создаёт справочник персонажей из окружения."""
|
"""Лениво создаёт справочник персонажей из окружения."""
|
||||||
global _IDENTITY_DIR
|
global _IDENTITY_DIR
|
||||||
@@ -311,6 +326,17 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if path in ("/applications", "/applications/"):
|
if path in ("/applications", "/applications/"):
|
||||||
self._file(WEB_ROOT / "applications.html")
|
self._file(WEB_ROOT / "applications.html")
|
||||||
return
|
return
|
||||||
|
if path in ("/sudoku", "/sudoku/"):
|
||||||
|
self._file(WEB_ROOT / "sudoku.html")
|
||||||
|
return
|
||||||
|
if path == "/api/sudoku/games":
|
||||||
|
try:
|
||||||
|
nickname = parse_qs(urlparse(self.path).query).get("nickname", [""])[0]
|
||||||
|
game = sudoku_store().current(nickname)
|
||||||
|
self._json(200, {"game": public_sudoku_game(game) if game else None})
|
||||||
|
except SudokuError as exc:
|
||||||
|
self._json(400, {"error": str(exc)})
|
||||||
|
return
|
||||||
if path == "/api/admin/session":
|
if path == "/api/admin/session":
|
||||||
self._json(200, {"authenticated": self._admin_session_authorized()})
|
self._json(200, {"authenticated": self._admin_session_authorized()})
|
||||||
return
|
return
|
||||||
@@ -374,13 +400,22 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
def do_POST(self) -> None: # noqa: N802
|
def do_POST(self) -> None: # noqa: N802
|
||||||
"""Обрабатывает вход, авторизацию и создание заявок через POST API."""
|
"""Обрабатывает вход, авторизацию и создание заявок через POST API."""
|
||||||
|
parsed = urlparse(self.path)
|
||||||
|
is_sudoku_create = parsed.path == "/api/sudoku/games"
|
||||||
|
is_sudoku_regenerate = parsed.path.startswith("/api/sudoku/games/") and parsed.path.endswith("/regenerate")
|
||||||
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
if self.path not in ("/api/admin/auth", "/api/admin/logout", "/api/web/upload", "/api/calculate", "/api/inspect-bulk", "/api/resolve-identity",
|
||||||
"/api/applications"):
|
"/api/applications") and not is_sudoku_create and not is_sudoku_regenerate:
|
||||||
self._json(404, {"error": "Не найдено"})
|
self._json(404, {"error": "Не найдено"})
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
payload = self._read_json_body()
|
payload = self._read_json_body()
|
||||||
if self.path == "/api/admin/auth":
|
if is_sudoku_create:
|
||||||
|
self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))})
|
||||||
|
elif is_sudoku_regenerate:
|
||||||
|
game_id = parsed.path.removeprefix("/api/sudoku/games/").removesuffix("/regenerate").strip("/")
|
||||||
|
sudoku_store().get(game_id, payload.get("nickname"))
|
||||||
|
self._json(201, {"game": public_sudoku_game(sudoku_store().create(payload.get("nickname"), payload.get("difficulty")))})
|
||||||
|
elif self.path == "/api/admin/auth":
|
||||||
client_ip = self.client_address[0]
|
client_ip = self.client_address[0]
|
||||||
if not allow_admin_auth_attempt(client_ip):
|
if not allow_admin_auth_attempt(client_ip):
|
||||||
self._json(429, {"error": "Слишком много попыток. Повторите через 15 минут."})
|
self._json(429, {"error": "Слишком много попыток. Повторите через 15 минут."})
|
||||||
@@ -435,13 +470,29 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
else:
|
else:
|
||||||
payload["attachments"] = validate_web_attachments(payload.get("attachments", []))
|
payload["attachments"] = validate_web_attachments(payload.get("attachments", []))
|
||||||
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
self._json(200, calculate_and_store(payload, actor_id=None, source="web"))
|
||||||
except (ApiError, ApplicationError) as exc:
|
except (ApiError, ApplicationError, SudokuError) as exc:
|
||||||
self._json(400, {"error": str(exc)})
|
self._json(400, {"error": str(exc)})
|
||||||
except (ValueError, json.JSONDecodeError) as exc:
|
except (ValueError, json.JSONDecodeError) as exc:
|
||||||
self._json(400, {"error": str(exc)})
|
self._json(400, {"error": str(exc)})
|
||||||
except Exception:
|
except Exception:
|
||||||
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
|
self._json(500, {"error": "Внутренняя ошибка калькулятора"})
|
||||||
|
|
||||||
|
def do_PUT(self) -> None: # noqa: N802
|
||||||
|
"""Save an in-progress Sudoku board for resuming on another device."""
|
||||||
|
parsed = urlparse(self.path)
|
||||||
|
prefix = "/api/sudoku/games/"
|
||||||
|
if not parsed.path.startswith(prefix) or not parsed.path.removeprefix(prefix):
|
||||||
|
self._json(404, {"error": "Не найдено"})
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
payload = self._read_json_body()
|
||||||
|
game = sudoku_store().save(parsed.path.removeprefix(prefix), payload.get("nickname"), payload.get("board"), payload.get("elapsedSeconds"))
|
||||||
|
self._json(200, {"game": public_sudoku_game(game)})
|
||||||
|
except (ApiError, SudokuError) as exc:
|
||||||
|
self._json(400, {"error": str(exc)})
|
||||||
|
except Exception:
|
||||||
|
self._json(500, {"error": "Не удалось сохранить игру"})
|
||||||
|
|
||||||
def do_DELETE(self) -> None: # noqa: N802
|
def do_DELETE(self) -> None: # noqa: N802
|
||||||
"""Удаляет заявку после проверки административной авторизации."""
|
"""Удаляет заявку после проверки административной авторизации."""
|
||||||
parsed = urlparse(self.path)
|
parsed = urlparse(self.path)
|
||||||
|
|||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
"""Sudoku generation, validation, and persistent cross-device game storage."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sqlite3
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from dokusan import generators, solvers
|
||||||
|
from dokusan.boards import BoxSize, Sudoku
|
||||||
|
|
||||||
|
|
||||||
|
class SudokuError(ValueError):
|
||||||
|
"""Raised when a public Sudoku request cannot be accepted."""
|
||||||
|
|
||||||
|
|
||||||
|
DIFFICULTIES = {"easy": 70, "medium": 120, "hard": 180, "expert": 260}
|
||||||
|
NICKNAME_PATTERN = re.compile(r"^[^\s]{2,32}$")
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_nickname(value: object) -> str:
|
||||||
|
"""Validate the deliberately simple nickname used to resume a game."""
|
||||||
|
nickname = str(value or "").strip()
|
||||||
|
if not NICKNAME_PATTERN.fullmatch(nickname):
|
||||||
|
raise SudokuError("Ник должен состоять из 2–32 символов без пробелов")
|
||||||
|
return nickname
|
||||||
|
|
||||||
|
|
||||||
|
def validate_difficulty(value: object) -> str:
|
||||||
|
"""Return one supported difficulty identifier."""
|
||||||
|
difficulty = str(value or "medium")
|
||||||
|
if difficulty not in DIFFICULTIES:
|
||||||
|
raise SudokuError("Выберите сложность: лёгкая, средняя, сложная или экспертная")
|
||||||
|
return difficulty
|
||||||
|
|
||||||
|
|
||||||
|
def generate_game(difficulty: object) -> dict[str, Any]:
|
||||||
|
"""Create a ranked, uniquely solvable puzzle and keep its answer server-side."""
|
||||||
|
selected_difficulty = validate_difficulty(difficulty)
|
||||||
|
puzzle_model = generators.random_sudoku(avg_rank=DIFFICULTIES[selected_difficulty])
|
||||||
|
puzzle = [int(cell) for cell in str(puzzle_model)]
|
||||||
|
solution_model = solvers.backtrack(Sudoku.from_string(str(puzzle_model), box_size=BoxSize(3, 3)))
|
||||||
|
solution = [int(cell) for cell in str(solution_model)]
|
||||||
|
return {"difficulty": selected_difficulty, "puzzle": puzzle, "solution": solution}
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_board(value: object, puzzle: list[int], solution: list[int]) -> tuple[list[int], bool]:
|
||||||
|
"""Accept only a legal player board that preserves initial clues."""
|
||||||
|
if not isinstance(value, list) or len(value) != 81 or any(type(cell) is not int or not 0 <= cell <= 9 for cell in value):
|
||||||
|
raise SudokuError("Поле должно содержать 81 цифру от 0 до 9")
|
||||||
|
board = list(value)
|
||||||
|
for index, clue in enumerate(puzzle):
|
||||||
|
if clue and board[index] != clue:
|
||||||
|
raise SudokuError("Исходные цифры нельзя изменять")
|
||||||
|
for unit in ([row * 9 + column for column in range(9)] for row in range(9)):
|
||||||
|
digits = [board[index] for index in unit if board[index]]
|
||||||
|
if len(digits) != len(set(digits)):
|
||||||
|
raise SudokuError("В строке не должно быть повторяющихся цифр")
|
||||||
|
for unit in ([row * 9 + column for row in range(9)] for column in range(9)):
|
||||||
|
digits = [board[index] for index in unit if board[index]]
|
||||||
|
if len(digits) != len(set(digits)):
|
||||||
|
raise SudokuError("В столбце не должно быть повторяющихся цифр")
|
||||||
|
for box_row in range(0, 9, 3):
|
||||||
|
for box_column in range(0, 9, 3):
|
||||||
|
unit = [(box_row + row_offset) * 9 + box_column + column_offset for row_offset in range(3) for column_offset in range(3)]
|
||||||
|
digits = [board[index] for index in unit if board[index]]
|
||||||
|
if len(digits) != len(set(digits)):
|
||||||
|
raise SudokuError("В квадрате 3×3 не должно быть повторяющихся цифр")
|
||||||
|
return board, board == solution
|
||||||
|
|
||||||
|
|
||||||
|
class SudokuStore:
|
||||||
|
"""Persist Sudoku games in PostgreSQL or a local SQLite fallback."""
|
||||||
|
|
||||||
|
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
||||||
|
self.database_url = database_url or ""
|
||||||
|
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
import psycopg
|
||||||
|
self._psycopg = psycopg
|
||||||
|
self._ensure_postgres_schema()
|
||||||
|
else:
|
||||||
|
self.sqlite_path = self.sqlite_path or Path("data/sudoku.sqlite3")
|
||||||
|
self.sqlite_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._ensure_sqlite_schema()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_environment(cls) -> "SudokuStore":
|
||||||
|
"""Reuse production PostgreSQL while retaining a local SQLite fallback."""
|
||||||
|
return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("SUDOKU_DB", "data/sudoku.sqlite3"))
|
||||||
|
|
||||||
|
def _ensure_sqlite_schema(self) -> None:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS sudoku_games (
|
||||||
|
id TEXT PRIMARY KEY, nickname TEXT NOT NULL, nickname_key TEXT NOT NULL,
|
||||||
|
difficulty TEXT NOT NULL, puzzle_json TEXT NOT NULL, solution_json TEXT NOT NULL,
|
||||||
|
board_json TEXT NOT NULL, elapsed_seconds INTEGER NOT NULL DEFAULT 0,
|
||||||
|
completed_at TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
||||||
|
)""")
|
||||||
|
connection.execute("CREATE INDEX IF NOT EXISTS sudoku_games_active ON sudoku_games(nickname_key, completed_at, updated_at DESC)")
|
||||||
|
|
||||||
|
def _ensure_postgres_schema(self) -> None:
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
connection.execute("""CREATE TABLE IF NOT EXISTS sudoku_games (
|
||||||
|
id UUID PRIMARY KEY, nickname TEXT NOT NULL, nickname_key TEXT NOT NULL,
|
||||||
|
difficulty TEXT NOT NULL, puzzle_json JSONB NOT NULL, solution_json JSONB NOT NULL,
|
||||||
|
board_json JSONB NOT NULL, elapsed_seconds INTEGER NOT NULL DEFAULT 0,
|
||||||
|
completed_at TIMESTAMPTZ, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||||
|
)""")
|
||||||
|
connection.execute("CREATE INDEX IF NOT EXISTS sudoku_games_active ON sudoku_games(nickname_key, completed_at, updated_at DESC)")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _record(row: tuple[Any, ...]) -> dict[str, Any]:
|
||||||
|
game_id, nickname, difficulty, puzzle, solution, board, elapsed, completed_at, created_at, updated_at = row
|
||||||
|
decode = lambda item: json.loads(item) if isinstance(item, str) else item
|
||||||
|
return {"id": str(game_id), "nickname": nickname, "difficulty": difficulty, "puzzle": decode(puzzle), "solution": decode(solution), "board": decode(board), "elapsedSeconds": elapsed, "completedAt": completed_at.isoformat() if hasattr(completed_at, "isoformat") else completed_at, "createdAt": created_at.isoformat() if hasattr(created_at, "isoformat") else created_at, "updatedAt": updated_at.isoformat() if hasattr(updated_at, "isoformat") else updated_at}
|
||||||
|
|
||||||
|
def create(self, nickname: object, difficulty: object) -> dict[str, Any]:
|
||||||
|
nickname = normalize_nickname(nickname)
|
||||||
|
generated = generate_game(difficulty)
|
||||||
|
game_id, now = str(uuid.uuid4()), datetime.now(timezone.utc).isoformat()
|
||||||
|
values = (game_id, nickname, nickname.casefold(), generated["difficulty"], json.dumps(generated["puzzle"]), json.dumps(generated["solution"]), json.dumps(generated["puzzle"]), 0, now, now)
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
connection.execute("INSERT INTO sudoku_games (id, nickname, nickname_key, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())", (game_id, nickname, nickname.casefold(), generated["difficulty"], Jsonb(generated["puzzle"]), Jsonb(generated["solution"]), Jsonb(generated["puzzle"]), 0))
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
connection.execute("INSERT INTO sudoku_games VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)", values)
|
||||||
|
return self.get(game_id, nickname)
|
||||||
|
|
||||||
|
def get(self, game_id: str, nickname: object) -> dict[str, Any]:
|
||||||
|
nickname = normalize_nickname(nickname)
|
||||||
|
query = "SELECT id, nickname, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, completed_at, created_at, updated_at FROM sudoku_games WHERE id = %s AND nickname_key = %s" if self.database_url.startswith(("postgres://", "postgresql://")) else "SELECT id, nickname, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, completed_at, created_at, updated_at FROM sudoku_games WHERE id = ? AND nickname_key = ?"
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
row = connection.execute(query, (game_id, nickname.casefold())).fetchone()
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
row = connection.execute(query, (game_id, nickname.casefold())).fetchone()
|
||||||
|
if row is None:
|
||||||
|
raise SudokuError("Игра не найдена")
|
||||||
|
return self._record(row)
|
||||||
|
|
||||||
|
def current(self, nickname: object) -> dict[str, Any] | None:
|
||||||
|
nickname = normalize_nickname(nickname)
|
||||||
|
placeholder = "%s" if self.database_url.startswith(("postgres://", "postgresql://")) else "?"
|
||||||
|
query = f"SELECT id, nickname, difficulty, puzzle_json, solution_json, board_json, elapsed_seconds, completed_at, created_at, updated_at FROM sudoku_games WHERE nickname_key = {placeholder} ORDER BY (completed_at IS NULL) DESC, updated_at DESC LIMIT 1"
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
row = connection.execute(query, (nickname.casefold(),)).fetchone()
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
row = connection.execute(query, (nickname.casefold(),)).fetchone()
|
||||||
|
return self._record(row) if row else None
|
||||||
|
|
||||||
|
def save(self, game_id: str, nickname: object, board: object, elapsed_seconds: object) -> dict[str, Any]:
|
||||||
|
game = self.get(game_id, nickname)
|
||||||
|
if game["completedAt"]:
|
||||||
|
return game
|
||||||
|
saved_board, complete = _validate_board(board, game["puzzle"], game["solution"])
|
||||||
|
if type(elapsed_seconds) is not int or not 0 <= elapsed_seconds <= 86_400:
|
||||||
|
raise SudokuError("Некорректное игровое время")
|
||||||
|
completed_at = datetime.now(timezone.utc).isoformat() if complete else None
|
||||||
|
params = (json.dumps(saved_board), elapsed_seconds, completed_at, game_id)
|
||||||
|
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
with self._psycopg.connect(self.database_url) as connection:
|
||||||
|
connection.execute("UPDATE sudoku_games SET board_json = %s, elapsed_seconds = %s, completed_at = COALESCE(completed_at, %s), updated_at = NOW() WHERE id = %s", (Jsonb(saved_board), elapsed_seconds, completed_at, game_id))
|
||||||
|
else:
|
||||||
|
with sqlite3.connect(self.sqlite_path) as connection:
|
||||||
|
connection.execute("UPDATE sudoku_games SET board_json = ?, elapsed_seconds = ?, completed_at = COALESCE(completed_at, ?), updated_at = ? WHERE id = ?", (*params[:-1], datetime.now(timezone.utc).isoformat(), game_id))
|
||||||
|
return self.get(game_id, nickname)
|
||||||
+18
@@ -96,6 +96,24 @@ http {
|
|||||||
proxy_pass http://10.12.0.212/applications/;
|
proxy_pass http://10.12.0.212/applications/;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
location = /sudoku {
|
||||||
|
proxy_intercept_errors on;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_pass http://10.12.0.212/sudoku;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /sudoku/ {
|
||||||
|
proxy_intercept_errors on;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_pass http://10.12.0.212/sudoku/;
|
||||||
|
}
|
||||||
|
|
||||||
location ^~ /api/ {
|
location ^~ /api/ {
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Host $host;
|
proxy_set_header Host $host;
|
||||||
|
|||||||
@@ -53,10 +53,16 @@ mindmap
|
|||||||
Attachment mirroring
|
Attachment mirroring
|
||||||
bounded verified raster bytes
|
bounded verified raster bytes
|
||||||
Applications dialog
|
Applications dialog
|
||||||
|
Sudoku
|
||||||
|
/sudoku adaptive game UI
|
||||||
|
nickname-only resume key
|
||||||
|
dokusan ranked generator
|
||||||
|
server-side solution key
|
||||||
Data
|
Data
|
||||||
PostgreSQL production
|
PostgreSQL production
|
||||||
calculations
|
calculations
|
||||||
applications
|
applications
|
||||||
|
sudoku_games
|
||||||
export outbox
|
export outbox
|
||||||
identities and profiles
|
identities and profiles
|
||||||
SQLite local fallback
|
SQLite local fallback
|
||||||
@@ -107,6 +113,7 @@ flowchart LR
|
|||||||
Web --> Store[(PostgreSQL or SQLite)]
|
Web --> Store[(PostgreSQL or SQLite)]
|
||||||
Bot --> Store
|
Bot --> Store
|
||||||
Web --> ImageHost[Image-host API]
|
Web --> ImageHost[Image-host API]
|
||||||
|
Web --> Sudoku[Sudoku game store]
|
||||||
Bot --> ImageHost
|
Bot --> ImageHost
|
||||||
Admin[Администратор] -->|session cookie| Web
|
Admin[Администратор] -->|session cookie| Web
|
||||||
Web --> Admin
|
Web --> Admin
|
||||||
|
|||||||
@@ -1,2 +1,4 @@
|
|||||||
# PostgreSQL driver used by production stores; SQLite remains the local fallback.
|
# PostgreSQL driver used by production stores; SQLite remains the local fallback.
|
||||||
psycopg[binary]==3.3.4
|
psycopg[binary]==3.3.4
|
||||||
|
# GPL-3.0-only Sudoku generator/solver, selected explicitly for /sudoku.
|
||||||
|
dokusan==0.1.0
|
||||||
@@ -47,6 +47,9 @@
|
|||||||
- 2026-08-16 `prevent-eol` check: `python:3.12-slim` is currently maintained through 2028-10-31; Docker `29.6.1-cli` was `unknown` to the EOL catalog (no finding). Docker/CI references remain tag-pinned rather than digest-pinned.
|
- 2026-08-16 `prevent-eol` check: `python:3.12-slim` is currently maintained through 2028-10-31; Docker `29.6.1-cli` was `unknown` to the EOL catalog (no finding). Docker/CI references remain tag-pinned rather than digest-pinned.
|
||||||
|
|
||||||
## Change Log
|
## Change Log
|
||||||
|
- 2026-08-25: added `/sudoku`: a standalone mobile-first game with nickname-based cross-device resume, server-side answer keys, automatic save, new-board generation, and four ranked difficulty presets. `app/sudoku.py` stores `sudoku_games` in the same production PostgreSQL database as Belki, or `SUDOKU_DB` SQLite locally. The API returns no solution data; it validates clues and Sudoku constraints before saving.
|
||||||
|
- 2026-08-25: added `/sudoku` and `/sudoku/` gateway proxies in `nginx.conf`; publishing them requires rebuilding the immutable `Dockerfile.gateway-base` image and updating `Dockerfile.gateway` to its resulting tag before CI/deployment.
|
||||||
|
- 2026-08-25: added `dokusan==0.1.0` as the explicitly selected Sudoku generator/solver. It is GPL-3.0-only and Alpha/last released in 2023; the image's distribution obligations and upstream source are recorded in `NOTICE` and `README.md`. The lifecycle check found the pinned PyPI release available; that is not a security assessment.
|
||||||
- 2026-06-27: updated the Docker CI image to `docker:29.6.1-cli` and aligned the pipeline to `docker:dind` with `DOCKER_HOST=tcp://docker:2375`.
|
- 2026-06-27: updated the Docker CI image to `docker:29.6.1-cli` and aligned the pipeline to `docker:dind` with `DOCKER_HOST=tcp://docker:2375`.
|
||||||
- 2026-06-27: verified the working runner on `docker-03.homelab.local` and confirmed `docker:29.6.1-dind` is reachable from the job network.
|
- 2026-06-27: verified the working runner on `docker-03.homelab.local` and confirmed `docker:29.6.1-dind` is reachable from the job network.
|
||||||
- 2026-08-16: added the Belki calculator domain, report templates, local web form, VK Long Poll adapter, and draft k3s manifests. Deployment remains intentionally deferred.
|
- 2026-08-16: added the Belki calculator domain, report templates, local web form, VK Long Poll adapter, and draft k3s manifests. Deployment remains intentionally deferred.
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
"""Regression tests for generated and resumable Sudoku games."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from tempfile import TemporaryDirectory
|
||||||
|
from pathlib import Path
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from app.sudoku import SudokuError, SudokuStore, generate_game
|
||||||
|
|
||||||
|
|
||||||
|
class SudokuTests(unittest.TestCase):
|
||||||
|
def test_generated_puzzle_has_a_complete_solution(self) -> None:
|
||||||
|
game = generate_game("easy")
|
||||||
|
self.assertEqual(len(game["puzzle"]), 81)
|
||||||
|
self.assertEqual(len(game["solution"]), 81)
|
||||||
|
self.assertTrue(any(cell == 0 for cell in game["puzzle"]))
|
||||||
|
self.assertTrue(all(1 <= cell <= 9 for cell in game["solution"]))
|
||||||
|
|
||||||
|
def test_game_can_be_resumed_with_same_nickname(self) -> None:
|
||||||
|
with TemporaryDirectory() as directory:
|
||||||
|
store = SudokuStore(sqlite_path=Path(directory) / "sudoku.sqlite3")
|
||||||
|
created = store.create("Лис_7", "easy")
|
||||||
|
board = created["board"].copy()
|
||||||
|
empty_cell = board.index(0)
|
||||||
|
board[empty_cell] = created["solution"][empty_cell]
|
||||||
|
saved = store.save(created["id"], "лис_7", board, 42)
|
||||||
|
current = store.current("ЛИС_7")
|
||||||
|
self.assertEqual(saved["board"][empty_cell], created["solution"][empty_cell])
|
||||||
|
self.assertEqual(current["id"], created["id"])
|
||||||
|
self.assertEqual(current["elapsedSeconds"], 42)
|
||||||
|
|
||||||
|
def test_given_cells_and_conflicting_moves_are_rejected(self) -> None:
|
||||||
|
with TemporaryDirectory() as directory:
|
||||||
|
store = SudokuStore(sqlite_path=Path(directory) / "sudoku.sqlite3")
|
||||||
|
created = store.create("Белка", "easy")
|
||||||
|
changed_clue = created["board"].copy()
|
||||||
|
clue_cell = next(index for index, value in enumerate(created["puzzle"]) if value)
|
||||||
|
changed_clue[clue_cell] = 0
|
||||||
|
with self.assertRaisesRegex(SudokuError, "Исходные"):
|
||||||
|
store.save(created["id"], "Белка", changed_clue, 0)
|
||||||
|
conflict = created["board"].copy()
|
||||||
|
empty_cell = conflict.index(0)
|
||||||
|
row_start = empty_cell // 9 * 9
|
||||||
|
conflict[empty_cell] = next(value for value in conflict[row_start:row_start + 9] if value)
|
||||||
|
with self.assertRaisesRegex(SudokuError, "строке"):
|
||||||
|
store.save(created["id"], "Белка", conflict, 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="theme-color" content="#202522">
|
||||||
|
<title>Судоку</title>
|
||||||
|
<style>
|
||||||
|
:root { --ink:#202522; --paper:#f2f4ef; --surface:#fffefa; --line:#9ca39d; --soft:#d9ded7; --accent:#df8d28; --accent-ink:#55320e; --danger:#9c3d32; --muted:#58615a; --radius:14px; font-family:"Avenir Next", "Segoe UI", sans-serif; color:var(--ink); background:var(--paper); }
|
||||||
|
* { box-sizing:border-box; } body { margin:0; min-height:100dvh; background:linear-gradient(90deg,transparent 31px,#dfe3dd 32px,transparent 33px) 0 0/64px 64px,var(--paper); }
|
||||||
|
button,input,select { font:inherit; } button { cursor:pointer; touch-action:manipulation; } button:focus-visible,input:focus-visible,select:focus-visible { outline:3px solid #176b69; outline-offset:3px; }
|
||||||
|
.skip { position:absolute; left:12px; top:-80px; z-index:10; background:var(--ink); color:white; padding:10px; } .skip:focus { top:12px; }
|
||||||
|
main { width:min(100%, 1060px); margin:0 auto; padding:24px 16px calc(32px + env(safe-area-inset-bottom)); }
|
||||||
|
.masthead { display:flex; justify-content:space-between; align-items:baseline; gap:16px; border-bottom:2px solid var(--ink); padding-bottom:16px; margin-bottom:28px; } h1 { font-family:Georgia,serif; font-size:clamp(2.25rem,7vw,4.5rem); letter-spacing:-.055em; margin:0; line-height:.9; } .masthead p { margin:0; color:var(--muted); font-size:.95rem; }
|
||||||
|
.intro, .game { max-width:900px; margin:auto; } .intro { display:grid; gap:24px; grid-template-columns:minmax(0,1.1fr) minmax(280px,.9fr); align-items:start; } .intro-copy { padding-top:12px; } h2 { font-size:1.3rem; margin:0 0 8px; } p { line-height:1.5; } .quiet { color:var(--muted); }
|
||||||
|
.panel { background:var(--surface); border:1px solid var(--soft); border-radius:var(--radius); padding:20px; box-shadow:0 8px 22px rgba(31,38,33,.08); } label { font-weight:700; display:block; margin-bottom:8px; } input,select { width:100%; min-height:48px; border:1px solid var(--line); border-radius:8px; background:white; color:var(--ink); padding:10px 12px; font-size:16px; } .hint { font-size:.9rem; margin:8px 0 0; color:var(--muted); }
|
||||||
|
.button { min-height:48px; border:0; border-radius:8px; padding:10px 16px; font-weight:750; background:var(--ink); color:#fff; transition:background 150ms ease-out,transform 150ms ease-out; } .button:hover { background:#3f4741; } .button:active { transform:translateY(1px); } .button.secondary { color:var(--ink); background:transparent; border:1px solid var(--line); } .button.accent { background:var(--accent); color:var(--accent-ink); } .button[disabled] { opacity:.55; cursor:wait; } .panel .button { margin-top:18px; width:100%; }
|
||||||
|
.game { display:grid; grid-template-columns:minmax(0,1fr) 250px; gap:24px; align-items:start; } .game-top { display:flex; justify-content:space-between; gap:12px; align-items:center; margin-bottom:14px; } .identity { margin:0; font-size:.95rem; color:var(--muted); } .identity strong { color:var(--ink); } .timer { font-variant-numeric:tabular-nums; font-weight:750; font-size:1.2rem; }
|
||||||
|
.board { display:grid; grid-template-columns:repeat(9,1fr); aspect-ratio:1; border:2px solid var(--ink); background:var(--ink); gap:1px; } .cell { min-width:0; border:0; background:var(--surface); color:var(--ink); font-size:clamp(1.1rem,4.5vw,2rem); font-weight:600; } .cell.given { background:#e6eae3; font-weight:800; } .cell.selected { background:#f8d9ab; } .cell.related { background:#eff1ec; } .cell.conflict { background:#f3c6bf; color:#6f251d; } .cell:nth-child(3n):not(:nth-child(9n)) { border-right:2px solid var(--ink); } .cell:nth-child(n+19):nth-child(-n+27),.cell:nth-child(n+46):nth-child(-n+54) { border-bottom:2px solid var(--ink); }
|
||||||
|
.numpad { display:grid; grid-template-columns:repeat(5,1fr); gap:8px; margin-top:16px; } .number { min-height:48px; border:1px solid var(--line); border-radius:8px; background:var(--surface); font-weight:800; font-size:1.08rem; } .number:hover { background:#e6eae3; } .number.erase { grid-column:span 2; font-size:.9rem; }
|
||||||
|
.side { display:grid; gap:12px; } .side .button { width:100%; } .status { min-height:24px; margin:12px 0 0; color:var(--muted); font-size:.92rem; } .status.error { color:var(--danger); font-weight:700; } .status.done { color:#176b69; font-weight:700; } .how { border-top:1px solid var(--soft); padding-top:16px; font-size:.92rem; }
|
||||||
|
.hidden { display:none; } @media (max-width:720px) { main { padding-top:16px; } .masthead { margin-bottom:20px; } .intro,.game { grid-template-columns:1fr; } .game { gap:16px; } .side { grid-template-columns:1fr 1fr; } .side .how { grid-column:1/-1; } .board { max-width:600px; margin:auto; } } @media (prefers-reduced-motion:reduce) { *,*:before,*:after { transition:none!important; } }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<a class="skip" href="#content">К игровому полю</a>
|
||||||
|
<main id="content">
|
||||||
|
<header class="masthead"><h1>Судоку</h1><p>Одна партия — там, где вы её оставили.</p></header>
|
||||||
|
<section class="intro" id="start-view" aria-labelledby="start-title">
|
||||||
|
<div class="intro-copy"><h2 id="start-title">Спокойная задача на 9×9</h2><p>Введите один и тот же ник на телефоне, планшете или компьютере. Незавершённая партия откроется автоматически.</p><p class="quiet">Ник — это способ найти игру, а не пароль: не используйте личные данные.</p></div>
|
||||||
|
<form class="panel" id="start-form"><label for="nickname">Ваш ник</label><input id="nickname" name="nickname" autocomplete="nickname" maxlength="32" spellcheck="false" required placeholder="Например, Лис_7"><p class="hint">2–32 символа, без пробелов.</p><label for="difficulty" style="margin-top:18px">Сложность новой игры</label><select id="difficulty" name="difficulty"><option value="easy">Лёгкая</option><option value="medium" selected>Средняя</option><option value="hard">Сложная</option><option value="expert">Экспертная</option></select><button class="button accent" type="submit">Продолжить</button><p class="status" id="start-status" aria-live="polite"></p></form>
|
||||||
|
</section>
|
||||||
|
<section class="game hidden" id="game-view" aria-label="Игра в судоку">
|
||||||
|
<div class="panel"><div class="game-top"><p class="identity"><strong id="game-nickname"></strong> · <span id="game-difficulty"></span></p><time class="timer" id="timer" aria-label="Прошло времени">00:00</time></div><div class="board" id="board" role="grid" aria-label="Игровое поле судоку"></div><div class="numpad" id="numpad" aria-label="Выбор цифры"></div><p class="status" id="game-status" aria-live="polite"></p></div>
|
||||||
|
<aside class="side"><button class="button" type="button" id="save-button">Сохранить</button><label for="game-difficulty-select">Следующее поле<select id="game-difficulty-select"><option value="easy">Лёгкая</option><option value="medium">Средняя</option><option value="hard">Сложная</option><option value="expert">Экспертная</option></select></label><button class="button secondary" type="button" id="new-button">Новое поле</button><button class="button secondary" type="button" id="change-user">Сменить ник</button><div class="how"><strong>Как играть</strong><br>Выберите пустую клетку, затем цифру. Нули и повторы в строке, столбце или квадрате подсвечиваются.</div></aside>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
<script>
|
||||||
|
(() => {
|
||||||
|
const labels={easy:'Лёгкая',medium:'Средняя',hard:'Сложная',expert:'Экспертная'};
|
||||||
|
const startView=document.querySelector('#start-view'), gameView=document.querySelector('#game-view'), form=document.querySelector('#start-form'), nicknameInput=document.querySelector('#nickname'), difficultyInput=document.querySelector('#difficulty'), gameDifficultyInput=document.querySelector('#game-difficulty-select'), startStatus=document.querySelector('#start-status'), gameStatus=document.querySelector('#game-status'), boardElement=document.querySelector('#board'), numpad=document.querySelector('#numpad');
|
||||||
|
let game=null, selected=null, startedAt=0, ticker=null, saveTimer=null;
|
||||||
|
nicknameInput.value=localStorage.getItem('sudokuNickname')||'';
|
||||||
|
const request=async(url,options={})=>{const response=await fetch(url,{headers:{'Content-Type':'application/json'},...options});const data=await response.json().catch(()=>({}));if(!response.ok)throw new Error(data.error||'Не удалось выполнить запрос');return data;};
|
||||||
|
const elapsed=()=>game?Math.min(86400,game.elapsedSeconds+Math.floor((Date.now()-startedAt)/1000)):0;
|
||||||
|
const formatTime=value=>`${String(Math.floor(value/60)).padStart(2,'0')}:${String(value%60).padStart(2,'0')}`;
|
||||||
|
function conflicts(board){const bad=new Set;for(let row=0;row<9;row++)for(let col=0;col<9;col++){const index=row*9+col,value=board[index];if(!value)continue;for(let other=0;other<81;other++){if(other===index||board[other]!==value)continue;const orow=Math.floor(other/9),ocol=other%9;if(row===orow||col===ocol||(Math.floor(row/3)===Math.floor(orow/3)&&Math.floor(col/3)===Math.floor(ocol/3))){bad.add(index);bad.add(other);}}}return bad;}
|
||||||
|
function render(){if(!game)return;document.querySelector('#game-nickname').textContent=game.nickname;document.querySelector('#game-difficulty').textContent=labels[game.difficulty];gameDifficultyInput.value=game.difficulty;const bad=conflicts(game.board);boardElement.replaceChildren(...game.board.map((value,index)=>{const button=document.createElement('button');button.type='button';button.className=`cell${game.puzzle[index]?' given':''}${selected===index?' selected':''}${selected!==null&&value&&value===game.board[selected]?' related':''}${bad.has(index)?' conflict':''}`;button.textContent=value||'';button.disabled=Boolean(game.puzzle[index])||Boolean(game.completedAt);button.setAttribute('role','gridcell');button.setAttribute('aria-label',`Строка ${Math.floor(index/9)+1}, столбец ${index%9+1}${value?`, цифра ${value}`:', пусто'}`);button.onclick=()=>{selected=index;render();};return button;}));numpad.replaceChildren(...[1,2,3,4,5,6,7,8,9].map(number=>numberButton(String(number),()=>setValue(number))),numberButton('Стереть',()=>setValue(0),'erase'));updateTimer();}
|
||||||
|
function numberButton(text,action,kind=''){const button=document.createElement('button');button.type='button';button.className=`number ${kind}`;button.textContent=text;button.onclick=action;return button;}
|
||||||
|
function setValue(value){if(selected===null||game.puzzle[selected]||game.completedAt)return;game.board[selected]=value;gameStatus.textContent='';gameStatus.className='status';render();clearTimeout(saveTimer);saveTimer=setTimeout(save,650);if(game.board.every(Boolean)&&!conflicts(game.board).size)save();}
|
||||||
|
function updateTimer(){document.querySelector('#timer').textContent=formatTime(elapsed());}
|
||||||
|
function openGame(next){game=next;selected=null;startedAt=Date.now();startView.classList.add('hidden');gameView.classList.remove('hidden');clearInterval(ticker);ticker=setInterval(updateTimer,1000);render();}
|
||||||
|
async function save(){if(!game||game.completedAt)return;const button=document.querySelector('#save-button');button.disabled=true;gameStatus.textContent='Сохранение…';try{const data=await request(`/api/sudoku/games/${game.id}`,{method:'PUT',body:JSON.stringify({nickname:game.nickname,board:game.board,elapsedSeconds:elapsed()})});game=data.game;startedAt=Date.now();gameStatus.textContent=game.completedAt?'Готово. Партия сохранена как завершённая.':'Сохранено. Можно продолжить на другом устройстве.';gameStatus.className=`status ${game.completedAt?'done':''}`;render();}catch(error){gameStatus.textContent=error.message;gameStatus.className='status error';}finally{button.disabled=false;}}
|
||||||
|
async function startNew(){const button=document.querySelector('#new-button');if(game&&!confirm('Создать новое поле? Текущая партия останется сохранённой.'))return;button.disabled=true;try{const data=await request(game?`/api/sudoku/games/${game.id}/regenerate`:'/api/sudoku/games',{method:'POST',body:JSON.stringify({nickname:game.nickname,difficulty:gameDifficultyInput.value})});openGame(data.game);gameStatus.textContent='Новое поле готово.';}catch(error){gameStatus.textContent=error.message;gameStatus.className='status error';}finally{button.disabled=false;}}
|
||||||
|
form.onsubmit=async event=>{event.preventDefault();const nickname=nicknameInput.value.trim();startStatus.textContent='Ищем сохранённую игру…';try{localStorage.setItem('sudokuNickname',nickname);const data=await request(`/api/sudoku/games?nickname=${encodeURIComponent(nickname)}`);if(data.game){openGame(data.game);gameStatus.textContent=data.game.completedAt?'Последняя партия уже завершена. Можно создать новую.':'Незавершённая партия восстановлена.';}else{const created=await request('/api/sudoku/games',{method:'POST',body:JSON.stringify({nickname,difficulty:difficultyInput.value})});openGame(created.game);}}catch(error){startStatus.textContent=error.message;startStatus.className='status error';}};
|
||||||
|
document.querySelector('#save-button').onclick=save;document.querySelector('#new-button').onclick=startNew;document.querySelector('#change-user').onclick=()=>{if(game&&!game.completedAt)save();clearInterval(ticker);game=null;gameView.classList.add('hidden');startView.classList.remove('hidden');nicknameInput.focus();};
|
||||||
|
document.addEventListener('keydown',event=>{if(!game||selected===null||event.metaKey||event.ctrlKey||event.altKey)return;if(/^[1-9]$/.test(event.key)){setValue(Number(event.key));event.preventDefault();}if(event.key==='Backspace'||event.key==='Delete'){setValue(0);event.preventDefault();}});
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in new issue
Block a user