-
Notifications
You must be signed in to change notification settings - Fork 1.4k
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
base: master
Are you sure you want to change the base?
Solution #1
Conversation
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.
поразка це коли на полі не має вільної клітинки, це можна перевірити, якщо немає куди вставляти нову цифру - це поразка.
src/scripts/main.js
Outdated
function randomValue() { | ||
if (Math.random() < 0.1) { | ||
return 4; | ||
} else { | ||
return 2; | ||
} | ||
} |
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.
це 9.999% але не 10, <= постав
src/scripts/main.js
Outdated
function calculateScore() { | ||
let totalScore = 0; | ||
|
||
for (const row of arrField) { | ||
for (const column of row) { | ||
totalScore += column; | ||
} | ||
} | ||
|
||
scoreValue.textContent = totalScore; | ||
} |
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.
рахунок це сума складених клітинок за хід
2 + 2 = 4
8+ 8 = 16
в результаті до рахунку додаємо + 20
src/scripts/main.js
Outdated
// Win message | ||
|
||
function checkWin(number) { | ||
if (number === 2048) { |
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.
що таке 2048?)))
src/scripts/main.js
Outdated
row: Math.floor(Math.random() * 4), | ||
column: Math.floor(Math.random() * 4), |
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.
а 4 що таке? Чому саме 4? А якщо захочеться зробити розширену версію де бу 6*6? Прийдеться в багатьох місцях міняти код (що може призвести до помилок)
краще винести в константу FIELD_SIZE
src/scripts/main.js
Outdated
function newRandomCell() { | ||
const { row, column } = randomPosition(); | ||
|
||
if (arrField[row][column] === 0) { |
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.
таке теж виносять в змінну
if (arrField[row][column] === 0) { | |
const isCellEmpty = arrField[row][column] === 0; | |
if (isCellEmpty) { |
src/scripts/main.js
Outdated
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); | ||
} | ||
} | ||
} |
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.
Якщо так глянути не вчитуючись то ці функції ідентичні просто різниця в них в 0, 1, -1 в правильних місцях, Думаю можна спокійно скоротити і не дублювати код
src/scripts/main.js
Outdated
newRandomCell(); | ||
loopArray(buildGameField); | ||
calculateScore(); |
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.
ці три рядки відбуваються в любому випадку? Виносимо за if? А перед цим перевіряємо чи arrows.includes(event.key) якщо ні то виходимо
(~ -7 рядків коду на рівному місці.)
А якщо написати функцію getMoveMethod(key), котра буде повертати правильну функцію в залежності від кнопки, то тут if взагалі не потрібні
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.
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.
Одразу порада як логічно таке пофіксити, проходитися не по всьому полю, в з кінця до початку
Тобто якщо це стрілка в ліво то починаємо перевіряти поле від 0 до кінця
Якщо стрілка в право то починаємо перевіряти від кінця до початку
в такому разі при наборі 2 - 2 - 4 ми перевіримо 4ку, побачимо що поруч стоїть не 4ка і все підемо далі, 2 зліпиться з 2кою, а до 4ки ми вже не повернемося
src/scripts/main.js
Outdated
const loseMessage = messages.querySelector('.message-lose'); | ||
const winMessage = messages.querySelector('.message-win'); | ||
const scoreValue = container.querySelector('.game-score'); | ||
const winNumber = 2048; |
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.
глобальні константи пишуться в upper case
const FIELD_SIZE = { | ||
rows: 4, | ||
columns: 4, | ||
}; |
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.
просто 4 і все, 2048 це гра про квадрат, тому прямокутники там не передбачені, але хай буде, то твоє бачення)
src/scripts/main.js
Outdated
const ARROWS = { | ||
'ArrowUp': 'ArrowUp', | ||
'ArrowRight': 'ArrowRight', | ||
'ArrowDown': 'ArrowDown', | ||
'ArrowLeft': 'ArrowLeft', | ||
}; |
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.
те що ти пишеш в значенні повну назву кнопки з івента це нормально, але те що ти пишеш в ключі повну назву трішки не камільфо. Виходить маслоМасляне. В тебе вже об'єкт в цілому має назву ARROWS, що передбачає що у ньому стрілки зберігаються тобто ARROWS.left само собою означа стрілку в ліво.
src/scripts/main.js
Outdated
if (checkUp() || checkDown() || checkLeft() || checkRight()) { | ||
return true; | ||
} |
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.
по твоїй логічі, якщо хоч одна з штук зверху поверне true, то ти програв, але ж насправді ні. не треба нічого повертати, можкш просто return; написати щоб вийти з функції
Чому перевірка на програш, щей викликає "програти". Вона має тільки перевіряти, а не викликати сайд ефекти у вигляді програшу.
Назви її isLose
тоді має бути щось типу
if (isLose()) {
endGame();
}
src/scripts/main.js
Outdated
arrField[newRow][newColumn] *= 2; | ||
arrField[row][column] = 0; | ||
calculateScore(arrField[newRow][newColumn]); | ||
checkWin(arrField[newRow][newColumn]); |
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.
та сама історія, функція і перевіряє і ще й щось робить окрім того.
if (checkWin()) {
endGame()
}
Вона має просто true або false повертати
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.
https://pokhylko.github.io/js_2048_game/
Готово все, кроме:
Не понял, каким образом считается результат, пока сделал сумму всех цифр на поле.