let main = document.querySelector('main'); if (!main) throw ''; const tableSize = 19; const directions = [[1, 0], [1, 1], [0, 1], [-1, 1]]; // let turn = true; /** @typedef {'white' | 'black' | undefined} Square */ /** @typedef {{squares: Square[], whiteTurn: boolean}} State */ /** @type {State} */ let state = {squares: Array(tableSize*tableSize), whiteTurn: true}; /** @type {State[]} */ let hist = []; /** @type {HTMLDivElement[]} */ let squares = []; /** * @param x {number} * @param y {number} * @returns HTMLDivElement */ function get(x, y) { return squares[y * 19 + x]; } function testWin() { for (let by = 0; by < tableSize; by++) { for (let bx = 0; bx < tableSize; bx++) { let a = get(bx, by); if (a.classList.length < 2) { continue; } for (const [dx, dy] of directions) { let aColor = a.classList[1]; let sequence = 1; for (let [x, y] = [bx+dx, by+dy]; x >= 0 && x < tableSize && y >= 0 && y < tableSize; [x, y] = [x + dx, y + dy]) { let b = get(x, y); if (b.classList.length < 2) { aColor = 'skip'; // gambiarra; break; } let bColor = b.classList[1]; if (aColor != bColor) { aColor = 'skip'; // gambiarra; break; } sequence += 1; } if (sequence > 4) { alert('vitória!'); return; } } } } } /** @returns State */ function cloneState() { /** @type {State} */ let ret = {squares: Array(tableSize*tableSize), whiteTurn: state.whiteTurn}; for (let i = 0; i < tableSize*tableSize; i++) { let square = squares[i]; let a = square.classList.values().find((x) => x === 'white') || square.classList.values().find((x) => x === 'black') ret.squares[i] = a; } return ret; } for (let i = 0; i < 19 * 19; i++) { let d = document.createElement('div'); d.classList.add('square'); d.onclick = () => { if (d.classList.contains('white') || d.classList.contains('black') ) { return; } d.classList.add(state.whiteTurn ? 'white' : 'black'); d.classList.remove('hover-white', 'hover-black') state.whiteTurn = !state.whiteTurn; testWin(); hist.push(cloneState()); }; d.onmouseenter = () => { if (d.classList.contains('white') || d.classList.contains('black') ) { return; } d.classList.add(state.whiteTurn ? 'hover-white' : 'hover-black'); } d.onmouseleave = () => { if (d.classList.contains('white') || d.classList.contains('black') ) { return; } d.classList.remove('hover-white', 'hover-black') } main.append(d); squares.push(d); }