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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open

Solution #1

wants to merge 6 commits into from

Conversation

pokhylko
Copy link

https://pokhylko.github.io/js_2048_game/

Готово все, кроме:

  • Функции в случае проигрыша, если все поля заполнены
  • Ограничения возможности хода в сторону, если туда нельзя сдвинуть элементы
  • Остановки игры после победы

Не понял, каким образом считается результат, пока сделал сумму всех цифр на поле.

Copy link
Contributor

@vpolets vpolets left a comment

Choose a reason for hiding this comment

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

поразка це коли на полі не має вільної клітинки, це можна перевірити, якщо немає куди вставляти нову цифру - це поразка.

Comment on lines 87 to 93
function randomValue() {
if (Math.random() < 0.1) {
return 4;
} else {
return 2;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

це 9.999% але не 10, <= постав

Comment on lines 106 to 116
function calculateScore() {
let totalScore = 0;

for (const row of arrField) {
for (const column of row) {
totalScore += column;
}
}

scoreValue.textContent = totalScore;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

рахунок це сума складених клітинок за хід
2 + 2 = 4
8+ 8 = 16

в результаті до рахунку додаємо + 20

// Win message

function checkWin(number) {
if (number === 2048) {
Copy link
Contributor

Choose a reason for hiding this comment

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

що таке 2048?)))

Comment on lines 99 to 100
row: Math.floor(Math.random() * 4),
column: Math.floor(Math.random() * 4),
Copy link
Contributor

Choose a reason for hiding this comment

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

а 4 що таке? Чому саме 4? А якщо захочеться зробити розширену версію де бу 6*6? Прийдеться в багатьох місцях міняти код (що може призвести до помилок)
краще винести в константу FIELD_SIZE

function newRandomCell() {
const { row, column } = randomPosition();

if (arrField[row][column] === 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

таке теж виносять в змінну

Suggested change
if (arrField[row][column] === 0) {
const isCellEmpty = arrField[row][column] === 0;
if (isCellEmpty) {

Comment on lines 158 to 222
function moveUp(row, column) {
if (arrField[row][column] > 0 && row - 1 >= 0) {
if (arrField[row - 1][column] === 0) {
moveElement(row, column, row - 1, column);

return moveUp(row - 1, column);
}

if (arrField[row][column] === arrField[row - 1][column]
&& row - 1 >= 0) {
sumElement(row, column, row - 1, column);
}
}
}

// Move elements down

function moveDown(row, column) {
if (arrField[row][column] > 0 && row + 1 < arrField.length) {
if (arrField[row + 1][column] === 0) {
moveElement(row, column, row + 1, column);

return moveDown(row + 1, column);
}

if (arrField[row][column] === arrField[row + 1][column]
&& row + 1 < arrField.length) {
sumElement(row, column, row + 1, column);
}
}
}

// Move elements left

function moveLeft(row, column) {
if (arrField[row][column] > 0 && column - 1 >= 0) {
if (arrField[row][column - 1] === 0) {
moveElement(row, column, row, column - 1);

return moveLeft(row, column - 1);
}

if (arrField[row][column] === arrField[row][column - 1]
&& column - 1 >= 0) {
sumElement(row, column, row, column - 1);
}
}
}

// Move elements right

function moveRight(row, column) {
if (arrField[row][column] > 0 && column + 1 < arrField[row].length) {
if (arrField[row][column + 1] === 0) {
moveElement(row, column, row, column + 1);

return moveRight(row, column + 1);
}

if (arrField[row][column] === arrField[row][column + 1]
&& column + 1 < arrField[row].length) {
sumElement(row, column, row, column + 1);
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Якщо так глянути не вчитуючись то ці функції ідентичні просто різниця в них в 0, 1, -1 в правильних місцях, Думаю можна спокійно скоротити і не дублювати код

Comment on lines 229 to 231
newRandomCell();
loopArray(buildGameField);
calculateScore();
Copy link
Contributor

Choose a reason for hiding this comment

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

ці три рядки відбуваються в любому випадку? Виносимо за if? А перед цим перевіряємо чи arrows.includes(event.key) якщо ні то виходимо
(~ -7 рядків коду на рівному місці.)
А якщо написати функцію getMoveMethod(key), котра буде повертати правильну функцію в залежності від кнопки, то тут if взагалі не потрібні

@pokhylko pokhylko requested a review from vpolets July 25, 2020 12:47
Copy link
Contributor

@vpolets vpolets left a comment

Choose a reason for hiding this comment

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

Пограв трішки і знайшов баг
image

Copy link
Contributor

@vpolets vpolets left a comment

Choose a reason for hiding this comment

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

Одразу порада як логічно таке пофіксити, проходитися не по всьому полю, в з кінця до початку
Тобто якщо це стрілка в ліво то починаємо перевіряти поле від 0 до кінця
Якщо стрілка в право то починаємо перевіряти від кінця до початку
в такому разі при наборі 2 - 2 - 4 ми перевіримо 4ку, побачимо що поруч стоїть не 4ка і все підемо далі, 2 зліпиться з 2кою, а до 4ки ми вже не повернемося

const loseMessage = messages.querySelector('.message-lose');
const winMessage = messages.querySelector('.message-win');
const scoreValue = container.querySelector('.game-score');
const winNumber = 2048;
Copy link
Contributor

Choose a reason for hiding this comment

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

глобальні константи пишуться в upper case

Comment on lines +15 to +18
const FIELD_SIZE = {
rows: 4,
columns: 4,
};
Copy link
Contributor

Choose a reason for hiding this comment

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

просто 4 і все, 2048 це гра про квадрат, тому прямокутники там не передбачені, але хай буде, то твоє бачення)

Comment on lines 19 to 24
const ARROWS = {
'ArrowUp': 'ArrowUp',
'ArrowRight': 'ArrowRight',
'ArrowDown': 'ArrowDown',
'ArrowLeft': 'ArrowLeft',
};
Copy link
Contributor

Choose a reason for hiding this comment

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

те що ти пишеш в значенні повну назву кнопки з івента це нормально, але те що ти пишеш в ключі повну назву трішки не камільфо. Виходить маслоМасляне. В тебе вже об'єкт в цілому має назву ARROWS, що передбачає що у ньому стрілки зберігаються тобто ARROWS.left само собою означа стрілку в ліво.

Comment on lines 350 to 352
if (checkUp() || checkDown() || checkLeft() || checkRight()) {
return true;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

по твоїй логічі, якщо хоч одна з штук зверху поверне true, то ти програв, але ж насправді ні. не треба нічого повертати, можкш просто return; написати щоб вийти з функції
Чому перевірка на програш, щей викликає "програти". Вона має тільки перевіряти, а не викликати сайд ефекти у вигляді програшу.
Назви її isLose
тоді має бути щось типу

if (isLose()) {
  endGame();
}

arrField[newRow][newColumn] *= 2;
arrField[row][column] = 0;
calculateScore(arrField[newRow][newColumn]);
checkWin(arrField[newRow][newColumn]);
Copy link
Contributor

Choose a reason for hiding this comment

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

та сама історія, функція і перевіряє і ще й щось робить окрім того.

if (checkWin()) {
  endGame()
}

Вона має просто true або false повертати

@pokhylko pokhylko requested a review from vpolets July 28, 2020 15:07
Copy link
Contributor

@vpolets vpolets left a comment

Choose a reason for hiding this comment

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

Кароч це може був і не баг, а просто 2ка з'явилася не в тому місці і так здалося але ось ілюстрація того що було
image
Яне певен що було саме так, але мені здалося що було так, по коду не можу зрозуміти точно чи це могло відбутися

NataliiaNudyk added a commit to NataliiaNudyk/js_2048_game that referenced this pull request Feb 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants