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 #983

Open
wants to merge 7 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
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://1luki9901.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
23 changes: 13 additions & 10 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

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
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
src="scripts/main.js"
type="module"
></script>
</body>
</html>
198 changes: 138 additions & 60 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,146 @@
'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);
constructor(initialState = null) {
this.size = 4;
this.board = initialState || this.createEmptyBoard();
this.score = 0;
this.status = 'idle';
}

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
createEmptyBoard() {
return Array.from({ length: this.size }, () => Array(this.size).fill(0));
}

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

restart() {
this.board = this.createEmptyBoard();
this.score = 0;
this.status = 'idle';
this.start();
}

addRandomTile() {
const emptyCells = [];

// eslint-disable-next-line no-shadow
for (let r = 0; r < this.size; r++) {
// eslint-disable-next-line no-shadow
for (let c = 0; c < this.size; c++) {
if (this.board[r][c] === 0) {
emptyCells.push({ r, c });
}
}
}

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

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

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

moveLeft() {
let moved = false;

for (let r = 0; r < this.size; r++) {
const row = this.board[r].filter((val) => val);

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

while (row.length < this.size) {
row.push(0);
}

if (this.board[r].toString() !== row.toString()) {
moved = true;
}
this.board[r] = row;
}

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

moveRight() {
this.board.forEach((row) => row.reverse());
this.moveLeft();
this.board.forEach((row) => row.reverse());
}

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

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

transpose() {
this.board = this.board[0].map(
(_, colIndex) => this.board.map((row) => row[colIndex]),
// eslint-disable-next-line function-paren-newline
);
}

getScore() {
return this.score;
}

getState() {
return this.board;
}

getStatus() {
if (this.board.flat().includes(2048)) {
return 'win';
}

if (!this.canMove()) {
return 'lose';
}

return this.status;
}

canMove() {
for (let r = 0; r < this.size; r++) {
for (let c = 0; c < this.size; c++) {
if (this.board[r][c] === 0) {
return true;
}

if (c < this.size - 1 && this.board[r][c] === this.board[r][c + 1]) {
return true;
}

if (r < this.size - 1 && this.board[r][c] === this.board[r + 1][c]) {
return true;
}
}
}

return false;
}
}

module.exports = Game;
67 changes: 65 additions & 2 deletions src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,70 @@
'use strict';
// const Game = require('../modules/Game.class');

// Uncomment the next lines to use your game instance in the browser
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is that file?

// const Game = require('../modules/Game.class');
// const game = new Game();
const Game = require('../modules/Game.class');
const game = new Game();

// Write your code here
document.addEventListener('DOMContentLoaded', () => {
const startButton = document.getElementById('start-button');
const scoreElement = document.getElementById('score');
const statusElement = document.getElementById('status');
const gameBoard = document.getElementById('game-board');
const cells = gameBoard.getElementsByClassName('field-cell');

let previousState = [];

function updateUI() {
const state = game.getState();

for (let i = 0; i < cells.length; i++) {
const cell = cells[i];
const value = state[Math.floor(i / 4)][i % 4];

if (previousState[i] !== value) {
cell.className = 'field-cell';

if (value) {
cell.classList.add(`field-cell--${value}`);
cell.textContent = value;
} else {
cell.textContent = '';
}
}
}
previousState = state.flat();
scoreElement.textContent = game.getScore();
statusElement.textContent = game.getStatus();
}

startButton.addEventListener('click', () => {
if (game.getStatus() === 'playing') {
game.restart();
} else {
game.start();
}
updateUI();

startButton.textContent =
game.getStatus() === 'playing' ? 'Restart' : 'Start';
});

const keyMap = {
ArrowLeft: () => game.moveLeft(),
ArrowRight: () => game.moveRight(),
ArrowUp: () => game.moveUp(),
ArrowDown: () => game.moveDown(),
};

// eslint-disable-next-line no-shadow
document.addEventListener('keydown', (event) => {
const moveFunction = keyMap[event.key];

if (moveFunction && moveFunction()) {
updateUI();
}
});

updateUI();
});
Loading