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 2048 game #1130

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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>
222 changes: 162 additions & 60 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,170 @@
/* eslint-disable function-paren-newline */
/* eslint-disable comma-dangle */
'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);
}

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
}
export class Game {
constructor(initialState = null) {
this.board = initialState || this.createEmptyBoard();
this.score = 0;
this.status = 'ready';
}

createEmptyBoard() {
return Array.from({ length: 4 }, () => Array(4).fill(null));
}

spawnTile() {
const emptyCells = [];

this.board.forEach((row, rIndex) => {
row.forEach((cell, cIndex) => {
if (!cell) {
emptyCells.push({ rowIndex: rIndex, colIndex: cIndex });
}
});
});

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

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

this.board[rowIndex][colIndex] = Math.random() < 0.1 ? 4 : 2;
}

getState() {
return this.board;
}

getScore() {
return this.score;
}

getStatus() {
return this.status;
}

canMove() {
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.board[row][col] === null) {
return true;
}

if (
(col < 3 && this.board[row][col] === this.board[row][col + 1]) ||
(row < 3 && this.board[row][col] === this.board[row + 1][col])
) {
return true;
}
}
}

return false;
}

slideAndMerge(row) {
const filteredRow = row.filter((val) => val !== null);
const mergedRow = [];
let skip = false;

module.exports = Game;
for (let i = 0; i < filteredRow.length; i++) {
if (
!skip &&
i < filteredRow.length - 1 &&
filteredRow[i] === filteredRow[i + 1]
) {
mergedRow.push(filteredRow[i] * 2);
this.score += filteredRow[i] * 2;
skip = true;
} else {
mergedRow.push(filteredRow[i]);
skip = false;
}
}

while (mergedRow.length < 4) {
mergedRow.push(null);
}

return mergedRow;
}
moveLeft() {
const previousState = JSON.stringify(this.board);

this.board = this.board.map((row) => this.slideAndMerge(row));

if (JSON.stringify(this.board) !== previousState) {
this.spawnTile();
this.checkGameOver();
}
}
moveRight() {
const previousState = JSON.stringify(this.board);

this.board = this.board.map((row) =>
// eslint-disable-next-line prettier/prettier
this.slideAndMerge(row.slice().reverse()).reverse());

if (JSON.stringify(this.board) !== previousState) {
this.spawnTile();
this.checkGameOver();
}
}

moveUp() {
const previousState = JSON.stringify(this.board);

this.transpose();
this.moveLeft();
this.transpose();

if (JSON.stringify(this.board) !== previousState) {
this.spawnTile();
this.checkGameOver();
}
}
moveDown() {
const previousState = JSON.stringify(this.board);

this.transpose();
this.board = this.board.map((row) =>
this.slideAndMerge(row.slice().reverse()).reverse()
);
this.transpose();

if (JSON.stringify(this.board) !== previousState) {
this.spawnTile();
this.checkGameOver();
}
}
transpose() {
this.board = this.board[0].map((_, colIndex) =>
// eslint-disable-next-line prettier/prettier
this.board.map((row) => row[colIndex]));
}
checkGameOver() {
if (!this.canMove()) {
this.status = 'lost';
} else if (this.board.flat().includes(2048)) {
this.status = 'won';
}
}
start() {
this.board = this.createEmptyBoard();
this.score = 0;
this.status = 'in_progress';
this.spawnTile();
this.spawnTile();
}
restart() {
this.start();
}
}
89 changes: 88 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,91 @@
// const Game = require('../modules/Game.class');
// const game = new Game();

// Write your code here
// Write your code hereimport Game from '../modules/Game.class.js';
import { Game } from '../modules/Game.class.js';

const game = new Game();

function updateUI() {
const board = game.getState();
const score = game.getScore();
const gameStatus = game.getStatus();

const scoreElement = document.querySelector('.game-score');
const cells = document.querySelectorAll('.field-cell');
const winMessage = document.querySelector('.message-win');
const loseMessage = document.querySelector('.message-lose');

if (scoreElement) {
scoreElement.textContent = score;
}

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

cell.textContent = value || '';
cell.className = `field-cell${value ? ` field-cell--${value}` : ''}`;
});
}

if (winMessage && loseMessage) {
if (gameStatus === 'won') {
winMessage.classList.remove('hidden');
loseMessage.classList.add('hidden');
} else if (gameStatus === 'lost') {
loseMessage.classList.remove('hidden');
winMessage.classList.add('hidden');
} else {
winMessage.classList.add('hidden');
loseMessage.classList.add('hidden');
}
}
}

document.querySelector('.button.start').addEventListener('click', (e) => {
const button = e.target;
const messageStart = document.querySelector('.message-start');

if (game.getStatus() === 'ready' || game.getStatus() === 'lost') {
game.start();
updateUI();
button.classList.add('restart');
button.textContent = 'Restart';

if (messageStart) {
messageStart.classList.add('hidden');
}
} else {
game.restart();
updateUI();
}
});

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

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

updateUI();
3 changes: 3 additions & 0 deletions src/styles/main.scss
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,9 @@ h1 {

.restart {
background: #f1b2b2;
display: flex;
align-items: center;
justify-content: center;

&:hover {
background: #f87474;
Expand Down
Loading