-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_board.js
81 lines (73 loc) · 1.64 KB
/
game_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
78
79
80
81
function GameBoard(cols, rows, proportion){
this.rows = rows;
this.cols = cols;
this.proportion = proportion;
this.map = new Array(2);
for (var k = 0; k < 2; k ++){
this.map[k] = new Array(rows);
for (var i = 0; i < rows; i ++){
this.map[k][i] = new Array(cols);
}
}
this.cur = 0;
this.dir = [[-1, 0],[-1, -1],[-1, 1],[0, -1],[0, 1],[1, -1],[1, 0],[1, 1]];
this.init = function(cols, rows) {
this.rows = rows;
this.cols = cols;
for (var k = 0; k < 2; k ++){
this.map[k] = new Array(rows);
for (var i = 0; i < rows; i ++){
this.map[k][i] = new Array(cols);
}
}
}
this.start = function () {
this.cur = 0;
for (var i = 0; i < this.rows; i ++){
for (var j = 0; j < this.cols; j ++){
if (Math.random() < proportion){
this.map[this.cur][i][j] = 1;
}
else{
this.map[this.cur][i][j] = 0;
}
}
}
}
this.update = function() {
var pre = this.cur;
var cur = 1 - pre;
for (var i = 0; i < this.rows; i ++){
for (var j = 0; j < this.cols; j ++){
var cnt = 0;
for (var k = 0; k < 8; k ++){
var ti = i + this.dir[k][0];
var tj = j + this.dir[k][1];
if (ti >= 0 && ti < this.rows && tj >= 0 && tj <= this.cols){
if (this.map[pre][ti][tj]){
if (++ cnt > 3) {
break;
}
}
}
}
if (cnt == 2){
this.map[cur][i][j] = this.map[pre][i][j];
}
else if (cnt == 3){
this.map[cur][i][j] = 1;
}
else{
this.map[cur][i][j] = 0;
}
}
}
this.cur = cur;
}
this.turn = function(x, y) {
this.map[this.cur][x][y] = 1 - this.map[this.cur][x][y];
}
this.getMap = function() {
return this.map[this.cur];
}
}