-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboard.js
77 lines (68 loc) · 2.13 KB
/
board.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
import Tile from "./tile.js"
/**
* Represents the game board.
* @constructor
* @param {object} [size] - Size (width and height in tiles) of the board
* @param {number} size.x - Width in tiles of the board
* @param {number} size.y - Height in tiles of the board
*/
export default function Board(size = {x: 8, y: 8}) {
let board = new Array(size.x).fill(null)
this.board = board.map(_ => new Array(size.y).fill(null).map(_ => new Tile()))
console.table(this.board)
}
Board.prototype.render = function (ctx) {
this.board.forEach((row, i) => {
row.forEach((tile, j) => {
tile.render(ctx, {x: i, y: j})
})
})
}
Board.prototype.moveObject = function (src, dest) {
// console.log("Board moving player", src, dest)
if(this.board[dest.x] && this.board[dest.x][dest.y]) {
this.board[dest.x][dest.y].entity = this.board[src.x][src.y].entity
this.board[src.x][src.y].entity = null
} else {
console.warn("Invalid move to dest", dest, src)
throw("Invalid Move")
}
}
Board.prototype.placeObject = function (entity, dest) {
if(this.board[dest.x] && this.board[dest.x][dest.y]) {
this.board[dest.x][dest.y].entity = entity
} else {
throw("Invalid dest passed to Board.placeObject", dest)
}
}
Board.prototype.findRandomUnoccupiedTile = function() {
let randomX = Math.floor(Math.random() * this.board.length)
let randomY = Math.floor(Math.random() * this.board[0].length)
while(!this.board[randomX][randomY].contains(null)) {
// keep finding random tile until unoccupied one is found
randomX = Math.floor(Math.random() * this.board.length)
randomY = Math.floor(Math.random() * this.board[0].length)
}
return {
x: randomX,
y: randomY
}
}
/**
* @param (Object[]) tiles - Array of position objects
* @param (number) tiles.x - x coordinate of tile position
* @param (number) tiles.y - y coordinate of tile position
*/
Board.prototype.highlightTiles = function(tiles) {
// console.log("Highlighting tiles", tiles)
for(let tile of tiles) {
this.board[tile.x][tile.y].isHighlighted = true
}
}
Board.prototype.clearHighlights = function () {
this.board.forEach((row) => {
row.forEach((tile) => {
tile.isHighlighted = false
})
})
}