-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
86 lines (73 loc) · 1.75 KB
/
game.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
var grid;
var numBombs = 25;
var playerCoordinate = {
x: 7.5,
y: -7.5
};
var gameEnded = false;
var startTime = Date.now();
function initGame() {
grid = new Array(16).fill(0);
for(var i = 0; i < 16; i++) {
grid[i] = new Array(16).fill(0);
for(var j = 0; j < 16; j++) {
grid[i][j] = {
bomb: false,
number: 0,
revealed: false,
flagged: false
};
}
}
//Plant bombs
plantBombs(numBombs);
setNumBombs(numBombs);
//Print grid to console
printGrid();
}
function plantBombs(totalBombs) {
var bombsPlanted = 0;
while (bombsPlanted < totalBombs) {
var x = getRandomNumber(16);
var y = getRandomNumber(16);
if(!grid[x][y].bomb) {
grid[x][y].bomb = true;
grid[x][y].number = "X";
countNumbers(x,y);
bombsPlanted++;
}
}
}
//Increment numbers based on a given bomb position
function countNumbers(x,y) {
if (inBounds(x-1,y-1)) {grid[x-1][y-1].number++;}
if (inBounds(x ,y-1)) {grid[x ][y-1].number++;}
if (inBounds(x+1,y-1)) {grid[x+1][y-1].number++;}
if (inBounds(x-1,y )) {grid[x-1][y ].number++;}
if (inBounds(x+1,y )) {grid[x+1][y ].number++;}
if (inBounds(x-1,y+1)) {grid[x-1][y+1].number++;}
if (inBounds(x ,y+1)) {grid[x ][y+1].number++;}
if (inBounds(x+1,y+1)) {grid[x+1][y+1].number++;}
}
function inBounds(x,y) {
if (x < 0 || y < 0 || x > 15 || y > 15) {
return false;
}
if (grid[x][y].bomb) {
return false;
}
return true;
}
function printGrid() {
var string = "\n";
for (var i = 0; i < 16; i++) {
for (var k = 0 ; k < 16; k++){
string += grid[i][k].number + " ";
}
string += "\n";
}
console.log(string);
}
function getRandomNumber(max){
return Math.floor((Math.random() * 1000) + 1) % max;
}