Last time on “AngularJS Game Programming”: We added graphics to a basic working minefield that allows you to uncover blocks. In this post we’re going to add mines!
Adding Mines
Ok, now we’re ready to add mines to the minefield. First let’s write the code to place a single random mine. Let’s start by calculating the row and column where the mine will be placed:
var row = Math.round(Math.random() * 8); var column = Math.round(Math.random() * 8);
Then we need a way to retrieve information about that spot so that we can indicate there’s a mine there:
function getSpot(minefield, row, column) { return minefield.rows[row].spots[column]; }
Now we need a way to store that information somehow. Let’s create a property in the spot and set it to either “empty” or “mine”. Our mine placing function should look like this:
function placeRandomMine(minefield) { var row = Math.round(Math.random() * 8); var column = Math.round(Math.random() * 8); var spot = getSpot(minefield, row, column); spot.content = "mine"; }
Now we need to update the createMinefield()
function so that it initially sets content
to “empty”.
var spot = {}; spot.isCovered = true; spot.content = "empty"; // new row.spots.push(spot);
Now we need a way to display it. The spot should look empty if content
is set to “empty” and isCovered
is false
. You should see a mine if isCovered
is set to false
and content
is set to “mine”.
Your td
should now look like this:
<td ng-repeat="spot in row.spots" ng-click="spot.isCovered = false"> <img ng-if="spot.isCovered" src="block.png"> <img ng-if="!spot.isCovered && spot.content == 'empty'" src="empty.png"> <img ng-if="!spot.isCovered && spot.content == 'mine'" src="mine.png"> </td>
Let’s do a quick test by placing one mine in the minefield. Update the createMinefield()
to call placeRandomMine()
. Then click to uncover the blocks until you find it – it might take a while:
Play with it at: http://jsfiddle.net/luisperezphd/Ap8Xp/
More Mines
Let’s add a function to place more mines. Name it placeManyRandomMines()
and have it call placeRandomMine()
10 times:
function placeManyRandomMines(minefield) { for(var i = 0; i < 10; i++) { placeRandomMine(minefield); } }
Update createMinefield()
to call this function instead of the previous one that only places one mine. Again test it by clicking on the blocks until you uncover several mines:
Play with it at: http://jsfiddle.net/luisperezphd/V5pwz/
Next Time
In the next post we’re going to add numbers and get one step closer to the full game.
Next Post: Adding Numbers