From a791b79fea2a81864394c8a573f5f97edf8b8e15 Mon Sep 17 00:00:00 2001 From: lucas mendes Date: Wed, 18 Dec 2024 00:38:24 -0300 Subject: [PATCH] =?UTF-8?q?inclus=C3=A3o=20dos=20metodos=20de=20movimento,?= =?UTF-8?q?=20inicializa=C3=A7=C3=A3o,=20start=20e=20restart?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/modules/Game.class.js | 282 ++++++++++++-------------------------- src/scripts/main.js | 111 +-------------- 2 files changed, 90 insertions(+), 303 deletions(-) diff --git a/src/modules/Game.class.js b/src/modules/Game.class.js index d2574d893..35adabd60 100644 --- a/src/modules/Game.class.js +++ b/src/modules/Game.class.js @@ -28,72 +28,57 @@ class Game { [0, 0, 0, 0], ], ) { - // eslint-disable-next-line no-console this.state = 'idle'; this.score = 0; this.initialState = initialState; } - moveLeft() { - if (this.state !== 'idle') { - const moveTheLeft = this.initialState.map((row) => mergeToTheLeft(row)); - - this.state = loseWinState(moveTheLeft); + // eslint-disable-next-line no-console - this.score += calculateScore(this.initialState, moveTheLeft); + moveLeft() { + if (this.state === 'idle') { + return; + } - const newCellAdded = addNewCellRandomCell(moveTheLeft, 1); + const updatedState = this.processMoveLeft(); - this.initialState = newCellAdded; + this.updatedGameState(updatedState); - return this.initialState; - } + return this.initialState; } moveRight() { - if (this.state !== 'idle') { - const moveTheRight = this.initialState.map((row) => mergeToTheRight(row)); - - this.state = loseWinState(moveTheRight); - - this.score += calculateScore(this.initialState, moveTheRight); + if (this.state === 'idle') { + return; + } - const newCellAdded = addNewCellRandomCell(moveTheRight, 1); + const updatedState = this.processMoveRight(); - this.initialState = newCellAdded; + this.updatedGameState(updatedState); - return this.initialState; - } + return this.initialState; } moveUp() { - if (this.state !== 'idle') { - const moveAllNonZeroToTheUp = mergeUp(this.initialState); - - this.state = loseWinState(moveAllNonZeroToTheUp); - - this.score += calculateScore(this.initialState, moveAllNonZeroToTheUp); + if (this.state === 'idle') { + return; + } - const newCellAdded = addNewCellRandomCell(moveAllNonZeroToTheUp, 1); + const updatedState = this.processMoveUp(); - this.initialState = newCellAdded; + this.updatedGameState(updatedState); - return this.initialState; - } + return this.initialState; } moveDown() { - if (this.state !== 'idle') { - const moveAllNonZeroToTheDown = mergeDown(this.initialState); - - this.score += calculateScore(this.initialState, moveAllNonZeroToTheDown); - this.state = loseWinState(moveAllNonZeroToTheDown); + if (this.state === 'idle') { + return; + } - const newCellAdded = addNewCellRandomCell(moveAllNonZeroToTheDown, 1); + const updatedState = this.processMoveDown(); - this.initialState = newCellAdded; + this.updatedGameState(updatedState); - return this.initialState; - } + return this.initialState; } - /** * @returns {number} */ @@ -126,17 +111,11 @@ class Game { * Starts the game. */ start() { - const allInitialDateIsZero = this.initialState - .flat() - .every((value) => value === 0); + const initialStateEmpty = this.isInitialStateAllZeros; - const returnToInitialArray = allInitialDateIsZero - ? addNewCellRandomCell(this.initialState, 2) - : addNewCellRandomCell(this.initialState, 1); + const newInitialState = this.generateInitialState(initialStateEmpty); - this.initialState = returnToInitialArray; - this.score = 0; - this.state = 'playing'; + this.resetGamesState(newInitialState); return this.initialState; } @@ -151,188 +130,103 @@ class Game { [0, 0, 0, 0], [0, 0, 0, 0], ]; + this.score = 0; this.state = 'idle'; return this.initialState; } - // Add your own methods here -} - -function addNewCellRandomCell(initialState, qntOfRandomCellsToAdd) { - const flatGameInARow = initialState.flat(); - const availableIndices = flatGameInARow - .map((value, i) => (value === 0 ? i : null)) - .filter((value) => value !== null); - - if (availableIndices.length === 0) { - return initialState; + // add metodo de inicialização do jogo + isInitialStateAllZeros() { + return this.initialState.flat().every((value) => value === 0); } - for (let i = 0; i < qntOfRandomCellsToAdd; i++) { - if (availableIndices.length === 0) { - break; - } - - const randomIndex = Math.floor(Math.random() * availableIndices.length); - const indexToAdd = availableIndices.splice(randomIndex, 1)[0]; - const randomValue = Math.random() < 0.9 ? 2 : 4; + generateInitialState(isEmpty) { + const numberOfCellsToAdd = isEmpty ? 2 : 1; - flatGameInARow[indexToAdd] = randomValue; + return this.addNewCellRandomCell(this.initialState, numberOfCellsToAdd); } - const returnToInitialArray = []; - - while (flatGameInARow.length) { - returnToInitialArray.push(flatGameInARow.splice(0, 4)); + resetGamesState(newState) { + this.initialState = newState; + this.score = 0; + this.state = 'playing'; } - return returnToInitialArray; -} + // add metodo de atualização do tabuleiro quando se move para a esquerda + processMoveLeft() { + const moveRows = this.initialState.map(this.mergeToTheLeft); + const withNewCell = this.addNewCellRandomCell(moveRows, 1); -function mergeToTheLeft(result) { - for (let i = 0; i < result.length - 1; i++) { - if (result[i] === result[i + 1] && result[i] !== 0) { - result[i] *= 2; - result[i + 1] = 0; - } + return withNewCell; } - const filtered = result.filter((num) => num !== 0); - - while (filtered.length < result.length) { - filtered.push(0); + // atualiza os movimentos independente da direção + updatedGameState(newState) { + this.state = this.loseWinState(newState); + this.score += this.calculateScore(this.initialState, newState); + this.initialState = newState; } - return filtered; -} - -function mergeToTheRight(result) { - let nonZeroValues = result.filter((value) => value !== 0); + // add metodo de atualização do tabuleiro quando se move para a direta + processMoveRight() { + const moveRows = this.initialState(this.mergeToTheRight); + const withNewCell = this.addNewCellRandomCell(moveRows, 1); - for (let i = nonZeroValues.length - 1; i > 0; i--) { - if (nonZeroValues[i] === nonZeroValues[i - 1]) { - nonZeroValues[i] *= 2; - nonZeroValues[i - 1] = 0; - } + return withNewCell; } - // Remove zeros again after merging - nonZeroValues = nonZeroValues.filter((value) => value !== 0); - // Add zeros to the left to maintain the row length - while (nonZeroValues.length < result.length) { - nonZeroValues.unshift(0); - } - - return nonZeroValues; -} - -function mergeDown(initialState) { - const result = initialState.map((col) => [...col]); - - for (let col = 0; col < result[0].length; col++) { - const column = result.map((row) => row[col]); + // add metodo de atualização do tabuleiro quando se move para cima + processMoveUp() { + const moveRows = this.initialState(this.mergeToTheUp); + const withNewCell = this.addNewCellRandomCell(moveRows, 1); - for (let i = column.length - 1; i > 0; i--) { - if (column[i] === column[i - 1] && column[i] !== 0) { - column[i] *= 2; - column[i - 1] = 0; - } - } - - const filtered = column.filter((num) => num !== 0); - - while (filtered.length < column.length) { - filtered.unshift(0); - } - - for (let i = 0; i < result.length; i++) { - result[i][col] = filtered[i]; - } + return withNewCell; } - return result; -} - -function mergeUp(initialState) { - const result = initialState.map((col) => [...col]); - - for (let col = 0; col < result[0].length; col++) { - const column = result.map((row) => row[col]); - - for (let i = 0; i < column.length - 1; i++) { - if (column[i] === column[i + 1] && column[i] !== 0) { - column[i] *= 2; - column[i + 1] = 0; - } - } - - const filtered = column.filter((num) => num !== 0); + // add metodo de atualização do tabuleiro quando se move para baixo + processMoveDown() { + const moveRows = this.initialState(this.mergeToTheDown); + const withNewCell = this.addNewCellRandomCell(moveRows, 1); - while (filtered.length < column.length) { - filtered.push(0); - } - - for (let i = 0; i < result.length; i++) { - result[i][col] = filtered[i]; - } + return withNewCell; } - return result; -} + // add novas celulas ao tabuleiro + addNewCellRandomCell(initialState, qtdCellAdd) { + const matrixInRow = initialState.flat(); -function checkIfWin(initialState) { - for (let i = 0; i < initialState.length; i++) { - for (let j = 0; j < initialState[i].length; j++) { - if (initialState[i][j] === 2048) { - return true; + const indexEvaluation = matrixInRow.forEach((value, index) => { + if (value === 0 && qtdCellAdd > 0) { + matrixInRow[index] = 1; + } else { + matrixInRow[index] = null; } - } - } - - return false; -} + }); -function checkIfLose(initialState) { - for (let i = 0; i < initialState.length; i++) { - for (let j = 0; j < initialState[i].length; j++) { - if (initialState[i][j] === 0) { - return false; - } + if (indexEvaluation.length === 0) { + return initialState; } } - return true; -} + // verifica se perdeu ou ganhou + loseWinState() {} -function loseWinState(initialState) { - const lose = checkIfLose(initialState); - const win = checkIfWin(initialState); + // verifca a pontuação + calculateScore() {} - if (lose) { - return 'lose'; - } + // mescla para a esquerda + mergeToTheLeft() {} - if (win) { - return 'win'; - } - - return 'playing'; -} + // mescla para a direita + mergeToTheRight() {} -function calculateScore(initialState, finalState) { - let score = 0; - - for (let i = 0; i < initialState.length; i++) { - for (let j = 0; j < initialState[i].length; j++) { - if (finalState[i][j] > initialState[i][j]) { - score += finalState[i][j]; - } - } - } + // mescla para cima + mergeToTheUp() {} - return score; + // mescla para baixo + mergeToTheDown() {} } module.exports = Game; diff --git a/src/scripts/main.js b/src/scripts/main.js index 6197fdfa8..21e895dea 100644 --- a/src/scripts/main.js +++ b/src/scripts/main.js @@ -1,115 +1,8 @@ 'use strict'; // Uncomment the next lines to use your game instance in the browser -import Game from '../modules/Game.class.js'; +// import Game from '../modules/Game.class.js'; -const game = new Game(); +// const game = new Game(); // Write your code here -const gameScore = document.querySelector('.game-score'); -const startButton = document.querySelector('.buttom start'); -const messageWin = document.querySelector('.message-win'); -const messageLose = document.querySelector('.message-lose'); -const messageStart = document.querySelector('message-start'); - -const fields = document.querySelector('.field-cell'); - -document.addEventListener('keydown', keypressHandler); -startButton.addEventListener('click', startGame); - -function keypressHandler(e) { - const keyActions = { - Escape: restartGame, - Enter: startGame, - ArrowUp: () => updateBoard(game.moveUp()), - ArrowDown: () => updateBoard(game.moveDown()), - ArrowLeft: () => updateBoard(game.moveLeft()), - ArrowRight: () => updateBoard(game.moveRight()), - }; - - // Ações globais (Escape e Enter) - if (keyActions[e.key] && (e.key === 'Escape' || e.key === 'Enter')) { - keyActions[e.key](); - - return; - } - - // Ações de movimento apenas se o jogo estiver em progresso - if (game.status() === 'playing' && keyActions[e.key]) { - keyActions[e.key](); - - return; - } - - // Gerenciamento de estados de vitoria e derrota - const gameStatusHandlers = { - win: () => { - messageWin.classList.remove('hidden'); - }, - lose: () => { - messageLose.classList.remove('hidden'); - }, - }; - - if (gameStatusHandlers[game.getStatus()]) { - gameStatusHandlers[game.getStatus()](); - startButton.classList.add('start'); - startButton.classList.remove('restart'); - startButton.textContent = 'Start'; - } -} - -function updateBoard(initialState) { - const gameValues = initialState.flat(); - - fields.forEach((field, index) => { - field.textContent = gameValues[index] || ''; - }); - - const score = game.getScore(); - - gameScore.textContent = score; - - const statuss = game.getStatus(); - - if (statuss === 'win') { - messageWin.classList.remove('hidden'); - } else if (statuss === 'lose') { - messageLose.classList.remove('hidden'); - } -} - -function restartGame() { - messageStart.classList.remove('hidden'); - messageWin.classList.add('hidden'); - messageLose.classList.add('hidden'); - startButton.classList.add('start'); - startButton.classList.remove('restart'); - startButton.textContent = 'Start'; - - const initialState = game.restart(); - - updateBoard(initialState); -} - -function startGame() { - if (game.getStatus() === 'idle') { - const initialState = game.start(); - - startButton.textContent = 'Restart'; - startButton.classList.add('restart'); - startButton.classList.remove('start'); - - updateBoard(initialState); - - messageStart.classList.add('hidden'); - messageWin.classList.add('hidden'); - messageLose.classList.remove('hidden'); - - return; - } - - if (game.getStatus() === 'playing') { - restartGame(); - } -}