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

Solution #996

Open
wants to merge 1 commit 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
29 changes: 29 additions & 0 deletions .github/workflows/test.yml-template
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: Test

on:
pull_request:
branches: [ master ]

jobs:
build:

runs-on: ubuntu-latest

strategy:
matrix:
node-version: [20.x]

steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm start & sleep 5 && npm test
- name: Upload tests report(cypress mochaawesome merged HTML report)
if: ${{ always() }}
uses: actions/upload-artifact@v2
with:
name: report
path: reports
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://anna-daryna.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
1,314 changes: 741 additions & 573 deletions package-lock.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@mate-academy/eslint-config": "latest",
"@mate-academy/jest-mochawesome-reporter": "^1.0.0",
"@mate-academy/linthtml-config": "latest",
"@mate-academy/scripts": "^1.8.5",
"@mate-academy/scripts": "^1.9.12",
"@mate-academy/stylelint-config": "latest",
"@parcel/transformer-sass": "^2.12.0",
"cypress": "^13.13.0",
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.
9 changes: 8 additions & 1 deletion src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
content="width=device-width, initial-scale=1.0"
/>
<title>2048</title>
<link
rel="icon"
href="images/favicon.png"
/>
<link
rel="stylesheet"
href="./styles/main.scss"
Expand Down Expand Up @@ -65,6 +69,9 @@ <h1>2048</h1>
</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';
}

addRandomTile() {
const emptyTiles = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 column = 0; column < 4; column++) {
if (this.state[row][column] === 0) {
return true;
}
}
}

return false;
}

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

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

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

return false;
}

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

return;
}
}
}

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

transposeState(state) {
const result = [];

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

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

return result;
}

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

return true;
}
}

module.exports = Game;
Loading
Loading