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

add task solution #426

Open
wants to merge 5 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
28 changes: 28 additions & 0 deletions src/scripts/Button.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

class Button {
constructor(element, startFunc, restartFunc) {
const START_TEXT = 'Start';
const START_CLASS = 'start';
const RESTART_TEXT = 'Restart';
const RESTART_CLASS = 'restart';

this.element = element;

this.element.addEventListener('click', () => {
if (this.element.classList.contains(START_CLASS)) {
startFunc();
this.element.classList.remove(START_CLASS);
this.element.classList.add(RESTART_CLASS);
this.element.textContent = RESTART_TEXT;
} else if (this.element.classList.contains(RESTART_CLASS)) {
restartFunc();
this.element.classList.remove(RESTART_CLASS);
this.element.classList.add(START_CLASS);
this.element.textContent = START_TEXT;
}
});
}
}

module.exports = Button;
28 changes: 28 additions & 0 deletions src/scripts/Cell.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

class Cell {
constructor(element) {
this.isEmpty = true;
this.value = 0;
this.element = element;
}

setValue(value) {
if (!this.isEmpty) {
this.element.classList.remove('field-cell--' + this.value);
}
this.isEmpty = false;
this.element.classList.add('field-cell--' + value);
this.value = value;
this.element.textContent = value;
}

clear() {
this.isEmpty = true;
this.element.classList.remove('field-cell--' + this.value);
this.value = 0;
this.element.textContent = '';
}
}

module.exports = Cell;
39 changes: 39 additions & 0 deletions src/scripts/Controls.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
'use strict';

class Controls {
constructor(onLeft, onRight, onUp, onDown, onAction) {
this.enabled = false;
this.onLeft = onLeft;
this.onRight = onRight;
this.onUp = onUp;
this.onDown = onDown;
this.onAction = onAction;

document.addEventListener('keydown', (keyboardEvent) => {
if (!this.enabled) {
return;
}

switch (keyboardEvent.key) {
case 'ArrowLeft':
this.onLeft();
break;
case 'ArrowRight':
this.onRight();
break;
case 'ArrowUp':
this.onUp();
break;
case 'ArrowDown':
this.onDown();
break;
default:
break;
}

this.onAction();
});
}
}

module.exports = Controls;
155 changes: 155 additions & 0 deletions src/scripts/Field.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
'use strict';

const Cell = require('./Cell');

class Field {
constructor(element) {
this.cells = [];

const rows = element.querySelectorAll('.field-row');

for (let i = 0; i < rows.length; i++) {

Choose a reason for hiding this comment

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

Consider using 'forEach' or 'map' instead of the 'for' loop for better readability and performance. For instance, you can refactor this part like 'rows.forEach((row, i) => {...})'.

const row = rows[i].querySelectorAll('.field-cell');

this.cells.push([...row].map((cell) => new Cell(cell)));
}
}

getMaxValue() {
let maxValue = 0;

for (let row = 0; row < this.cells.length; row++) {
for (let column = 0; column < this.cells[row].length; column++) {
const cellValue = this.cells[row][column].value;

if (cellValue > maxValue) {
maxValue = cellValue;
}
}
}

return maxValue;
}

hasAvailableMoves() {
for (let row = 0; row < this.cells.length; row++) {

Choose a reason for hiding this comment

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

Consider using 'forEach' or 'map' instead of the 'for' loop for better readability and performance. You could use a nested 'forEach' loop to iterate over the 2D 'cells' array.

for (let column = 0; column < this.cells[row].length; column++) {
const cell = this.cells[row][column];

if (cell.isEmpty) {
return true;
}

if (
(row > 0 && this.cells[row - 1][column].value === cell.value)
|| (column > 0 && this.cells[row][column - 1].value === cell.value)
) {
return true;
}
}
}

return false;
}

mergeCells(cells) {
let score = 0;

for (let i = 0; i < cells.length; i++) {
for (let j = i + 1; j < cells.length; j++) {
if (!cells[i].isEmpty && cells[i].value === cells[j].value) {
score += cells[i].value * 2;
cells[i].setValue(cells[i].value * 2);
cells[j].clear();
} else if (cells[i].isEmpty && !cells[j].isEmpty) {
cells[i].setValue(cells[j].value);
cells[j].clear();
i++;
}
}
}

return score;
}

shiftLeft() {
let totalScore = 0;

for (let row = 0; row < this.cells.length; row++) {
totalScore += this.mergeCells(this.cells[row]);
}

return totalScore;
}

shiftRight() {
let totalScore = 0;

for (let row = 0; row < this.cells.length; row++) {
const reversedRow = this.cells[row].slice().reverse();

totalScore += this.mergeCells(reversedRow);
}

return totalScore;
}

shiftUp() {
let totalScore = 0;

for (let column = 0; column < this.cells[0].length; column++) {
const columnCells = this.cells.map((row) => row[column]);

totalScore += this.mergeCells(columnCells);
}

return totalScore;
}

shiftDown() {
let totalScore = 0;

for (let column = 0; column < this.cells[0].length; column++) {
const columnCells = this.cells.map((row) => row[column]).reverse();

totalScore += this.mergeCells(columnCells);
}

return totalScore;
}

addTile(value) {
const emptyCells = [];

for (let row = 0; row < this.cells.length; row++) {

Choose a reason for hiding this comment

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

Consider using 'forEach' or 'map' instead of the 'for' loop for better readability and performance. You could use a nested 'forEach' loop to iterate over the 2D 'cells' array.

for (let column = 0; column < this.cells[row].length; column++) {
if (this.cells[row][column].isEmpty) {
emptyCells.push({
row, column,
});
}
}
}

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

const randomIndex = Math.floor(Math.random() * emptyCells.length);
const randomCell = emptyCells[randomIndex];

this.cells[randomCell.row][randomCell.column].setValue(value);

return true;
}

reset() {
for (let column = 0; column < this.cells.length; column++) {
for (let row = 0; row < this.cells.length; row++) {
this.cells[row][column].clear();
}
}
}
}

module.exports = Field;
113 changes: 113 additions & 0 deletions src/scripts/Game.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
'use strict';

const Field = require('./Field');
const Button = require('./Button');
const Message = require('./Message');
const Score = require('./Score');
const SwipeControls = require('./SwipeControls');

class Game {
constructor() {
this.START_VALUE = 2;
this.END_VALUE = 2048;
this.DIVIDER = 2;

this.MESSAGES = {
WIN: 'win',
LOSE: 'lose',
START: 'start',
};

this.score = new Score(document.querySelector('.game-score'));
this.message = new Message(document.querySelector('.message-container'));
this.field = new Field(document.querySelector('.game-field'));

const onStart = () => {
this.field.addTile(this.START_VALUE);
this.field.addTile(this.START_VALUE);
this.message.setMessage();
this.controls.enabled = true;
};

const onRestart = () => {
this.score.reset();
this.message.setMessage(this.MESSAGES.START);
this.field.reset();
this.controls.enabled = false;
};

const getRandomValue = (min, max) => {
if (min > max) {
return 2 ** min;
}

const randomExponent = Math.floor(
Math.random() * (Math.log2(max) - Math.log2(min) + 1) + Math.log2(min)
);

return 2 ** randomExponent;
};

const onLeft = () => {
const points = this.field.shiftLeft();

this.score.addPoints(points);
};

const onRight = () => {
const points = this.field.shiftRight();

this.score.addPoints(points);
};

const onUp = () => {
const points = this.field.shiftUp();

this.score.addPoints(points);
};

const onDown = () => {
const points = this.field.shiftDown();

this.score.addPoints(points);
};

const onAction = () => {
const maxValue = this.field.getMaxValue();

if (maxValue === this.END_VALUE) {
this.message.setMessage(this.MESSAGES.WIN);
this.controls.enabled = false;

return;
}

if (!this.field.hasAvailableMoves()) {
this.message.setMessage(this.MESSAGES.LOSE);
this.controls.enabled = false;

return;
}

const newValue = getRandomValue(
this.START_VALUE, maxValue / this.DIVIDER
);

this.field.addTile(newValue);
};

this.button = new Button(
document.querySelector('.controls .button'),
onStart, onRestart
);

this.controls = new SwipeControls(onLeft, onRight, onUp, onDown, onAction);
this.message.setMessage(this.MESSAGES.START);
}

load() {

Choose a reason for hiding this comment

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

The load() method returns this without doing anything, which seems unnecessary. If this is not being used, consider removing it.

return this;
}
}

module.exports = Game;
21 changes: 21 additions & 0 deletions src/scripts/Message.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
'use strict';

class Message {
constructor(element) {
this.element = element;
}

setMessage(messageType) {
const messages = this.element.querySelectorAll('.message');

messages.forEach((message) => {
if (message.classList.contains(`message-${messageType}`)) {
message.classList.remove('hidden');
} else {
message.classList.add('hidden');
}
});
}
}

module.exports = Message;
Loading
Loading