Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #1083

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open

Develop #1083

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ You can change the HTML/CSS layout if you need it.
## Deploy and Pull Request

1. Replace `<your_account>` with your Github username in the link
- [DEMO LINK](https://<your_account>.github.io/js_2048_game/)
- [DEMO LINK](https://1umamaster.github.io/js_2048_game/)
2. Follow [this instructions](https://mate-academy.github.io/layout_task-guideline/)
- Run `npm run test` command to test your code;
- Run `npm run test:only -- -n` to run fast test ignoring linter;
Expand Down
Binary file added src/images/favicon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 9 additions & 1 deletion src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
rel="stylesheet"
href="./styles/main.scss"
/>
<link
rel="shortcut icon"
href="./images/favicon.png"
type="image/x-icon"
/>
</head>
<body>
<div class="container">
Expand Down Expand Up @@ -65,6 +70,9 @@ <h1>2048</h1>
</p>
</div>
</div>
<script src="scripts/main.js"></script>
<script
type="module"
src="scripts/main.js"
></script>
</body>
</html>
188 changes: 129 additions & 59 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,138 @@
'use strict';

/**
* This class represents the game.
* Now it has a basic structure, that is needed for testing.
* Feel free to add more props and methods if needed.
*/
class Game {
/**
* Creates a new game instance.
*
* @param {number[][]} initialState
* The initial state of the board.
* @default
* [[0, 0, 0, 0],
* [0, 0, 0, 0],
* [0, 0, 0, 0],
* [0, 0, 0, 0]]
*
* If passed, the board will be initialized with the provided
* initial state.
*/
constructor(initialState) {
// eslint-disable-next-line no-console
console.log(initialState);
this.board =
initialState ||
Array(4)
.fill()
.map(() => Array(4).fill(0));
this.score = 0;
this.status = 'idle'; // 'idle', 'playing', 'win', 'lose'
}

moveLeft() {}
moveRight() {}
moveUp() {}
moveDown() {}

/**
* @returns {number}
*/
getScore() {}

/**
* @returns {number[][]}
*/
getState() {}

/**
* Returns the current game status.
*
* @returns {string} One of: 'idle', 'playing', 'win', 'lose'
*
* `idle` - the game has not started yet (the initial state);
* `playing` - the game is in progress;
* `win` - the game is won;
* `lose` - the game is lost
*/
getStatus() {}

/**
* Starts the game.
*/
start() {}

/**
* Resets the game.
*/
restart() {}

// Add your own methods here
getState() {
return this.board;
}

getScore() {
return this.score;
}

getStatus() {
return this.status;
}

start() {
this.board = Array(4)
.fill()
.map(() => Array(4).fill(0));
this.score = 0;
this.status = 'playing';
this.addRandomTile();
this.addRandomTile();
}

restart() {
this.start();
}

moveLeft() {
let moved = false;

this.board = this.board.map((row) => {
const filtered = row.filter((v) => v !== 0);

for (let i = 0; i < filtered.length - 1; i++) {
if (filtered[i] === filtered[i + 1]) {
filtered[i] *= 2;
this.score += filtered[i];
filtered[i + 1] = 0;
moved = true;
}
}

const newRow = filtered.filter((v) => v !== 0);

while (newRow.length < 4) {
newRow.push(0);
}

if (!moved && row.toString() !== newRow.toString()) {
moved = true;
}

return newRow;
});

if (moved) {
this.addRandomTile();
}
this.checkGameState();
}

moveRight() {
this.board = this.board.map((row) => row.reverse());
this.moveLeft();
this.board = this.board.map((row) => row.reverse());
}

moveUp() {
this.transpose();
this.moveLeft();
this.transpose();
}

moveDown() {
this.transpose();
this.moveRight();
this.transpose();
}

addRandomTile() {
const emptyCells = [];

this.board.forEach((row, i) => {
row.forEach((cell, j) => {
if (cell === 0) {
emptyCells.push({ i, j });
}
});
});

if (emptyCells.length > 0) {
const { i, j } =
emptyCells[Math.floor(Math.random() * emptyCells.length)];

this.board[i][j] = Math.random() < 0.9 ? 2 : 4;
}
}

checkGameState() {
if (this.board.flat().includes(2048)) {
this.status = 'win';

return;
}

const movesAvailable = this.board.some((row, i) => {
return row.some((cell, j) => {
return (
cell === 0 ||
(j < 3 && cell === this.board[i][j + 1]) ||
(i < 3 && cell === this.board[i + 1][j])
);
});
});

if (!movesAvailable) {
this.status = 'lose';
}
}

transpose() {
this.board = this.board[0].map((_, i) => this.board.map((row) => row[i]));
}
}

module.exports = Game;
82 changes: 79 additions & 3 deletions src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,83 @@
'use strict';

// Uncomment the next lines to use your game instance in the browser
// const Game = require('../modules/Game.class');
// const game = new Game();
const Game = require('../modules/Game.class');
const game = new Game();

// Write your code here
const cells = document.querySelectorAll('.field-cell');
const scoreElement = document.querySelector('.game-score');
const startButton = document.querySelector('.button.start');
const messages = {
start: document.querySelector('.message-start'),
win: document.querySelector('.message-win'),
lose: document.querySelector('.message-lose'),
};

function updateUI() {
const board = game.getState();

cells.forEach((cell, index) => {
const x = Math.floor(index / 4);
const y = index % 4;
const value = board[x][y];

cell.className = 'field-cell';

if (value > 0) {
cell.classList.add(`field-cell--${value}`);
}
cell.textContent = value || '';
});

scoreElement.textContent = game.getScore();

Object.keys(messages).forEach((key) => {
messages[key].classList.add('hidden');
});

if (game.getStatus() === 'idle') {
messages.start.classList.remove('hidden');
} else if (game.getStatus() === 'win') {
messages.win.classList.remove('hidden');
} else if (game.getStatus() === 'lose') {
messages.lose.classList.remove('hidden');
}

if (game.getStatus() === 'playing' || game.getStatus() === 'lose') {
startButton.textContent = 'Restart';
} else {
startButton.textContent = 'Start';
}

startButton.classList.add('restart');
}

startButton.addEventListener('click', () => {
game.restart();
updateUI();
});

document.addEventListener('keydown', (ev) => {
if (game.getStatus() !== 'playing') {
return;
}

switch (ev.key) {
case 'ArrowLeft':
game.moveLeft();
break;
case 'ArrowRight':
game.moveRight();
break;
case 'ArrowUp':
game.moveUp();
break;
case 'ArrowDown':
game.moveDown();
break;
default:
return;
}

updateUI();
});
Loading