-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsketch.js
116 lines (104 loc) · 3.08 KB
/
sketch.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
var grid;
var cols;
var rows;
var w = 40;
var canvasW= 401;
var totalBombs=1;
var fontSize= w * 0.5;
var isGameOver;
var emptyCellsClicked=0;
var totalEmptyCells = 0;
var totalCells=0;
var difficultyLevel = 1;
function setup() {
createCanvas(canvasW, canvasW).parent("#canvasWrapper");
textAlign(CENTER, CENTER);
textSize(fontSize);
cols = floor(width / w);
rows = floor(height / w);
grid = make2DArray(cols,rows);
isGameOver=false;
totalBombs = floor( (canvasW / w) * difficultyLevel);
// create neighbors
for(var i=0; i < cols; i++){
for(var j=0; j < rows; j++){
grid[i][j] = new Cell(i, j, w);
totalCells++;
}
}
// Pik totalBombs spots
var options= [];
for(var i=0; i < cols; i++){
for(var j=0; j < rows; j++){
options.push([i, j]);
}
}
for (var n=0; n < totalBombs; n++){
var index = floor(random(options.length));
var choice = options[index];
var i = choice[0];
var j = choice[1];
options.splice(index, 1);
grid[i][j].bee = true;
}
// Count neighbors
for(var i=0; i < cols; i++){
for(var j=0; j < rows; j++){
var neighborBombs = grid[i][j].countNeighbors();
if(neighborBombs > 0)
totalEmptyCells++;
}
}
console.log("total bombs : ", totalBombs, " difficulty level : ", difficultyLevel);
}
function draw() {
background(255);
for(var i=0; i < cols; i++){
for(var j=0; j < rows; j++){
grid[i][j].show();
}
}
}
function gameOver(){
isGameOver=true;
for(var i=0; i < cols; i++){
for(var j=0; j < rows; j++){
grid[i][j].forceReveal();
}
}
}
function mousePressed(event){
if(!isGameOver){
for(var i=0; i < cols; i++){
for(var j=0; j < rows; j++){
var currentCell = grid[i][j];
if(currentCell.contains(mouseX, mouseY)){
// if left clicked
if(event.button == 0 && currentCell.flagged == false){
currentCell.reveal();
if(currentCell.bee){
currentCell.backgroundColor = color(255, 0 ,0);
gameOver();
}else{
emptyCellsClicked++;
console.log(emptyCellsClicked , totalEmptyCells);
if(emptyCellsClicked == totalEmptyCells){
alert('you won!');
}
}
}else if(event.button == 2 && currentCell.revealed == false){ // if right clicked
currentCell.toggleFlag();
}
return;
}
}
}
}
}
function make2DArray(cols, rows){
var arr = new Array(cols);
for (var i=0; i < arr.length; i++){
arr[i] = new Array(rows);
}
return arr;
}