Files
cwshed-clone/web/sudoku.html
T
2026-08-25 21:25:04 +03:00

62 lines
14 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!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>