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 silution #1067

Open
wants to merge 6 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
78 changes: 41 additions & 37 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,51 +7,56 @@ In this task, you need to implement the 2048 game like in [this reference](https
Don't play for too long! We need you to write the code!

Okay, what do we have?
1) HTML and CSS are already written. You can use it, or implement your own design if you want.
2) Base `Game` class structure is already written too. Extend it with your own methods. Obligatory methods (used in tests):
- constructor with `initialState` parameter (value is optional, defaults to the empty board)
- `getState()`
- `getScore()`
- `getStatus()`
- `moveLeft()`
- `moveRight()`
- `moveUp()`
- `moveDown()`
- `start()`
- `restart()`

3) Reference.

1. HTML and CSS are already written. You can use it, or implement your own design if you want.
2. Base `Game` class structure is already written too. Extend it with your own methods. Obligatory methods (used in tests):

- constructor with `initialState` parameter (value is optional, defaults to the empty board)
- `getState()`
- `getScore()`
- `getStatus()`
- `moveLeft()`
- `moveRight()`
- `moveUp()`
- `moveDown()`
- `start()`
- `restart()`

3. Reference.

That's it!

Okay, okay. Also, we have some rules:
1) The game field is 4 x 4
2) Each cell can be empty or contain one of the numbers: 2, 4, 8 ... 2^n
3) The player can move cells with keyboard arrows
4) All the numbers should be moved in the selected direction until all empty cells are filled in

1. The game field is 4 x 4
2. Each cell can be empty or contain one of the numbers: 2, 4, 8 ... 2^n
3. The player can move cells with keyboard arrows
4. All the numbers should be moved in the selected direction until all empty cells are filled in
- 2 equal cells should be merged into a doubled number
- The merged cell can’t be merged twice during one move
5) The move is possible if at least one cell is changed after the move
6) After move 2 or 4 appears in a random empty cell. 4 probability is 10%
7) When 2048 value is displayed in any cell, win message should be shown.
8) The `game over` message should be shown if there are no more available moves.
9) Hide start message when game starts.
10) Change the `Start` button to `Restart` after the first move.
11) `Restart` button should reset the game to the initial state.
12) Increase score with each move. The score should be increased by the sum of all merged cells.
13) The game consists of 2 main parts:
- game logic written in `src/modules/Game.class.js` module that exports `Game` class
- game UI written in `src/index.html` with `main.js` script that need to use `Game` class instance
5. The move is possible if at least one cell is changed after the move
6. After move 2 or 4 appears in a random empty cell. 4 probability is 10%
7. When 2048 value is displayed in any cell, win message should be shown.
8. The `game over` message should be shown if there are no more available moves.
9. Hide start message when game starts.
10. Change the `Start` button to `Restart` after the first move.
11. `Restart` button should reset the game to the initial state.
12. Increase score with each move. The score should be increased by the sum of all merged cells.
13. The game consists of 2 main parts:

- game logic written in `src/modules/Game.class.js` module that exports `Game` class
- game UI written in `src/index.html` with `main.js` script that need to use `Game` class instance

Hints:

- You have class `field-cell--%cell_value%`, for styling cell in the game.
- Use `hidden` class for hiding elements on page.
- Use `start`, `restart` classes for the main button for different styles.
- Use `field-cell--%cell_value%` class like additional class, don't replace the main class.
- Use `keydown` event and `event.key` property to handle arrow buttons presses
```js
document.addEventListener('keydown', event => console.log(event.key));
```
```js
document.addEventListener('keydown', (event) => console.log(event.key));
```
- Adding animation to the game is optional. It is a bit tricky, but you can try it if you want. Probably, you will need to extend the Game class with additional methods and create a separate board storage with Tile entities to operate their corresponding DOM elements' positions.

You can change the HTML/CSS layout if you need it.
Expand All @@ -61,9 +66,8 @@ 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://gorbachovam00.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;
- Run `npm run test:only -- -l` to run fast test with additional info in console ignoring linter.

- Run `npm run test` command to test your code;
- Run `npm run test:only -- -n` to run fast test ignoring linter;
- Run `npm run test:only -- -l` to run fast test with additional info in console ignoring linter.
6 changes: 5 additions & 1 deletion 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="stylesheet"
href="./styles/main.scss"
Expand Down Expand Up @@ -65,6 +66,9 @@ <h1>2048</h1>
</p>
</div>
</div>
<script src="scripts/main.js"></script>
<script
type="module"
src="scripts/main.js"
></script>
</body>
</html>
218 changes: 174 additions & 44 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
/* eslint-disable no-undef */
'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.
Expand All @@ -16,53 +11,188 @@ class Game {
* [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);
STATUSES = {
IDLE: 'IDLE',
IN_PROGRESS: 'IN_PROGRESS',
WON: 'WON',
LOST: 'LOST',
};

constructor(initialState = null) {
this.board = initialState || this.generateEmptyBoard();
this.score = 0;
this.status = this.STATUSES.IDLE;
}

moveLeft() {}
moveRight() {}
moveUp() {}
moveDown() {}
generateEmptyBoard() {
return Array.from({ length: 4 }, () => Array(4).fill(0));
}

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

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

/**
* 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() {}
getStatus() {
return this.status;
}

/**
* Starts the game.
*/
start() {}
moveLeft() {
if (this.status !== this.STATUSES.IN_PROGRESS) {
return;
}
this.move(this.compress(this.board));
}

/**
* Resets the game.
*/
restart() {}
moveRight() {
if (this.status !== this.STATUSES.IN_PROGRESS) {
return;
}
this.move(this.reverse(this.compress(this.reverse(this.board))));
}

moveUp() {
if (this.status !== this.STATUSES.IN_PROGRESS) {
return;
}
this.move(this.transpose(this.compress(this.transpose(this.board))));
}

moveDown() {
if (this.status !== this.STATUSES.IN_PROGRESS) {
return;
}

this.move(
this.transpose(
this.reverse(this.compress(this.reverse(this.transpose(this.board)))),
),
);
}

move(newBoard) {
if (this.board.toString() !== newBoard.toString()) {
this.board = newBoard;
this.addRandomTile();

if (!this.isMoveAvailable()) {
this.status = this.STATUSES.LOST;
}

if (this.checkWin()) {
this.status = this.STATUSES.WON;
}
}
}

// Add your own methods here
compress(board) {
let newBoard = board.map((row) => {
const arr = row.filter((val) => val);
const missing = 4 - arr.length;
const zeroes = Array(missing).fill(0);

arr.push(...zeroes);

return arr;
});

for (let i = 0; i < 4; i++) {
for (let j = 0; j < 3; j++) {
if (newBoard[i][j] === newBoard[i][j + 1] && newBoard[i][j] !== 0) {
newBoard[i][j] *= 2;
this.score += newBoard[i][j];
newBoard[i][j + 1] = 0;
}
}
}

newBoard = newBoard.map((row) => {
const arr = row.filter((val) => val);
const missing = 4 - arr.length;
const zeroes = Array(missing).fill(0);

arr.push(...zeroes);

return arr;
});

return newBoard;
}

reverse(board) {
return board.map((row) => row.reverse());
}

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

isMoveAvailable() {
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
if (this.board[i][j] === 0) {
return true;
}

if (i !== 3 && this.board[i][j] === this.board[i + 1][j]) {
return true;
}

if (j !== 3 && this.board[i][j] === this.board[i][j + 1]) {
return true;
}
}
}

return false;
}

checkWin() {
for (const row of this.board) {
for (const cell of row) {
if (cell === 2048) {
return true;
}
}
}

return false;
}

start() {
this.status = this.STATUSES.IN_PROGRESS;
this.board = this.generateEmptyBoard();
this.score = 0;
this.addRandomTile();
this.addRandomTile();
}

restart() {
this.start();
}

addRandomTile() {
const emptyCells = [];

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

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

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

module.exports = Game;
Loading
Loading