Nicholas Barger

Entrepreneur - CTO - Engineer

I have a software development background specializing in web technologies coupled with business and management experience. I have direct experience with e-commerce, insurance, medical device, aviation and large web-based applications.

Conway’s Game of Life in Angular.js

2014-10-20

I know there are a lot of posts for Angular, so I will spare everyone a rehash of setup and Hello World. Instead, I thought it would be fun to show a simple example of Angular recreating Conway’s Game of Life.

This example will use the following technologies:

  • HTML
  • CSS
  • Angular.js
  • Bootstrap

If you would like to see a sample of the working application, click here: http://www.nicholasbarger.com/demos/conways-game-of-life.

What is Conway’s Game of Life

Check out Wikipedia: http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for a more in depth definition and origin of the game, but in short, it’s a simulation that allows you to observe evolutions based on an initial starting configuration while applying the following four basic rules at each round:

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

The game can continue indefinitely resulting in either a repeating pattern or a “still life” where no more moves can occur.

Since this article is more about Angular, I’ve simplified the game a bit as well to randomly select the starting positions and limited the board to 30 by 30 cells, but feel free to improve the code to allow the gamer to specify starting positions or infinite space. All source code can be found here: https://github.com/nicholasbarger/conways-game-of-life.

Let’s set up the UI

To start, let’s set up a form and board to play on. The form is pretty straightforward and allows you to specify the number of starting life forms, how many generations to simulate and finally, a button to start the game.

<div class="container" ng-controller="MainController">

<form ng-submit="start()">
            <label>Enter the number of spontaneous lifeforms:</label>
            <input type="number" ng-model="numberOfSpontaneousLifeforms" style="width: 40px;"><br>
            <label>Enter the number of generations to simulate:</label>
            <input type="number" ng-model="numberOfGenerations" style="width: 60px;">
            <button type="submit">Start</button>
        </form>

</div>

Notice, that we’re using a few Angular tags to collect the data and fire off the game.

First, the data to interact with is wrapped with a div that specifies an ng-controller attribute. This attribute is used to specify what controller will be used to execute logic against the HTML DOM elements. It is common to place this controller logic in another Javascript file.

Next, ng-submit is used to specify what function will be called on the controller when the form is submitted. When we wire up the controller, this is the method that will start iterating over generations in the game.

Finally, ng-model is used to bind data values from the input form fields into variables that can be accessed in the controller. When the values on the form are changed, the variables backing them are automatically notified of the change and updated.

Now that we have a form created to gather some basic information about starting the game, let’s create the board that the game will actually play on.

<strong ng-show="rows.length > 0">Generation </strong>
        <table id="board" class="table table-bordered">
            <tr ng-repeat="row in rows">
                <td ng-repeat="cell in row">
                    <i class="glyphicon glyphicon-fire" ng-show="cell.isAlive == true"></i>
                    
                </td>
            </tr>
        </table>

In this code snippet, we see a few new Angular components used for controlling presentation of data.

First, ng-show allows us to toggle the visibility of DOM elements by evaluating a true/false statement. Essentially, when the expression is true, we’re setting a CSS style “display: block”, and when false, setting “display: none”.

Next, we get our first look at the mustache-inspired template rendering (http://mustache.github.io) used by Angular. Notice the double curly braces surrounding the variable name in . This allows rendering of this variable and is automatically updated whenever the value of the variable changes.

The Angular control we have not yet covered is ng-repeat and is used when building out the table as we create rows and cells based on the number of items in the “rows” variable. This simply iterates over the collection and continues to generate the content where the attribute is specified and all information that is a child within it.

Finally, we revisit the ng-show attribute to show a small icon in the cell based on whether it is alive or dead. The “== true” is a bit redundant (and admittedly, should be “===” if used anyway to strictly check the value).

Wire up the Controller to Play

The controller is just a function that sets up all of the code to interact with the UI and exposes the necessary variables through a special parameter called $scope. You can read quite a bit more on $scope through the Angular documentation https://docs.angularjs.org/guide/scope but for simplicity, it’s a way to expose variables to binding in the UI.

If the UI is going to use a variable or call a function, it must be attached to $scope through the following syntax:

$scope.myVariable = ‘Some value’;
$scope.myFunction = function(param1, param2) { return param1 + param2; };

For brevity sake, I will just link to the file hosted on Github since its code is not truly Angular specific and mostly controls running the game. I’ve attempted to comment the rules fairly well so it is evident what is happening in each “generation” of the game. https://github.com/nicholasbarger/conways-game-of-life/blob/master/game.html

Take Away

At my company, we’ve adopted Angular to use every day in production development and haven’t looked back. The benefits of creating a single page applications (SPA) which limits full trips back and forth on the server has allowed us to provide a more native experience over the web while reducing our server load by pushing some of the processing back onto the client.

The example shown in this article is by no means production code and is structured all in one file, which is usually not appropriate for production use. Enterprise level applications need to fully utilize separation into various modules that are comprised of controllers, views, partials, directives, services, and so on.

I’ve learned to stop promising future blog posts since I tend to write in short waves and then neglect my blog for months at a time; however, I think it would be great to write several posts on architecting large Angular web applications and some of the challenges we have faced. Stay tuned (but don’t hold your breath)!

Resetting your defaults

2014-07-10

My blog at nicholasbarger.com pretty much died. It had a decent run from 2008 - 2013, but then a sudden death. I stopped writing, forgot about controlling all of the SPAM comments, and even forgot to update my credit card which subsequently caused my custom css theme to disappear.

I’m not quite ready for a blog eulogy, so time for a reboot and let’s see if we can salvage the remains.

Looking back at why I started my blog, I remember how I wanted to share what knowledge I had and help strengthen what topics I was learning. This was much easier to do when I was focused purely on technical topics. Programming languages, frameworks, libraries, and databases are so much easier to identify learning milestones and gain that feeling of accomplishment. They are black and white, either you know it, and the application you’re writing works, or you don’t and you continue learning more (and look it up on Stack Overflow).

In 2013, I spent the vast majority of my occupation in meetings. Some of my time went to architectural design and creating technical solutions, but most of my time went to project management, scheduling, explaining issues, and rehashing the same thing over and over. Though I complained at times, it wasn’t bad. In fact, I’m pretty sure I learned just as much, if not more during that year than ever before in my career. However, the accomplishments of that kind of learning aren’t black and white, and they can be sneaky at teaching you more abstract lessons.

One of those lessons learned was about how much impact you can have on people in ways you usually don’t even know. There have been many people I worked with directly who I really focused on to try and help and others I feel like I was nothing more than a casual acquaintance. To my surprise, months or years later, it has been the casual acquaintance that I hear from out of the blue to tell me that I made a difference some small (and on rare occasion, big) in their life. It doesn’t happen often, but when it does, it’s quite an experience. First I feel flattered, then a bit confused because what may have been an important conversation or action at the right time for them might have been casual and fleeting for me, and in some cases, I may not even remember it. Sometimes that leads to guilt not intentionally creating a relationship with them as I may have had with others. However, I realize that is how things work, and the impact others have had on me happen in much the same way. Some are direct and built over hundreds or thousands of interactions, others just happen to strike the right cord at the right time.

These interactions give me an occasional reminder of how important it is to set your default to being the kind of person you want to be remembered as, because when your guard is down may be the time you’re making an important impression.

That's one MEAN stack

2014-06-29
MEAN

On Thursday (6/26/2014), we had a nice meet up for the Southwest Florida [.net] Developers Group where I was happy to see some old friends and get the opportunity to present on the MEAN stack. This is a little out of my comfort zone since I am just learning this stack and am by no means an expert on it, but it was fun nonetheless.

This blog post is a bit of a recap on what we covered with some follow up links for more information.

What is the MEAN stack?

The MEAN stack is Mongo as the database, Express as a web server framework, Node as the underlying server, and Angular as the client-side framework. Let’s take a minute and briefly discuss each of these technologies.

Mongo

Mongo DB is a NoSQL document database that uses Javascript syntax and stores data as BSON (binary json). It's not a Mickey Mouse database; it's actually quite powerful, and it's free.

Some of the highlights of Mongo are:

  • Document database (NoSQL)
  • Javascript syntax
  • Stored as BSON (binary JSON)
  • Collections instead of tables
  • Single instance or sharded cluster
  • Replicated servers with automatic master failover

You can learn more about Mongo through 10gen’s introduction.

Also, take a look at comparing SQL to Mongo which is a great article if you’re already experienced in relational databases.

Express

Express is a web-server framework that sits on top of node. It's very lightweight and just makes node a little easier to use for web-based activities.

It’s not the only web framework for node, but it certainly is the most popular. Learn more about express.

Node

Node is server-side Javascript which focuses on non-blocking IO and is uses an event driven model. At first, the notion of writing Javascript to run the server-side code seemed a bit odd to me, but once I got over my old preconceptions of the limitations, I really embraced it.

The “hello world” of node looks a bit like this:

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

You can learn more about node by visiting the official website.

Angular

Angular is a front-end framework for Javascript web applications which is supported by Google. Angular has the following benefits (among others):

  • Creation of new directives which allow you to augment HTML controls.
  • Clean separation of view, controllers, and services.
  • A simple to use binding mechanism for updating the view based on changes in the controller.
  • Testable using the IoC pattern.

More information can be found on the official website.

Try it out

You can try out the MEAN stack in several ways. First, as we did during the meeting, install each component manually by first installing node, and then using npm and bower to install the other packages. You can follow the public Trello board for simple steps that we followed during the presentation.

Two additional ways, which are quite a bit quicker and include additional libraries not covered during the presentation, are to use mean.io and yeoman.io. Both of these are scaffolding tools to get you up quickly and provide a solid foundation to work from.

Past Posts