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

first commit #1172

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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://SerhiiUnhurian.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
9 changes: 5 additions & 4 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>
240 changes: 230 additions & 10 deletions src/modules/Game.class.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,102 @@ class Game {
* If passed, the board will be initialized with the provided
* initial state.
*/
constructor(initialState) {
constructor(initialState = null) {
// eslint-disable-next-line no-console
console.log(initialState);

this.size = 4;
this.score = 0;
this.status = 'idle';

this.board = initialState
? initialState.map((row) => [...row])
: this.createEmptyBoard();
}

createEmptyBoard() {
return Array.from({ length: this.size }, () => Array(this.size).fill(0));
}

moveLeft() {}
moveRight() {}
moveUp() {}
moveDown() {}
moveLeft() {
if (this.getStatus() === 'playing') {
let moved = false;

for (let row = 0; row < this.board.length; row++) {
let newRow = this.board[row].filter((tile) => tile !== 0);

for (let col = 0; col < newRow.length - 1; col++) {
if (newRow[col] !== 0 && newRow[col] === newRow[col + 1]) {
newRow[col] *= 2;
newRow[col + 1] = 0;
this.score += newRow[col];
moved = true;
}
}
newRow = newRow.filter((tile) => tile !== 0);

while (newRow.length < this.board[row].length) {
newRow.push(0);
}

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

if (moved) {
this.createRandomTile();
this.checkGameStatus();
}

return moved;
}
}

moveRight() {
if (this.getStatus() === 'playing') {
this.board = this.board.map((row) => row.reverse());
this.moveLeft();
this.board = this.board.map((row) => row.reverse());
}
}
moveUp() {
if (this.getStatus() === 'playing') {
this.transposeBoard();
this.moveLeft();
this.transposeBoard();
}
}
moveDown() {
if (this.getStatus() === 'playing') {
this.transposeBoard();
this.moveRight();
this.transposeBoard();
}
}

transposeBoard() {
this.board = this.board[0].map((_, colIndex) =>
// eslint-disable-next-line prettier/prettier
this.board.map((row) => row[colIndex]));

return this.board;
}

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

/**
* @returns {number[][]}
*/
getState() {}
getState() {
return this.board.map((row) => [...row]);
}

/**
* Returns the current game status.
Expand All @@ -50,19 +127,162 @@ class Game {
* `win` - the game is won;
* `lose` - the game is lost
*/
getStatus() {}
getStatus() {
return this.status;
}

initGame() {
this.board = this.createEmptyBoard();
this.createRandomTile();
this.createRandomTile();
this.status = 'playing';
// this.updateTable();
}

/**
* Starts the game.
*/
start() {}
start() {
this.initGame();
}

/**
* Resets the game.
*/
restart() {}
restart() {
this.board = this.createEmptyBoard();
this.score = 0;
this.status = 'idle';
}

// Add your own methods here

randomNumber(max) {
return Math.floor(Math.random() * (max + 1));
}

generateCellValue() {
return Math.random() < 0.9 ? 2 : 4;
}

// updateTable() {
// const cells = document.querySelectorAll('.field-cell');
// let index = 0;

// this.board.forEach((row) => {
// row.forEach((cellValue) => {
// const cell = cells[index++];

// cell.textContent = cellValue !== 0 ? cellValue : '';
// eslint-disable-next-line max-len
// cell.className = `field-cell ${cellValue ? 'field-cell--' + cellValue : ''}`;
// });
// });
// }

Choose a reason for hiding this comment

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

Remove all comments


createRandomTile() {
const emptyCells = [];

// eslint-disable-next-line no-shadow
this.board.forEach((row, rowIndex) => {
// eslint-disable-next-line no-shadow
row.forEach((cell, cellIndex) => {
if (cell === 0) {
emptyCells.push({ rowIndex, cellIndex });
}
});
});

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

const randomIndex = this.randomNumber(emptyCells.length - 1);
const { rowIndex, cellIndex } = emptyCells[randomIndex];

const newBoard = this.board.map((row) => row.slice());

newBoard[rowIndex][cellIndex] = this.generateCellValue();
this.board = newBoard;
}

checkGameStatus() {
for (const row of this.board) {
if (row.includes(2048)) {
this.status = 'win';

return;
}
}

for (const row of this.board) {
if (row.includes(0)) {
return;
}
}

if (!this.canMakeMove()) {
this.status = 'lose';
}
}

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

for (let row = 0; row < this.size; row++) {
for (let col = 0; col < this.size - 1; col++) {
if (
(this.board[row][col] === this.board[row][col + 1] &&
this.board[row][col] !== 0) ||
(this.board[row][col] !== 0 && this.hasMergeableTilesInRow(row))
) {
return true;
}
}
}

for (let col = 0; col < this.size; col++) {
for (let row = 0; row < this.size - 1; row++) {
if (this.board[row][col] === this.board[row + 1][col]) {
return true;
}
}
}

return false;
}

hasMergeableTilesInRow(row) {
const filteredRow = this.board[row].filter((value) => value !== 0);

for (let i = 0; i < filteredRow.length - 1; i++) {
if (filteredRow[i] === filteredRow[i + 1]) {
return true;
}
}

return false;
}

hasMergeableTilesInColumn(col) {
const filteredCol = this.board.map((row) =>
// eslint-disable-next-line prettier/prettier
row[col].filter((val) => val !== 0));

for (let i = 0; i < filteredCol.length - 1; i++) {
if (filteredCol[i] === filteredCol[i + 1]) {
return true;
}
}

return false;
}
}

module.exports = Game;
Loading
Loading