-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcell.js
102 lines (94 loc) · 2.55 KB
/
cell.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
function Cell(i, j, w){
this.i = i; //列索引
this.j = j; //行索引
this.x = i*w; //x坐标
this.y = j*w; //y坐标
this.w = w; //格子宽度
this.neighborCount = 0; //周围地雷数量
this.bee = false; //是否是地雷
this.revealed = false; //是否被揭开
this.flagged = false; //是否被标记为地雷
}
//显示格子内容
Cell.prototype.show = function(){
stroke(0); //绘制边框
noFill(); //默认无填充
rect(this.x, this.y, this.w, this.w); //绘制格子
if(this.flagged){
//如果被标记为地雷,显示标记
fill(255, 0, 0);
textAlign(CENTER);
text("F", this.x+this.w*0.5, this.y+this.w-6);
}else if(this.revealed){
//如果被揭开
if(this.bee){
fill(127);
ellipse(this.x+this.w*0.5, this.y+this.w*0.5, this.w * 0.5);
}else{
fill(200); //显示已揭开的格子
rect(this.x, this.y, this.w, this.w);
//当周边有雷的时候才显示雷的个数
if(this.neighborCount>0){
textAlign(CENTER);
fill(0);
text(this.neighborCount, this.x+this.w*0.5, this.y+this.w-6); //居中显示字数
}
}
}
};
//计算周围地雷数量
Cell.prototype.countBees = function(){
if(this.bee){
this.neighborCount = -1;
return;
}
var total = 0;
for(var xoff=-1; xoff<=1; xoff++){
for(var yoff=-1; yoff<=1; yoff++){
var i = this.i + xoff;
var j = this.j + yoff;
if(i>-1 && i<cols && j>-1 && j<rows){
var neighbor = grid[i][j];
//如果隔壁有雷,则增加数字
if(neighbor.bee){
total++;
}
}
}
}
//console.log(total);
this.neighborCount = total;
};
//判断鼠标点击是否在格子内
Cell.prototype.contains = function(x, y){
return (x>this.x && x<this.x + this.w && y>this.y && y<this.y+this.w);
}
//揭开格子
Cell.prototype.reveal = function(){
this.revealed = true;
console.log(this.neighborCount);
if(this.neighborCount == 0){
this.floodFill(); //如果周围没有地雷,自动揭开周围的格子
}
};
//标记或取消标记地雷
Cell.prototype.toggleFlag = function(){
if(!this.revealed){
this.flagged = !this.flagged;
}
};
//自动揭开周围的格子
Cell.prototype.floodFill = function(){
for(var xoff=-1; xoff<=1; xoff++){
for(var yoff=-1; yoff<=1; yoff++){
var i = this.i + xoff;
var j = this.j + yoff;
if(i>-1 && i<cols && j>-1 && j<rows){
var neighbor = grid[i][j];
if(!neighbor.bee && !neighbor.revealed){
neighbor.reveal();
}
}
}
}
};