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

add task solution #1191

Closed
wants to merge 1 commit into from
Closed
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
5 changes: 4 additions & 1 deletion src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ <h1>2048</h1>
</p>
</div>
</div>
<script src="scripts/main.js"></script>
<script
type="module"
src="scripts/main.js"
></script>
</body>
</html>
164 changes: 152 additions & 12 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,90 @@ class Game {
* initial state.
*/
constructor(initialState) {
// eslint-disable-next-line no-console
console.log(initialState);
this.board =
initialState || Array.from({ length: 4 }, () => Array(4).fill(0));
this.score = 0;
this.addRandomTile();
this.addRandomTile();
}

moveLeft() {}
moveRight() {}
moveUp() {}
moveDown() {}
addRandomTile() {
const emptyCells = [];

for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
if (this.board[r][c] === 0) {
emptyCells.push({ row: r, col: c });
}
}
}

if (emptyCells.length === 0) {
return;
}

const { row, col } =
emptyCells[Math.floor(Math.random() * emptyCells.length)];

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

moveLeft() {
this.board = this.board.map((row) => this.merge(row));
this.addRandomTile();
}

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

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

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

merge(row) {
const newRow = row.filter((num) => num !== 0);

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

return newRow
.filter((num) => num !== 0)
.concat(Array(4).fill(0))
.slice(0, 4);
}

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

/**
* @returns {number}
*/
getScore() {}
getScore() {
return this.score;
}

/**
* @returns {number[][]}
*/
getState() {}
getState() {
return this.board;
}

/**
* Returns the current game status.
Expand All @@ -50,19 +116,93 @@ class Game {
* `win` - the game is won;
* `lose` - the game is lost
*/
getStatus() {}
getStatus() {
if (this.board.some((row) => row.includes(2048))) {
return 'win';
}

if (this.isGameOver()) {
return 'lose';
}

return 'playing';
}

isGameOver() {
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
if (this.board[r][c] === 0) {
return false;
}

if (c < 3 && this.board[r][c] === this.board[r][c + 1]) {
return false;
}

if (r < 3 && this.board[r][c] === this.board[r + 1][c]) {
return false;
}
}
}

return true;
}

/**
* Starts the game.
*/
start() {}
start() {
this.updateUI();

document.addEventListener('keydown', (e) => {
switch (e.key) {
case 'ArrowLeft':
this.moveLeft();
break;
case 'ArrowRight':
this.moveRight();
break;
case 'ArrowUp':
this.moveUp();
break;
case 'ArrowDown':
this.moveDown();
break;
}
});
}

/**
* Resets the game.
*/
restart() {}
restart() {
this.board = Array.from({ length: 4 }, () => Array(4).fill(0));
this.score = 0;
this.addRandomTile();
this.addRandomTile();
}

updateUI() {
const boardElement = document.getElementById('board');

boardElement.innerHTML = '';

// Add your own methods here
this.board.forEach((row) => {
const rowElement = document.createElement('div');

rowElement.classList.add('row');

row.forEach((cell) => {
const cellElement = document.createElement('div');

cellElement.classList.add('cell');
cellElement.textContent = cell !== 0 ? cell : '';
rowElement.appendChild(cellElement);
});
boardElement.appendChild(rowElement);
});
document.getElementById('score').textContent = `Score: ${this.score}`;
}
}

module.exports = Game;
51 changes: 49 additions & 2 deletions src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,54 @@
'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 scoreElement = document.querySelector('.game-score');
const boardElement = document.querySelector('.game-field tbody');
const startButton = document.querySelector('.start');
const messages = document.querySelector('.message-container');

function updateUI() {
scoreElement.textContent = game.getScore();

const board = game.getState();

boardElement.querySelectorAll('.field-cell').forEach((cell, i) => {
const row = Math.floor(i / 4);
const col = i % 4;

cell.textContent = board[row][col] !== 0 ? board[row][col] : '';
cell.className = `field-cell value-${board[row][col] || 0}`;
});

messages
.querySelector('.message-win')
.classList.toggle('hidden', game.getStatus() !== 'win');

messages
.querySelector('.message-lose')
.classList.toggle('hidden', game.getStatus() !== 'lose');
}

document.addEventListener('keydown', (e) => {
const moves = {
ArrowLeft: () => game.moveLeft(),
ArrowRight: () => game.moveRight(),
ArrowUp: () => game.moveUp(),
ArrowDown: () => game.moveDown(),
};

if (moves[e.key]) {
moves[e.key]();
updateUI();
}
});

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

updateUI();
Loading