-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameBoard.js
81 lines (67 loc) · 2.25 KB
/
GameBoard.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
import { GRID_SIZE, CELL_SIZE, OBJECT_TYPE, CLASS_LIST } from './setup';
class GameBoard {
constructor(DOMGrid) {
this.dotCount = 0;
this.grid = [];
this.DOMGrid = DOMGrid;
}
showGameStatus(gameWin) {
// Create and show game win or game over
const div = document.createElement('div');
div.classList.add('game-status');
div.innerHTML = `${gameWin ? 'WIN!' : 'GAME OVER!'}`;
this.DOMGrid.appendChild(div);
}
createGrid(level) {
this.dotCount = 0;
this.grid = [];
this.DOMGrid.innerHTML = '';
// First set correct amount of columns based on Grid Size and Cell Size
this.DOMGrid.style.cssText = `grid-template-columns: repeat(${GRID_SIZE}, ${CELL_SIZE}px);`;
level.forEach((square) => {
const div = document.createElement('div');
div.classList.add('square', CLASS_LIST[square]);
div.style.cssText = `width: ${CELL_SIZE}px; height: ${CELL_SIZE}px;`;
this.DOMGrid.appendChild(div);
this.grid.push(div);
// Add dots
if (CLASS_LIST[square] === OBJECT_TYPE.DOT) this.dotCount++;
});
}
addObject(pos, classes) {
this.grid[pos].classList.add(...classes);
}
removeObject(pos, classes) {
this.grid[pos].classList.remove(...classes);
}
// Can have an arrow function here cause of this binding
objectExist(pos, object) {
return this.grid[pos].classList.contains(object);
}
rotateDiv(pos, deg) {
this.grid[pos].style.transform = `rotate(${deg}deg)`;
}
moveCharacter(character) {
if (character.shouldMove()) {
const { nextMovePos, direction } = character.getNextMove(
this.objectExist.bind(this)
);
const { classesToRemove, classesToAdd } = character.makeMove();
if (character.rotation && nextMovePos !== character.pos) {
// Rotate
this.rotateDiv(nextMovePos, character.dir.rotation);
// Rotate the previous div back
this.rotateDiv(character.pos, 0);
}
this.removeObject(character.pos, classesToRemove);
this.addObject(nextMovePos, classesToAdd);
character.setNewPos(nextMovePos, direction);
}
}
static createGameBoard(DOMGrid, level) {
const board = new this(DOMGrid);
board.createGrid(level);
return board;
}
}
export default GameBoard;