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

2048 the game #422

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Binary file added src/images/2048_Icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
29 changes: 21 additions & 8 deletions src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,19 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2048</title>
<link rel="stylesheet" href="./styles/main.scss">
<link
rel="shortcut icon"
href="./images/2048_Icon.png"
type="image/x-icon">
</head>
<body>
<div class="container">
<div class="game-header">
<h1>2048</h1>
<div class="controls">
<p class="info">
Score: <span class="game-score">0</span>
</p>
<button class="button start">Start</button>
</div>
<p class="info">
Score: <span class="game-score">0</span>
</p>
<button class="button start">Start</button>
</div>

<table class="game-field">
Expand Down Expand Up @@ -54,10 +56,21 @@ <h1>2048</h1>

<div class="message-container">
<p class="message message-lose hidden">You lose! Restart the game?</p>
<p class="message message-win hidden">Winner! Congrats! You did it!</p>
<p class="message message-start">Press "Start" to begin game. Good luck!</p>
<p class="message message-win hidden">Winner!<br>You did it!</p>
<p class="message message-start">Press "Start" to begin the game.<br>Good luck!</p>
</div>
</div>
<div class="audio">
<audio id="audio-move" controls>
<source src="./sounds/audio-move.mp3" type="audio/mpeg">
</audio>
<audio id="audio-loose" controls>
<source src="./sounds/audio-loose.mp3" type="audio/mpeg">
</audio>
<audio id="audio-win" controls>
<source src="./sounds/audio-win.wav" type="audio/mpeg">
</audio>
</div>
<script type="text/javascript" src="scripts/main.js"></script>
</body>
</html>
209 changes: 208 additions & 1 deletion src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,210 @@
'use strict';

// write your code here
const columns = [[], [], [], []];
const rows = Array.from(document.querySelectorAll('.field-row'));
const cells = document.querySelectorAll('.field-cell');
const cellsInRow = rows.map(row => [...row.querySelectorAll('.field-cell')]);

for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
columns[j].push(rows[i].children[j]);
}
}

const button = document.querySelector('.start');
const startMessage = document.querySelector('.message-start');
const loseMessage = document.querySelector('.message-lose');
const winMessage = document.querySelector('.message-win');
const score = document.querySelector('.game-score');
const moveSound = document.getElementById('audio-move');
const looseSound = document.getElementById('audio-loose');
const winSound = document.getElementById('audio-win');

let clearCells = [...cells];

function getRandomCell() {
return clearCells[Math.floor(Math.random() * clearCells.length)];
}

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

function newCell() {

Choose a reason for hiding this comment

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

The condition 'clearCells.length === undefined' can be simplified to '!clearCells.length' which checks if the array is empty or not.

if (clearCells.length === undefined) {
return;
}

const randomCell = getRandomCell();
const randomValue = getCellValue();

randomCell.className = `field-cell field-cell--${randomValue}`;
randomCell.innerText = randomValue;

clearCells.splice(clearCells.indexOf(randomCell), 1);
}

let started = false;

function startGame() {
startMessage.style.display = 'none';
button.className = 'button restart';
button.innerText = 'Restart';

newCell();
newCell();
started = true;
}

function restartGame() {
loseMessage.classList.add('hidden');
winMessage.classList.add('hidden');
clearCells = [...cells];
score.innerText = 0;

cells.forEach(cell => {
cell.innerText = '';
cell.className = 'field-cell';
});

newCell();
newCell();
}

button.addEventListener('click', () => {
if (!started) {
startGame();
} else {
restartGame();
}
});

function canBeMarged() {
const wholeField = [...cellsInRow, ...columns];

for (const line of wholeField) {

Choose a reason for hiding this comment

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

Avoid using a for...of loop to iterate over an array. Instead, use forEach or map.

for (let i = 0; i < 3; i++) {
if (line[i].innerText === line[i + 1].innerText) {
return true;
}
}
}

return false;
}

let flipped = false;

function flipLine(line) {
for (let i = 3; i > 0; i--) {
const canBeMooved = clearCells.includes(line[i])
&& !clearCells.includes(line[i - 1]);
const mergeAllowed = line[i].innerText === line[i - 1].innerText
&& line[i].innerText.length
&& !line[i - 1].dataset.blocked;

if ((mergeAllowed || canBeMooved) && !flipped) {
flipped = true;
}

if (mergeAllowed) {
mergeCells(line[i], line[i - 1]);
flipLine(line);
}

if (canBeMooved) {
flipElements(line[i], line[i - 1]);
flipLine(line);
}
}
}

function mergeCells(curr, prev) {
const value = curr.innerText * 2;

curr.innerText = value;
curr.className = `field-cell field-cell--${value}`;
score.innerText = +score.innerText + value;
deleteElement(prev);

curr.dataset.blocked = true;
prev.dataset.blocked = true;

if (value === 2048) {
winMessage.classList.remove('hidden');
winSound.currentTime = 0;
winSound.play();
}
}

function flipElements(curr, prev) {
curr.innerText = prev.innerText;
curr.className = prev.className;
clearCells = clearCells.filter(cell => cell !== curr);
deleteElement(prev);
}

function deleteElement(element) {
element.innerText = '';
element.className = 'field-cell';
clearCells.push(element);
}

function getDirection(direction) {
if (!clearCells.length && !canBeMarged()) {
loseMessage.classList.remove('hidden');
looseSound.currentTime = 0;
looseSound.play();
}

switch (direction) {
case 'ArrowUp':

Choose a reason for hiding this comment

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

Сreate a variable for these magic words

for (const column of columns) {

Choose a reason for hiding this comment

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

Avoid using a for...of loop to iterate over an array. Instead, use forEach or map.

flipLine([...column].reverse());
}
break;

case 'ArrowDown':
for (const column of columns) {
flipLine(column);
}
break;

case 'ArrowRight':
for (const row of cellsInRow) {
flipLine(row);
}
break;

case 'ArrowLeft':
for (const row of cellsInRow) {
flipLine([...row].reverse());
}
break;
}

cells.forEach(cell => {
cell.removeAttribute('data-blocked');
});
}

document.addEventListener('keyup', (evnt) => {

Choose a reason for hiding this comment

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

It's more efficient to listen to the keyup event only on the window or document object, not on the entire document. So you can change 'document.addEventListener' to 'window.addEventListener' or 'document.body.addEventListener'.

Copy link
Author

Choose a reason for hiding this comment

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

I've decided to change it back to 'keydown'. It feels more natural and more responsive while playing.

const arrowDirections = [
'ArrowUp',
'ArrowDown',
'ArrowLeft',
'ArrowRight',
];

if (arrowDirections.includes(evnt.key)) {
evnt.preventDefault();
getDirection(evnt.key);

if (flipped) {
moveSound.currentTime = 0;
moveSound.play();
newCell();
flipped = false;
}
}
});
Binary file added src/sounds/audio-loose.mp3
Binary file not shown.
Binary file added src/sounds/audio-move.mp3
Binary file not shown.
Binary file added src/sounds/audio-win.wav
Binary file not shown.
Loading
Loading