Skip to content

Commit

Permalink
no add random if board eas not changed
Browse files Browse the repository at this point in the history
  • Loading branch information
taniakolesnik committed Dec 25, 2024
1 parent bff22a7 commit 5710e68
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
27 changes: 20 additions & 7 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,12 @@ class Game {
*/

constructor(initialState = currentState) {
// if (initialState !== currentState) {
// currentState = initialState;
// }
this.initialStateSaved = JSON.parse(JSON.stringify(initialState));
currentState = initialState;
this.score = 0;
this.status = 'idle';
this.gameStarted = false;
this.boardChanged = false;
}

isMovePossibleHorisontally(state) {
Expand Down Expand Up @@ -150,6 +148,9 @@ class Game {
? this.rotateArrayCounterClockwise(result)
: result;

this.boardChanged =
JSON.stringify(currentState) !== JSON.stringify(finalResult);

currentState = finalResult;

return finalResult;
Expand Down Expand Up @@ -179,28 +180,40 @@ class Game {
moveLeft() {
if (this.gameStarted) {
this.moveCells('left');
this.addRandom();

if (this.boardChanged) {
this.addRandom();
}
}
}

moveRight() {
if (this.gameStarted) {
this.moveCells('right');
this.addRandom();

if (this.boardChanged) {
this.addRandom();
}
}
}

moveUp() {
if (this.gameStarted) {
this.moveCells('up');
this.addRandom();

if (this.boardChanged) {
this.addRandom();
}
}
}

moveDown() {
if (this.gameStarted) {
this.moveCells('down');
this.addRandom();

if (this.boardChanged) {
this.addRandom();
}
}
}

Expand Down
12 changes: 4 additions & 8 deletions src/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ const Game = require('../modules/Game.class');
// const game = new Game();

const game = new Game([
[2, 2, 4, 4],
[2, 2, 4, 4],
[2, 2, 4, 4],
[0, 0, 4, 4],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
]);

// // Write your code here
Expand Down Expand Up @@ -46,25 +46,21 @@ document.addEventListener('keydown', (e) => {

if (e.key === 'ArrowLeft') {
game.moveLeft();
// game.addRandom();
drawCells();
}

if (e.key === 'ArrowRight') {
game.moveRight();
// game.addRandom();
drawCells();
}

if (e.key === 'ArrowUp') {
game.moveUp();
// game.addRandom();
drawCells();
}

if (e.key === 'ArrowDown') {
game.moveDown();
// game.addRandom();
drawCells();
}

Expand Down

0 comments on commit 5710e68

Please sign in to comment.