notebookvb
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
# DailySudoku — technické poznámky
|
||||
|
||||
## Přehled skriptů
|
||||
|
||||
| Skript | Popis |
|
||||
|--------|-------|
|
||||
| `preskumaj_sudoku.py` | Průzkumný — vytáhne `gameLevels` z JS kontextu stránky |
|
||||
| `stahni_sudoku.py` | Stáhne data z webu a uloží do MySQL (celý rok najednou) |
|
||||
| `vykresli_sudoku.py` | Generuje PDF z dat v MySQL (reportlab, vektorové) |
|
||||
|
||||
## Zdroj dat
|
||||
|
||||
Stránka: https://www.solitaire.org/daily-sudoku/
|
||||
|
||||
Stejná architektura jako ostatní puzzle — `game.php` načte `gameLevels` s daty pro celý rok (366 dní × 4 obtížnosti). Klíče `"MM-DD"`, bez roku.
|
||||
|
||||
## Obtížnosti
|
||||
|
||||
| Obtížnost | Mřížka |
|
||||
|-----------|--------|
|
||||
| easy | 9×9 |
|
||||
| medium | 9×9 |
|
||||
| hard | 9×9 |
|
||||
| expert | 9×9 |
|
||||
|
||||
## Datová struktura `gameLevels`
|
||||
|
||||
Každý záznam je objekt `{board, solution}`:
|
||||
```json
|
||||
{
|
||||
"board": "2.78..3.6..5......39.614.7...",
|
||||
"solution": "247895316165723984398614275..."
|
||||
}
|
||||
```
|
||||
|
||||
- `board` = zadání, 81 znaků (9×9), tečka = prázdná buňka
|
||||
- `solution` = řešení, 81 znaků číslic 1–9
|
||||
|
||||
## MySQL tabulka `puzzle.puzzles`
|
||||
|
||||
Sdílená tabulka s ostatními puzzle. Pro Sudoku:
|
||||
- `game_type` = `'sudoku'`
|
||||
- `difficulty` = `'easy'` / `'medium'` / `'hard'` / `'expert'`
|
||||
- `puzzle` = board string (zadání s tečkami)
|
||||
- `solution` = solution string (řešení)
|
||||
- `extra` = `{"grid_size": 9}`
|
||||
- `source` = `'solitaire.org'`
|
||||
|
||||
Stav: celý rok 2026 naplněn (1460 řádků = 365 dní × 4 obtížnosti).
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
Průzkumný skript: připojí se na solitaire.org/daily-sudoku/ a vytáhne
|
||||
surová JS data o puzzle (gameLevels, Game objekt).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
URL = "https://www.solitaire.org/daily-sudoku/"
|
||||
|
||||
|
||||
async def main():
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
context = await browser.new_context(viewport={"width": 1280, "height": 900})
|
||||
|
||||
page = await context.new_page()
|
||||
print(f"Načítám {URL} ...")
|
||||
await page.goto(URL, wait_until="networkidle", timeout=60_000)
|
||||
|
||||
game_url = None
|
||||
for frame in page.frames:
|
||||
if frame.url != page.url and frame.url.strip() not in ("", "about:blank"):
|
||||
game_url = frame.url
|
||||
print(f" Nalezen iframe: {game_url}")
|
||||
break
|
||||
|
||||
if not game_url:
|
||||
iframe_src = await page.get_attribute("iframe", "src")
|
||||
if iframe_src:
|
||||
game_url = iframe_src if iframe_src.startswith("http") else f"https://www.solitaire.org{iframe_src}"
|
||||
print(f" Iframe src z DOM: {game_url}")
|
||||
|
||||
await page.close()
|
||||
|
||||
game_page = await context.new_page()
|
||||
target_url = game_url if game_url else URL
|
||||
print(f"Načítám hru: {target_url} ...")
|
||||
await game_page.goto(target_url, wait_until="networkidle", timeout=60_000)
|
||||
|
||||
# 1) gameLevels — struktura
|
||||
print("\n=== gameLevels — struktura ===")
|
||||
structure = await game_page.evaluate("""() => {
|
||||
if (typeof gameLevels === 'undefined') return null;
|
||||
const result = {};
|
||||
for (const diff of Object.keys(gameLevels)) {
|
||||
const keys = Object.keys(gameLevels[diff]);
|
||||
result[diff] = {
|
||||
count: keys.length,
|
||||
first_keys: keys.slice(0, 3),
|
||||
last_keys: keys.slice(-3),
|
||||
sample_value: gameLevels[diff][keys[0]]
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}""")
|
||||
if structure:
|
||||
print(json.dumps(structure, indent=2, ensure_ascii=False)[:5000])
|
||||
else:
|
||||
print(" gameLevels není definováno")
|
||||
|
||||
# 2) Dnešní data
|
||||
print("\n=== Dnešní data (05-08) ===")
|
||||
today_data = await game_page.evaluate("""() => {
|
||||
const key = '05-08';
|
||||
const result = {};
|
||||
if (typeof gameLevels === 'undefined') return null;
|
||||
for (const diff of Object.keys(gameLevels)) {
|
||||
if (gameLevels[diff] && gameLevels[diff][key]) {
|
||||
result[diff] = gameLevels[diff][key];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}""")
|
||||
if today_data:
|
||||
print(json.dumps(today_data, indent=2, ensure_ascii=False)[:5000])
|
||||
else:
|
||||
print(" žádná data pro dnešek")
|
||||
|
||||
# 3) Game objekt — klíče
|
||||
print("\n=== Game objekt — klíče ===")
|
||||
game_keys = await game_page.evaluate("""() => {
|
||||
if (typeof Game !== 'undefined') return Object.keys(Game);
|
||||
return null;
|
||||
}""")
|
||||
if game_keys:
|
||||
print(json.dumps(game_keys, indent=2))
|
||||
else:
|
||||
print(" Game není definováno")
|
||||
|
||||
await browser.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,97 @@
|
||||
"""
|
||||
Stáhne daily Sudoku puzzle data ze solitaire.org a uloží do MySQL.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.async_api import async_playwright
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "Knihovny"))
|
||||
from mysql_db import connect_mysql
|
||||
|
||||
URL = "https://www.solitaire.org/daily-sudoku/"
|
||||
DIFFICULTIES = ["easy", "medium", "hard", "expert"]
|
||||
|
||||
|
||||
async def fetch_all_levels() -> dict:
|
||||
async with async_playwright() as p:
|
||||
browser = await p.chromium.launch(headless=True)
|
||||
context = await browser.new_context(viewport={"width": 1280, "height": 900})
|
||||
|
||||
page = await context.new_page()
|
||||
print(f"Načítám {URL} ...")
|
||||
await page.goto(URL, wait_until="networkidle", timeout=60_000)
|
||||
|
||||
game_url = None
|
||||
for frame in page.frames:
|
||||
if frame.url != page.url and frame.url.strip() not in ("", "about:blank"):
|
||||
game_url = frame.url
|
||||
break
|
||||
|
||||
if not game_url:
|
||||
iframe_src = await page.get_attribute("iframe", "src")
|
||||
if iframe_src:
|
||||
game_url = iframe_src if iframe_src.startswith("http") else f"https://www.solitaire.org{iframe_src}"
|
||||
|
||||
await page.close()
|
||||
|
||||
game_page = await context.new_page()
|
||||
target_url = game_url if game_url else URL
|
||||
print(f"Načítám hru: {target_url} ...")
|
||||
await game_page.goto(target_url, wait_until="networkidle", timeout=60_000)
|
||||
|
||||
raw = await game_page.evaluate("() => JSON.stringify(gameLevels)")
|
||||
await browser.close()
|
||||
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def save_to_mysql(game_levels: dict, start_date: date, end_date: date):
|
||||
conn = connect_mysql(database="puzzle")
|
||||
cur = conn.cursor()
|
||||
|
||||
inserted = 0
|
||||
d = start_date
|
||||
while d <= end_date:
|
||||
mmdd = d.strftime("%m-%d")
|
||||
date_str = d.strftime("%Y-%m-%d")
|
||||
for diff in DIFFICULTIES:
|
||||
if diff not in game_levels or mmdd not in game_levels[diff]:
|
||||
continue
|
||||
entry = game_levels[diff][mmdd]
|
||||
board = entry["board"]
|
||||
solution = entry["solution"]
|
||||
cur.execute(
|
||||
"INSERT IGNORE INTO puzzles (game_type, difficulty, puzzle_date, puzzle, solution, extra, source) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||
("sudoku", diff, date_str, board, solution,
|
||||
json.dumps({"grid_size": 9}), "solitaire.org"),
|
||||
)
|
||||
if cur.rowcount > 0:
|
||||
inserted += 1
|
||||
d += timedelta(days=1)
|
||||
|
||||
cur.close()
|
||||
conn.close()
|
||||
return inserted
|
||||
|
||||
|
||||
async def main():
|
||||
game_levels = await fetch_all_levels()
|
||||
total = sum(len(game_levels.get(d, {})) for d in DIFFICULTIES)
|
||||
print(f"gameLevels: {total} záznamů")
|
||||
|
||||
inserted = save_to_mysql(game_levels, date(2026, 1, 1), date(2026, 12, 31))
|
||||
print(f"MySQL: vloženo {inserted} nových řádků (celý rok 2026)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,121 @@
|
||||
"""
|
||||
Vykreslí Sudoku puzzle do PDF z dat v MySQL tabulce puzzles.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "Knihovny"))
|
||||
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import A4
|
||||
from reportlab.lib.units import cm
|
||||
from reportlab.pdfbase import pdfmetrics
|
||||
from reportlab.pdfbase.ttfonts import TTFont
|
||||
from reportlab.pdfgen.canvas import Canvas
|
||||
|
||||
from mysql_db import connect_mysql
|
||||
|
||||
_fonts_dir = os.path.join(os.environ.get("WINDIR", r"C:\Windows"), "Fonts")
|
||||
pdfmetrics.registerFont(TTFont("Arial", os.path.join(_fonts_dir, "arial.ttf")))
|
||||
pdfmetrics.registerFont(TTFont("ArialBold", os.path.join(_fonts_dir, "arialbd.ttf")))
|
||||
|
||||
OUTPUT = Path(__file__).parent / "test_sudoku.pdf"
|
||||
|
||||
|
||||
def draw_sudoku(c: Canvas, x0: float, y0: float, cell: float,
|
||||
board: str, title: str = "", show_solution: bool = False,
|
||||
solution: str = ""):
|
||||
num_font = max(cell * 0.5, 7)
|
||||
given_font = max(cell * 0.5, 7)
|
||||
thin = 0.5
|
||||
thick = 2.2
|
||||
|
||||
if title:
|
||||
c.setFont("ArialBold", 12)
|
||||
c.drawString(x0, y0 + 5, title)
|
||||
|
||||
# Bílé pozadí
|
||||
c.setFillColor(colors.white)
|
||||
c.rect(x0, y0 - 9 * cell, 9 * cell, 9 * cell, fill=1, stroke=0)
|
||||
|
||||
# Číslice
|
||||
for i in range(81):
|
||||
row = i // 9
|
||||
col = i % 9
|
||||
cx = x0 + col * cell + cell / 2
|
||||
cy = y0 - (row + 1) * cell + cell * 0.3
|
||||
ch = board[i]
|
||||
|
||||
if ch != ".":
|
||||
c.setFillColor(colors.black)
|
||||
c.setFont("ArialBold", given_font)
|
||||
c.drawCentredString(cx, cy, ch)
|
||||
elif show_solution and solution:
|
||||
c.setFillColor(colors.Color(0.4, 0.4, 0.4))
|
||||
c.setFont("Arial", num_font)
|
||||
c.drawCentredString(cx, cy, solution[i])
|
||||
|
||||
# Tenké čáry
|
||||
c.setStrokeColor(colors.Color(0.6, 0.6, 0.6))
|
||||
c.setLineWidth(thin)
|
||||
for i in range(1, 9):
|
||||
if i % 3 == 0:
|
||||
continue
|
||||
c.line(x0, y0 - i * cell, x0 + 9 * cell, y0 - i * cell)
|
||||
c.line(x0 + i * cell, y0, x0 + i * cell, y0 - 9 * cell)
|
||||
|
||||
# Tlusté čáry (3×3 bloky + vnější okraj)
|
||||
c.setStrokeColor(colors.black)
|
||||
c.setLineWidth(thick)
|
||||
for i in range(0, 10, 3):
|
||||
c.line(x0, y0 - i * cell, x0 + 9 * cell, y0 - i * cell)
|
||||
c.line(x0 + i * cell, y0, x0 + i * cell, y0 - 9 * cell)
|
||||
|
||||
|
||||
def main():
|
||||
conn = connect_mysql(database="puzzle")
|
||||
cur = conn.cursor()
|
||||
cur.execute(
|
||||
"SELECT difficulty, puzzle, solution FROM puzzles "
|
||||
"WHERE game_type='sudoku' AND puzzle_date='2026-05-08' "
|
||||
"ORDER BY FIELD(difficulty, 'easy', 'medium', 'hard', 'expert') "
|
||||
"LIMIT 1"
|
||||
)
|
||||
row = cur.fetchone()
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
if not row:
|
||||
print("Žádná data.")
|
||||
return
|
||||
|
||||
difficulty, board, solution = row
|
||||
|
||||
page_w, page_h = A4
|
||||
board_cm = 11
|
||||
cell = board_cm * cm / 9
|
||||
board_px = 9 * cell
|
||||
|
||||
c = Canvas(str(OUTPUT), pagesize=A4)
|
||||
|
||||
# Zadání
|
||||
x0 = (page_w - board_px) / 2
|
||||
y0 = page_h - 2 * cm
|
||||
draw_sudoku(c, x0, y0, cell, board,
|
||||
f"Sudoku {difficulty.capitalize()} — 2026-05-08")
|
||||
|
||||
# Řešení
|
||||
y0_sol = y0 - board_px - 3 * cm
|
||||
draw_sudoku(c, x0, y0_sol, cell, board,
|
||||
"Řešení", show_solution=True, solution=solution)
|
||||
|
||||
c.save()
|
||||
print(f"PDF uloženo: {OUTPUT}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user