generated from mate-academy/gulp-template
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
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
Develop #1132
Open
olhakostovetska
wants to merge
6
commits into
mate-academy:master
Choose a base branch
from
olhakostovetska:develop
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Develop #1132
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,68 +1,236 @@ | ||
'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.initialState = initialState.map((row) => [...row]); | ||
// Зберігаємо копію initialState | ||
this.grid = initialState.map((row) => [...row]); // Глибока копія | ||
this.score = 0; | ||
this.status = 'idle'; // 'idle', 'playing', 'win', 'lose' | ||
} | ||
|
||
moveLeft() { | ||
if (this.status !== 'playing') { | ||
return; | ||
} | ||
|
||
const prevState = JSON.stringify(this.grid); | ||
|
||
this.grid = this.grid.map((row) => this._slideAndMerge(row)); | ||
this._postMoveHandler(prevState); | ||
} | ||
|
||
moveRight() { | ||
if (this.status !== 'playing') { | ||
return; | ||
} | ||
|
||
const prevState = JSON.stringify(this.grid); | ||
|
||
// Переміщаємо клітинки вправо без об'єднання | ||
this.grid = this.grid.map((row) => this._slideRight(row)); | ||
|
||
// Тепер об'єднуємо клітинки з однаковими значеннями | ||
this.grid = this.grid.map((row) => this._mergeRight(row)); | ||
|
||
this._postMoveHandler(prevState); | ||
} | ||
|
||
// Функція для переміщення вправо без об'єднання | ||
_slideRight(row) { | ||
const filtered = row.filter((cell) => cell !== 0); // Фільтруємо всі нулі | ||
const merged = new Array(4).fill(0); // Масив, в якому всі елементи рівні 0 | ||
|
||
let emptyIndex = 3; // Позиція, куди вставляти елементи | ||
|
||
for (let i = filtered.length - 1; i >= 0; i--) { | ||
merged[emptyIndex--] = filtered[i]; // Переміщаємо елементи вправо | ||
} | ||
|
||
return merged; // Повертаємо новий відсортований масив | ||
} | ||
|
||
// Функція для об'єднання клітинок вправо | ||
_mergeRight(row) { | ||
const merged = row.slice(); | ||
// Створюємо копію масиву, щоб не змінювати оригінальний | ||
|
||
for (let i = 3; i > 0; i--) { | ||
if (merged[i] === merged[i - 1] && merged[i] !== 0) { | ||
// Перевіряємо на однакові значення | ||
merged[i] *= 2; // Об'єднуємо клітинки | ||
this.score += merged[i]; // Додаємо до рахунку | ||
merged[i - 1] = 0; // Очищаємо клітинку, яка була об'єднана | ||
} | ||
} | ||
|
||
return this._slideRight(merged); | ||
// Повторно переміщаємо клітинки після об'єднання | ||
} | ||
|
||
moveUp() { | ||
if (this.status !== 'playing') { | ||
return; | ||
} | ||
|
||
const prevState = JSON.stringify(this.grid); | ||
|
||
this._transposeGrid(); | ||
this.grid = this.grid.map((row) => this._slideAndMerge(row)); | ||
this._transposeGrid(); | ||
this._postMoveHandler(prevState); | ||
} | ||
|
||
moveDown() { | ||
if (this.status !== 'playing') { | ||
return; | ||
} | ||
|
||
const prevState = JSON.stringify(this.grid); | ||
|
||
this._transposeGrid(); | ||
|
||
this.grid = this.grid.map( | ||
(row) => this._slideAndMerge(row.reverse()).reverse(), | ||
// eslint-disable-next-line function-paren-newline | ||
); | ||
this._transposeGrid(); | ||
this._postMoveHandler(prevState); | ||
} | ||
|
||
getScore() { | ||
return this.score; | ||
} | ||
|
||
getState() { | ||
return this.grid; | ||
} | ||
|
||
getStatus() { | ||
return this.status; | ||
} | ||
|
||
start() { | ||
if (this.status !== 'idle') { | ||
return; // Забороняємо старт, якщо гра вже активна | ||
} | ||
|
||
this.status = 'playing'; // Змінюємо статус на "playing" | ||
this._addRandomCell(); // Додаємо випадкову клітинку | ||
this._addRandomCell(); // Додаємо ще одну випадкову клітинку | ||
} | ||
|
||
restart() { | ||
this.score = 0; | ||
this.grid = this.initialState; | ||
this.status = 'idle'; | ||
} | ||
|
||
reset() { | ||
this.grid = this.initialState.map((row) => [...row]); | ||
// Повертаємося до initialState | ||
this.score = 0; | ||
this.status = 'idle'; | ||
} | ||
|
||
_slideAndMerge(row) { | ||
const filtered = row.filter((cell) => cell !== 0); | ||
const merged = []; | ||
|
||
let skipNext = false; // Позначка, щоб уникнути подвійного об'єднання | ||
|
||
for (let i = 0; i < filtered.length; i++) { | ||
if (skipNext) { | ||
skipNext = false; // Пропускаємо поточний елемент | ||
continue; | ||
} | ||
|
||
if (filtered[i] === filtered[i + 1]) { | ||
merged.push(filtered[i] * 2); | ||
this.score += filtered[i] * 2; | ||
skipNext = true; // Позначаємо, щоб пропустити наступне | ||
} else { | ||
merged.push(filtered[i]); | ||
} | ||
} | ||
|
||
while (merged.length < 4) { | ||
merged.push(0); | ||
} | ||
|
||
return merged; | ||
} | ||
|
||
_transposeGrid() { | ||
this.grid = this.grid[0].map( | ||
(_, colIndex) => this.grid.map((row) => row[colIndex]), | ||
// eslint-disable-next-line function-paren-newline | ||
); | ||
} | ||
|
||
_addRandomCell() { | ||
// Ensure you add a random value (e.g., 2 or 4) in an empty spot | ||
const emptyCells = []; | ||
|
||
for (let row = 0; row < this.grid.length; row++) { | ||
for (let col = 0; col < this.grid[row].length; col++) { | ||
if (this.grid[row][col] === 0) { | ||
emptyCells.push({ row, col }); | ||
} | ||
} | ||
} | ||
|
||
if (emptyCells.length > 0) { | ||
const randomIndex = Math.floor(Math.random() * emptyCells.length); | ||
const { row, col } = emptyCells[randomIndex]; | ||
|
||
this.grid[row][col] = Math.random() < 0.9 ? 2 : 4; | ||
// 90% chance for 2, 10% for 4 | ||
} | ||
} | ||
|
||
_postMoveHandler(prevState) { | ||
if (JSON.stringify(this.grid) !== prevState) { | ||
this._addRandomCell(); | ||
|
||
if (this._checkWin()) { | ||
this.status = 'win'; | ||
} else if (!this._hasAvailableMoves()) { | ||
this.status = 'lose'; | ||
} | ||
} | ||
} | ||
|
||
_checkWin() { | ||
return this.grid.some((row) => row.some((cell) => cell === 2048)); | ||
} | ||
|
||
_hasAvailableMoves() { | ||
for (let r = 0; r < 4; r++) { | ||
for (let c = 0; c < 4; c++) { | ||
if (this.grid[r][c] === 0) { | ||
return true; | ||
} | ||
|
||
if (c < 3 && this.grid[r][c] === this.grid[r][c + 1]) { | ||
return true; | ||
} | ||
|
||
if (r < 3 && this.grid[r][c] === this.grid[r + 1][c]) { | ||
return true; | ||
} | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
} | ||
|
||
module.exports = Game; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,77 @@ | ||
'use strict'; | ||
|
||
// Uncomment the next lines to use your game instance in the browser | ||
// const Game = require('../modules/Game.class'); | ||
// const game = new Game(); | ||
const Game = require('../modules/Game.class'); | ||
|
||
// Write your code here | ||
const game = new Game(); | ||
const startButton = document.querySelector('.button'); | ||
const scoreElement = document.querySelector('.game-score'); | ||
const messageStart = document.querySelector('.message-start'); | ||
const messageWin = document.querySelector('.message-win'); | ||
const messageLose = document.querySelector('.message-lose'); | ||
const fieldCells = document.querySelectorAll('.field-cell'); | ||
|
||
function renderGrid() { | ||
const grid = game.getState(); | ||
|
||
fieldCells.forEach((cell, index) => { | ||
const row = Math.floor(index / 4); | ||
const col = index % 4; | ||
const value = grid[row][col]; | ||
|
||
cell.textContent = value === 0 ? '' : value; | ||
cell.className = `field-cell ${value ? `field-cell--${value}` : ''}`; | ||
}); | ||
scoreElement.textContent = game.getScore(); | ||
} | ||
|
||
// eslint-disable-next-line no-shadow | ||
function handleKeyPress(event) { | ||
if (game.getStatus() !== 'playing') { | ||
return; | ||
} | ||
|
||
switch (event.key) { | ||
case 'ArrowLeft': | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Create variables for event keys |
||
game.moveLeft(); | ||
break; | ||
case 'ArrowRight': | ||
game.moveRight(); | ||
break; | ||
case 'ArrowUp': | ||
game.moveUp(); | ||
break; | ||
case 'ArrowDown': | ||
game.moveDown(); | ||
break; | ||
default: | ||
return; | ||
} | ||
|
||
renderGrid(); | ||
checkGameStatus(); | ||
} | ||
|
||
function checkGameStatus() { | ||
if (game.getStatus() === 'win') { | ||
messageWin.classList.remove('hidden'); | ||
} else if (game.getStatus() === 'lose') { | ||
messageLose.classList.remove('hidden'); | ||
} | ||
} | ||
|
||
startButton.addEventListener('click', () => { | ||
if (startButton.classList.contains('start')) { | ||
game.start(); | ||
startButton.classList.remove('start'); | ||
startButton.classList.add('restart'); | ||
startButton.textContent = 'Restart'; | ||
messageStart.classList.add('hidden'); | ||
} else { | ||
game.restart(); | ||
messageWin.classList.add('hidden'); | ||
messageLose.classList.add('hidden'); | ||
} | ||
renderGrid(); | ||
}); | ||
|
||
document.addEventListener('keydown', handleKeyPress); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove all comments