AngularJS Game Programming: Making Minesweeper (Part VII)

In the last post we added code to detect and tell the player when they have won. In this post we’re going to add code to detect when the player has lost.

This is actually actually a lot easier, just check if the post where they clicked has as mine. If it does do pretty much the same thing we did when the player won, which is set a flag / variable in the scope.

In this case we set hasLostMessageVisible to true. And just like we did when the user won we add the message to the HTML and use ngIf to show the message when hasLostMessageVisible is true.

To check if they clicked on a mine we update the uncoverSpot() function. From this:

$scope.uncoverSpot = function(spot) {
    spot.isCovered = false;
    
    if(hasWon($scope.minefield)) {
        $scope.isWinMessageVisible = true;
    }
};

To this:

$scope.uncoverSpot = function(spot) {
    spot.isCovered = false;
    
    if(spot.content == "mine") { // new
        $scope.hasLostMessageVisible = true; // new
    } else { // new
        if(hasWon($scope.minefield)) { // original code
            $scope.isWinMessageVisible = true;
        }
    } // new
};

And we add the message to the HTML:

<h3 ng-if="hasLostMessageVisible">You Lost!</h3>

You can play with this code in this JS Fiddle: http://jsfiddle.net/luisperezphd/cdtphbue/

There, now we have the core features of Minesweeper. You can now play the game and win and lose. It doesn’t yet have all the features that the orignal Windows Minesweeper had but it’s certainly a starting point.

I hope you enjoyed it.