Created
March 2, 2012 19:42
-
-
Save dafrancis/1960795 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Matrix = function (rows, cols, bombs, rupoors) { | |
var i, j; | |
this.grid = []; | |
this.rows = rows; | |
this.cols = cols; | |
this.bombs = bombs; | |
this.rupoors = rupoors; | |
this.leftToDig = (rows * cols) - (bombs + rupoors); | |
// fill Matrix with empty holes... | |
/* | |
* I decided that if I made the grid the size it was supposed | |
* to be in the first place there would be less deletion needed | |
* later in the code | |
*/ | |
for (i = 0; i < cols; i++) { | |
var row = []; | |
for (j = 0; j < rows; j++) { | |
row.push("white"); | |
} | |
this.grid.push(row); | |
} | |
this.plantItems("bomb"); | |
this.plantItems("rupoor"); | |
for (i = 0; i < cols; i++) { | |
for (j = 0; j < rows; j++) { | |
if(this.grid[i][j] === "white") { | |
this.determineColor(i, j); | |
} | |
} | |
} | |
}; | |
Matrix.prototype.plantItems = function (item) { | |
var items = 0; | |
while (items < this[item + "s"]) { | |
var item_x = Math.floor(Math.random()*(this.cols)); | |
var item_y = Math.floor(Math.random()*(this.rows)); | |
if (this.grid[item_x][item_y] === "white") { | |
this.grid[item_x][item_y] = item; | |
items++; | |
} | |
} | |
}; | |
Matrix.prototype.hasBomb = function (x, y) { | |
return this.grid[x] && this.grid[x][y] === "bomb"; | |
}; | |
Matrix.prototype.surroundingBombs = function (col, row) { | |
var bombs, i, j; | |
bombs = 0; | |
for (i = -1;i <= 1;i += 1) { | |
for (j = -1;j <= 1;j += 1) { | |
if (this.hasBomb(col + i, row + j) && !(i === 0 && j === 0)) { | |
bombs++; | |
} | |
} | |
} | |
return bombs; | |
}; | |
Matrix.prototype.determineColor = function (x, y) { | |
switch (this.surroundingBombs(x, y)) { | |
case (0): | |
this.grid[x][y] = "green"; | |
break; | |
case (1): | |
case (2): | |
this.grid[x][y] = "blue"; | |
break; | |
case (3): | |
case (4): | |
this.grid[x][y] = "red"; | |
break; | |
case (5): | |
case (6): | |
this.grid[x][y] = "silver"; | |
break; | |
case (7): | |
case (8): | |
this.grid[x][y] = "gold"; | |
break; | |
} | |
}; | |
var matrix = new Matrix(5, 8, 8, 8); | |
console.log(matrix.grid); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment