From 2aa7e37112fd0f389318e3cba9782d98ef926e03 Mon Sep 17 00:00:00 2001 From: doubledebug Date: Mon, 27 Jan 2025 00:23:29 +0100 Subject: [PATCH] feat: added reset game button --- src/index.js | 46 ++++++++++++++++++++++++++++++++++++++-------- src/style.css | 2 +- 2 files changed, 39 insertions(+), 9 deletions(-) diff --git a/src/index.js b/src/index.js index 0cf5a10..669c300 100644 --- a/src/index.js +++ b/src/index.js @@ -4,14 +4,7 @@ import { testDictionary, realDictionary } from './dictionary.js'; console.log('test dictionary:', testDictionary); const dictionary = realDictionary; -const state = { - secret: dictionary[Math.floor(Math.random() * dictionary.length)], - grid: Array(6) - .fill() - .map(() => Array(5).fill('')), - currentRow: 0, - currentCol: 0, -}; +let state = generateGameState(); function drawGrid(container) { const grid = document.createElement('div'); @@ -24,6 +17,14 @@ function drawGrid(container) { } container.appendChild(grid); + + // reset button + const resetBtn = document.createElement('button'); + resetBtn.id = 'btn-reset'; + resetBtn.textContent = 'Reset game'; + resetBtn.style.display = 'none'; + resetBtn.onclick = resetGame; + container.appendChild(resetBtn); } function updateGrid() { @@ -143,6 +144,11 @@ function revealWord(guess) { } else if (isGameOver) { alert(`Better luck next time! The word was ${state.secret}.`); } + + if (isWinner || isGameOver) { + const resetBtn = document.getElementById('btn-reset'); + resetBtn.style.display = 'block'; + } }, 3 * animation_duration); } @@ -162,6 +168,30 @@ function removeLetter() { state.currentCol--; } +function generateGameState() { + return { + secret: dictionary[Math.floor(Math.random() * dictionary.length)], + grid: Array(6) + .fill() + .map(() => Array(5).fill('')), + currentRow: 0, + currentCol: 0, + }; +} + +function resetGame() { + state = generateGameState(); + for (let i = 0; i < state.grid.length; i++) { + for (let j = 0; j < state.grid[i].length; j++) { + const box = document.getElementById(`box${i}${j}`); + box.classList.remove('right', 'wrong', 'empty', 'animated'); + } + } + updateGrid(); + const resetBtn = document.getElementById('btn-reset'); + resetBtn.style.display = 'none'; +} + function startup() { const game = document.getElementById('game'); drawGrid(game); diff --git a/src/style.css b/src/style.css index 86bad05..0e950a4 100644 --- a/src/style.css +++ b/src/style.css @@ -11,7 +11,7 @@ body { } #game { - display: flex; + display: grid; justify-content: center; align-items: start; margin-top: 5rem;