-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
87 lines (74 loc) · 2.41 KB
/
game.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class Game {
static start(element = document.querySelector('.game')) {
new Game(element);
}
constructor(element) {
this.element = element;
this.table = this.element.querySelector('.game__field');
this.size = this.table.rows.length;
this.emptyCellClassName = 'game__field-cell--empty';
const {
cellIndex,
parentElement: { rowIndex },
} = this.table.querySelector(`.${this.emptyCellClassName}`);
this.currentPosition = { x: cellIndex, y: rowIndex };
this.table.addEventListener('mousedown', ({ target }) => {
const cell = target.closest('.game__field-cell');
if (!cell) {
return;
}
this.handleMouseDown(cell);
});
window.addEventListener('keydown', ({ key }) => {
this.handleKeyDown(key);
});
}
handleMouseDown(cell) {
const { x, y } = this.currentPosition;
const { cellIndex, parentElement: { rowIndex } } = cell;
const newPosition = { x: cellIndex, y: rowIndex };
const isMoveable = Math.abs(x - cellIndex) + Math.abs(y - rowIndex) === 1;
if (!isMoveable) {
return;
}
this.changePosition(newPosition);
}
handleKeyDown(key) {
const { x, y } = this.currentPosition;
let newPosition;
switch (key) {
case 'ArrowUp':
newPosition = { ...this.currentPosition, y: y + 1 };
break;
case 'ArrowDown':
newPosition = { ...this.currentPosition, y: y - 1 };
break;
case 'ArrowLeft':
newPosition = { ...this.currentPosition, x: x + 1 };
break;
case 'ArrowRight':
newPosition = { ...this.currentPosition, x: x - 1 };
break;
default:
return;
}
const row = this.table.rows[newPosition.y];
if (row) {
const cell = row.cells[newPosition.x];
if (cell) {
this.changePosition(newPosition);
}
}
}
changePosition(newPosition) {
const { x, y } = this.currentPosition;
const currentEmptyCell = this.table.rows[y].cells[x];
const newEmptyCell = this.table.rows[newPosition.y].cells[newPosition.x];
currentEmptyCell.textContent = newEmptyCell.textContent;
currentEmptyCell.classList.remove(this.emptyCellClassName);
newEmptyCell.classList.add(this.emptyCellClassName);
newEmptyCell.textContent = '';
this.currentPosition = newPosition;
}
};
Game.start();