const ORDER = ['yellow', 'green', 'blue', 'purple']; const EMOJI = { yellow: '🟨', green: '🟩', blue: '🟦', purple: '🟪' }; const MAX_MISTAKES = 4; const $game = document.getElementById('game'); const idMatch = location.pathname.match(/^\/play\/(\d+)/); if (!idMatch) document.getElementById('nav-today').setAttribute('aria-current', 'page'); const state = { game: null, words: [], selected: new Set(), solved: [], mistakes: 0, guesses: [], tried: new Set(), done: false, won: false, showHint: false }; const icon = (name) => el('i', { class: `ph-bold ph-${name}`, 'aria-hidden': 'true' }); async function load() { const { ok, data } = await api(idMatch ? `/api/games/${idMatch[1]}` : '/api/daily'); if (!ok) { document.getElementById('title').textContent = idMatch ? 'Puzzle not found' : 'No puzzle today'; document.getElementById('sub').textContent = data.error || 'Something went wrong.'; $game.replaceChildren(el('div', { class: 'empty' }, 'Pick one from the ', el('a', { href: '/puzzles' }, 'puzzle list'), ' instead.')); return; } state.game = data; state.words = data.words; document.getElementById('title').textContent = data.title; document.title = `${data.title} | NT Connections`; if (data.date) document.getElementById('sub').textContent = `${fmtDate(data.date)}. Create four groups of four.`; render(); } function render() { const board = el('div', { class: 'board' }, state.solved.map((g) => el('div', { class: `solved ${g.color}` }, el('strong', {}, g.name), el('span', {}, g.words.flatMap((w, i) => [i ? ', ' : '', el('span', { class: 'word', 'data-word': w }, w)])))), state.words.length ? el('div', { class: 'row4' }, state.words.map((w) => el('button', { class: 'tile', 'aria-pressed': String(state.selected.has(w)), disabled: state.done, onclick: () => toggle(w) }, w))) : null, ); const kids = [board]; if (state.done) { kids.push(resultPanel()); const details = detailsPanel(); if (details) kids.push(details); } else { kids.push( el('div', { class: 'mistakes', 'aria-label': `${MAX_MISTAKES - state.mistakes} mistakes remaining` }, 'Mistakes remaining:', [...Array(MAX_MISTAKES)].map((_, i) => el('i', { class: i < state.mistakes ? 'used' : '' }))), el('div', { class: 'actions' }, el('button', { class: 'btn', onclick: shuffleWords }, icon('shuffle'), 'Shuffle'), el('button', { class: 'btn', disabled: !state.selected.size, onclick: () => { state.selected.clear(); render(); } }, 'Deselect all'), el('button', { class: 'btn primary', disabled: state.selected.size !== 4, onclick: submit }, 'Submit')), ); if (state.game.hint) { kids.push(state.showHint ? el('p', { class: 'hint' }, icon('lightbulb'), el('span', {}, el('strong', {}, 'Hint: '), state.game.hint)) : el('div', { class: 'hint-toggle' }, el('button', { class: 'btn', onclick: () => { state.showHint = true; render(); } }, icon('lightbulb'), 'Show hint'))); } } // Re-rendering replaces the buttons, so put keyboard focus back on the same one. const focused = $game.contains(document.activeElement) ? document.activeElement.textContent : null; $game.replaceChildren(...kids); if (focused) [...$game.querySelectorAll('button')].find((b) => b.textContent === focused && !b.disabled)?.focus(); } function toggle(w) { if (state.selected.has(w)) state.selected.delete(w); else if (state.selected.size < 4) state.selected.add(w); render(); } function shuffleWords() { const a = state.words; for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } render(); } let busy = false; async function submit() { if (busy) return; const words = [...state.selected]; const key = [...words].sort().join('|'); if (state.tried.has(key)) return toast('Already guessed!'); busy = true; const { ok, data } = await api(`/api/games/${state.game.id}/guess`, { method: 'POST', body: { words } }); busy = false; if (!ok) return toast(data.error || 'Could not check that guess.'); state.tried.add(key); state.guesses.push(words); if (data.result === 'correct') { state.solved.push(data.group); state.words = state.words.filter((w) => !data.group.words.includes(w)); state.selected.clear(); if (state.solved.length === 4) return finish(true); return render(); } state.mistakes++; if (data.result === 'one-away') toast('One away...'); if (state.mistakes >= MAX_MISTAKES) return finish(false); render(); const grid = $game.querySelector('.row4'); grid?.classList.add('shake'); } async function finish(won) { const { ok, data } = await api(`/api/games/${state.game.id}/reveal`, { method: 'POST' }); state.answers = ok ? data.groups : state.solved; if (!won) { const have = new Set(state.solved.map((g) => g.name)); state.solved.push(...state.answers.filter((g) => !have.has(g.name)).sort((a, b) => ORDER.indexOf(a.color) - ORDER.indexOf(b.color))); state.words = []; } state.done = true; state.won = won; state.selected.clear(); render(); } function shareGrid() { const colorOf = (w) => state.answers.find((g) => g.words.includes(w))?.color; return state.guesses.map((guess) => guess.map((w) => EMOJI[colorOf(w)] || '⬜').join('')).join('\n'); } function resultPanel() { const heading = !state.won ? 'Next time' : state.mistakes === 0 ? 'Perfect!' : 'Solved'; const grid = shareGrid(); const text = `NT Connections\n${state.game.title}\n${grid}\n${location.origin}/play/${state.game.id}`; return el('div', { class: 'result' }, el('h2', {}, heading), el('p', { class: 'sub' }, state.won ? `Finished with ${state.mistakes} mistake${state.mistakes === 1 ? '' : 's'}.` : 'Here are the groups.'), el('pre', { 'aria-label': 'Your guesses' }, grid), el('div', { class: 'actions' }, el('button', { class: 'btn primary', onclick: () => share(text) }, icon('copy'), 'Share results'), el('a', { class: 'btn', href: '/puzzles' }, 'More puzzles'))); } function detailsPanel() { const hasAny = state.solved.some((g) => g.details?.some((d) => d.description || d.source)); if (!hasAny) return null; const host = (url) => { try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return 'Source'; } }; return el('section', { class: 'details', 'aria-labelledby': 'details-h' }, el('h2', { id: 'details-h' }, 'About the words'), state.solved.map((g) => el('div', { class: 'detail-group' }, el('h3', {}, el('span', { class: `swatch ${g.color}` }), g.name), el('dl', {}, g.words.map((w, i) => { const d = g.details?.[i] || {}; return el('div', { class: 'detail', 'data-word': w }, el('dt', {}, w), el('dd', {}, d.description || null, d.source ? el('a', { class: 'source', href: d.source, target: '_blank', rel: 'noopener noreferrer' }, icon('arrow-square-out'), host(d.source)) : null)); }))))); } // After the game ends, hovering a word in a solved row highlights its description. function highlight(e, on) { const word = state.done && e.target.closest?.('.solved .word'); if (!word) return; word.classList.toggle('hl', on); $game.querySelector(`.detail[data-word="${CSS.escape(word.dataset.word)}"]`)?.classList.toggle('hl', on); } $game.addEventListener('mouseover', (e) => highlight(e, true)); $game.addEventListener('mouseout', (e) => highlight(e, false)); async function share(text) { try { await navigator.clipboard.writeText(text); toast('Copied to clipboard'); } catch { // Clipboard API needs HTTPS; the grid above is still selectable by hand. toast('Copy failed. Select the grid to copy it.'); } } load();