-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameBoard.js
73 lines (59 loc) · 2.16 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
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) {
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 = ''
this.DOMGrid.style.cssText = `grid-template-columns: repeat(${GRID_SIZE}, ${CELL_SIZE}px)`
level.forEach((square, i) => {
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)
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)
}
objectExist = (pos, obj) => {
return this.grid[pos].classList.contains(obj)
}
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) {
this.rotateDiv(nextMovePos, character.dir.rotation)
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