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

2048 #988

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

2048 #988

Show file tree
Hide file tree
Changes from 1 commit
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
Binary file added src/images/2048-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
8 changes: 6 additions & 2 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
content="width=device-width, initial-scale=1.0"
/>
<title>2048</title>
<link rel="icon" href="./images/2048-icon.png"/>
<link
rel="stylesheet"
href="./styles/main.scss"
Expand All @@ -24,6 +25,8 @@ <h1>2048</h1>
<button class="button start">Start</button>
</div>
</div>

<h3>Combine the numbers and aim to reach the 2048 tile!</h3>

<table class="game-field">
<tbody>
Expand Down Expand Up @@ -58,13 +61,14 @@ <h1>2048</h1>
</table>

<div class="message-container">
<p class="message message-lose hidden">You lose! Restart the game?</p>
<p class="message message-lose hidden">Game over! Restart the game?</p>
<p class="message message-win hidden">Winner! Congrats! You did it!</p>
<p class="message message-start">
Press "Start" to begin game. Good luck!
</p>
<p class="message message-rule">HOW TO PLAY: Use the arrow keys to move the tiles around. When two tiles with the same number collide, they combine into a single tile!</p>
</div>
</div>
<script src="scripts/main.js"></script>
<script type="module" src="scripts/main.js"></script>
</body>
</html>
322 changes: 260 additions & 62 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,266 @@
'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
constructor(
initialState = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
],
) {
this.score = 0;
this.status = 'idle';
this.initialState = initialState;
this.state = this.copyState(this.initialState);
}

getScore() {
return this.score;
}

getState() {
return this.state;
}

getStatus() {
return this.status;
}

start() {
if (this.status === 'idle') {
this.status = 'playing';
this.addRandomTile();
this.addRandomTile();
}
}

restart() {
this.state = this.copyState(this.initialState);
this.score = 0;
this.status = 'idle';
}

copyState(state) {
return state.map((row) => [...row]);
}

addRandomTile() {
const emptyTiles = [];

for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.state[row][col] === 0) {
emptyTiles.push([row, col]);
}
}
}

if (emptyTiles.length > 0) {
const randomIndex = Math.floor(Math.random() * emptyTiles.length);

const [row, col] = emptyTiles[randomIndex];

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

moveLeft() {
if (this.status !== 'playing') {
return;
}

const moved = this.move('left');

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

moveRight() {
if (this.status !== 'playing') {
return;
}

const moved = this.move('right');

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

moveUp() {
if (this.status !== 'playing') {
return;
}

const moved = this.move('up');

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

moveDown() {
if (this.status !== 'playing') {
return;
}

const moved = this.move('down');

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

move(direction) {
const originalState = this.copyState(this.state);

const combineRow = (row) => {
const newRow = row.filter((n) => n !== 0);

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

return newRow.filter((n) => n !== 0);
};

const moveRowLeft = (row) => {
const newRow = combineRow(row);

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

return newRow;
};

const moveRowRight = (row) => {
const copyRow = [...row];

const newRow = combineRow(copyRow.reverse());

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

return newRow.reverse();
};

const moveStateLeft = (state) => {
return state.map((row) => moveRowLeft(row));
};

const moveStateRight = (state) => {
return state.map((row) => moveRowRight(row));
};

switch (direction) {
case 'left':
this.state = moveStateLeft(this.state);
break;

case 'right':
this.state = moveStateRight(this.state);
break;

case 'up':
this.state = this.transposeState(
moveStateLeft(this.transposeState(this.state)),
);
break;

case 'down':
this.state = this.transposeState(
moveStateRight(this.transposeState(this.state)),
);
break;
}

return !this.areStatesEqual(this.state, originalState);
}

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

return false;
}

canCombine() {
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
const current = this.state[row][col];

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

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

return false;
}

checkGameState() {
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (this.state[row][col] === 2048) {
this.status = 'win';

return;
}
}
}

if (this.hasEmptyCells() || this.canCombine()) {
return;
}
this.status = 'lose';
}

transposeState(state) {
const result = [];

for (let col = 0; col < 4; col++) {
result[col] = [];

for (let row = 0; row < 4; row++) {
result[col].push(state[row][col]);
}
}

return result;
}

areStatesEqual(state1, state2) {
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
if (state1[row][col] !== state2[row][col]) {
return false;
}
}
}

return true;
}
}

module.exports = Game;
Loading
Loading