forked from eilite/GameOfLife
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBoard.js
63 lines (56 loc) · 1.92 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
var Cell = require("./Cell")
function Board(width, height){
this.width = width;
this.height = height;
this.cells = [];
for (var i = 0; i < width*height; i++) {
this.cells.push(new Cell(Math.random() < 0.5 ? true : false));
}
}
Board.prototype.getSize = function(){
return this.cells.length;
}
Board.prototype.setCellNeighbours = function(cell, index){
var column = index % this.width
var row = Math.trunc(index / this.width)
var neighbours = [];
if(column == 0){
neighbours.push(this.cells[index+1]);
} else if(column == this.width - 1){
neighbours.push(this.cells[index-1]);
} else {
neighbours.push(this.cells[index-1], this.cells[index+1]);
}
if(row == 0){
if(column == 0){
neighbours.push(this.cells[index+this.width],
this.cells[index+this.width+1]);
} else if(column == this.width - 1){
neighbours.push(this.cells[index-1+this.width], this.cells[index+this.width]);
} else {
neighbours.push(this.cells[index-1+this.width], this.cells[index+this.width],
this.cells[index+this.width]+1);
}
} else if(row == this.height - 1){
if(column == 0){
neighbours.push(this.cells[index-this.width],
this.cells[index+1-this.width]);
}else if(column == this.width - 1){
neighbours.push(this.cells[index-1-this.width], this.cells[index-this.width]);
}else {
neighbours.push(this.cells[index-1-this.width], this.cells[index-this.width],
this.cells[index+1-this.width]);
}
} else {
neighbours.push(this.cells[index-1-this.width], this.cells[index-this.width],
this.cells[index+1-this.width]);
neighbours.push(this.cells[index-1+this.width], this.cells[index+this.width],
this.cells[index+this.width]);
}
var resCell = new Cell(cell.state, neighbours.filter((neighbour)=>neighbour));
return resCell;
}
Board.prototype.setCells = function(cells){
this.cells = cells;
}
module.exports = Board;