Files
cwshed-clone/web/sudoku.html
T

74 lines
18 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">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="manifest" href="/sudoku.webmanifest">
<link rel="apple-touch-icon" href="/favicon.png">
<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; } .masthead-tools { display:flex; align-items:center; gap:12px; } .install-button { min-height:44px; border:1px solid var(--line); border-radius:8px; padding:8px 12px; background:var(--surface); color:var(--ink); font-size:.9rem; font-weight:750; }
.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; }
dialog { width:min(calc(100% - 32px),420px); border:0; border-radius:var(--radius); padding:24px; color:var(--ink); background:var(--surface); box-shadow:0 20px 60px rgba(31,38,33,.25); } dialog::backdrop { background:rgba(31,38,33,.42); } dialog h2 { margin-bottom:14px; } dialog p { margin:0 0 16px; } dialog .button { width:100%; } .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; }
body.playing { height:100dvh; overflow:hidden; } body.playing main { height:100dvh; padding:8px 12px; display:grid; grid-template-rows:auto minmax(0,1fr); } body.playing .masthead { padding-bottom:8px; margin-bottom:8px; } body.playing h1 { font-size:clamp(2rem,10vw,2.7rem); } body.playing .masthead p { max-width:15ch; font-size:.78rem; text-align:right; } body.playing .install-button { display:none; } body.playing .game { display:block; min-height:0; margin:0; } body.playing .game > .panel { height:100%; padding:0; border:0; box-shadow:none; background:transparent; display:flex; flex-direction:column; } body.playing .game-top { flex:0 0 auto; margin:0 0 8px; } body.playing .board { width:min(100%, calc(100dvh - 430px)); max-width:none; flex:0 0 auto; margin:0 auto; } body.playing .numpad { flex:0 0 auto; margin-top:10px; } body.playing .number { min-height:44px; } body.playing .status { margin:8px 0 0; min-height:20px; font-size:.83rem; } body.playing .side { position:fixed; z-index:10; left:0; right:0; bottom:0; display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; padding:8px 12px calc(8px + env(safe-area-inset-bottom)); background:var(--paper); border-top:1px solid var(--soft); } body.playing .side label,body.playing .side .how { display:none; } body.playing .side .button { min-height:48px; padding:8px; font-size:.82rem; } }
@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><div class="masthead-tools"><p>Партии сохраняются по нику.</p><button class="install-button" id="install-button" type="button">Установить</button></div></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>
<dialog id="install-dialog" aria-labelledby="install-title">
<form method="dialog"><h2 id="install-title">Установить Судоку</h2><p id="install-ios">На iPhone или iPad откройте это окно в Safari, нажмите «Поделиться», затем «На экран Домой» и «Добавить».</p><p id="install-android">На Android откройте меню браузера ⋮ и выберите «Установить приложение» или «Добавить на главный экран».</p><button class="button secondary" value="close">Закрыть</button></form>
</dialog>
<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'), installButton=document.querySelector('#install-button'), installDialog=document.querySelector('#install-dialog'), installIos=document.querySelector('#install-ios'), installAndroid=document.querySelector('#install-android');
let game=null, selected=null, startedAt=0, ticker=null, saveTimer=null, installPrompt=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();document.body.classList.add('playing');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;document.body.classList.remove('playing');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();}});
const isIos=/iphone|ipad|ipod/i.test(navigator.userAgent)||(navigator.platform==='MacIntel'&&navigator.maxTouchPoints>1), standalone=window.matchMedia('(display-mode: standalone)').matches||navigator.standalone===true;
if(standalone){installButton.hidden=true;}else{installIos.hidden=!isIos;installAndroid.hidden=isIos;window.addEventListener('beforeinstallprompt',event=>{event.preventDefault();installPrompt=event;});installButton.onclick=async()=>{if(installPrompt){await installPrompt.prompt();installPrompt=null;installButton.hidden=true;return;}installDialog.showModal();};}
if('serviceWorker' in navigator)navigator.serviceWorker.register('/sudoku-sw.js').catch(()=>{});
})();
</script>
</body>
</html>