Browser Games with Canvas, HTML5 and JavaScript

AstroidsI created this nifty little 80’s arcade style 2D Asteroids game almost 5 years ago when Canvas was starting to be adopted by the major browsers.  At the time I was learning JavaScript and Canvas only had limited support so this is meant to be used with Chrome.  At the time Chrome had more support of the features I needed than other browsers.

The code isn’t very clean, I was learning JavaScript and Canvas and this was my proof of concept.  It takes a while to download all the assets so you may have to hit F5 to refresh the browser after a few seconds (then the assets should be cached in the browser).

So why am I sharing this 1/2 finished work of 80’s style geekness?  Because I got out of it what I wanted and won’t have the time to go back and make it better.  It was never intended to catch on, however it’s fun to play for a hour a few times a year when you have time to kill.

So, give it a spin and view source to see the code, it’s all client side code, use the code to make something better, just credit with a link back to this blog.  Astroids


What kind of code do you write?

What kind of code do you write?
What kind of code do you write?

There is no perfect code so have some fun, post or tweet this URL to a friend and tag them with the type of code(s) they write.

#MinimalistCode – You try to use the least amount of characters to write code.  Your code tends to be hard to debug and manage.  Nobody wants to be the person who has to refactor this code.

#BusinessCode – Once value is derived from code you are finished.  The only reason to update is to add more value or debug.  This code often seems unfinished, lacks comments, is hard to manage and is ripe for refractoring.

#PerfectionestCode – Spacing is perfect, every method has a comment, variables are defined in perfect scope, judicious use of patterns.  Unfortunately you take days to write even the smallest throwaway application.  Likely you are a consultant paid by the hour.

#InventorCode – Instead of using well understood patterns you opt to invent your own.  Nobody understands them but not to worry, some day one of your patterns will catch on.

#HackerCode – You find similar code and hack away at it until it does what you want.  You might not understand how it works but you finished the project in record time.

#ManagableCode – Your primary goal is to make your code manageable at all costs, often refactoring many times for no functional benefit.  Nobody likes how long it takes you to write your code but nobody complains when updating your code.

#PerformantCode – Performance is everything to you and you argue milliseconds for the most trivial application.  Your code is often overbuilt and hard to manage but it’s always fast.

#BleedingEdgeCode – If there is a new API, pattern or language that is less than mature, it’s on your list to try out.  You often question your sanity when refactoring your code years later.

#OldSchoolCode – At some point in your career you learned everything there is to learn, nothing new is ever better.  Why use .Net when VB6 can do anything you ever wanted.  Side note, you probably prefer waterfall to agile.

#VendorCode – You follow vendor best practices to the T.  Don’t even talk to me about patterns not supported by the vendor, they must be evil.  For some reason other people can’t wait to refactor your code.

#PurestCode – JavaScript is not a language, C++ is a language.  Don’t talk to me about anything not strongly typed or case sensitive.

#HammerCode – You know one language and one pattern, its your hammer and every development project looks like a nail.  Need a GUI, no problem I’ll code that up in my functional language in no time.  By the way do you like ASCII art?

#MacGyverCode – You like to copy and paste bits and pieces of code to somehow MacGyver together an application.  Why re-invent the wheel, am I right?

#DesignerCode – You are concerned with looking good first and actually working comes in a distant second.  Why write a bunch of code when a picture is worth a thousand functions?

#PracticalCode – If it works, it ships.  Constantly found arguing with the #DesigerCode guy.  What is this usability you speak of?

#SpaghettiCode – Why use classes when you can write more functions?  Did you know some languages still support GoTo!  Why does everyone complain when they update my code?


Node Promises with Bluebird


In the previous post Node.JS for .Net Developers we talked about asynchronous callbacks and showed how to use callbacks to get processes to run in order.  In this post I’ll re-demonstrate the issue but use promises to manage the process synchronously.  Since I’m just learning this myself I’ll provide more of a Simple Sample Example to illustrate with little explanation.  Please comment below to further articulate.

The code:

var request = require('needle');

console.log("*** 1 ***");'',  {"foo":"1","bar":"11"}, function(err, resp) {

console.log("*** 2 ***");'',  {"foo":"2","bar":"2"}, function(err, resp) {

console.log("*** 3 ***");

The output:

*** 1 ***
*** 2 ***
*** 3 ***
{ bar: '11', foo: '1' }
{ bar: '2', foo: '2' }

This demonstrates how Node does not process synchronously which can really speed up a process but fails when you need it to run synchronously.  You can always use callbacks but promises can be a more elegant solution that is easier to manage.

Now lets see how to run this synchronously with Bluebird promises.

The code:

var Promise = require('bluebird');
var request = Promise.promisifyAll(require('needle'));

request.postAsync('', {"foo":"1","bar":"11"}).then(function(resp) {
    console.log("*** 1 ***");
    console.log("*** 2 ***");
}).then(function() {
    request.postAsync('', {"foo": "2", "bar": "22"}).then(function (resp) {
    console.log("*** 3 ***");

The Output:

{ bar: '11', foo: '1' }
*** 1 ***
*** 2 ***
{ bar: '22', foo: '2' }
*** 3 ***

Bluebird has promisifyAll that you can use to wrap an API, that’s what I did to the needle API during the require statement.  To use the API just postfix Async to the end of the method.  In this example request.postAsync was created due to using promisifyAll, if I hadn’t done that only would be available.  The then keyword is the indicator of what function to run when the current one ends.  This allows you to build a synchronous process (do this then do this other thing, then do yet another thing).

I hope this is helpful, please comment below with improvements.

Node.JS for .Net Developers

NodeI’ve been a .Net developer since I got my hands on the first beta and I’ve been a Microsoft stack developer since VB6 and Classic ASP. I’m a big fan and still am. Over the years my roll has changed to architecture and leadership but I still keep my skill current with .Net and databases while investigating new trends in development and data.

I’ve been following Node for a few years now and played around writing some code from time to time. Recently I’ve dedicated more time to learning Node and JavaScript. If you are like me, you have already done some JavaScript development however, like me you probably haven’t been aware of how Asynchronous JavaScript can be and how much impact it has when it’s not being used in the browser.

This post is meant to assist people like me who think in .Net to better understand Node development. But you may be wondering, why learn how to develop in Node in the first place? It’s a great question and in the past one strong reason would be the cross platform aspects. That appears to be changing quickly with .Net, while it’s not mature, it would appear that running .Net code on non-Windows platforms is an eventuality. There are many other reasons to learn Node.

  • It’s open source, currently without any trend to offer separate premium editions
  • It uses JavaScript as the programming language.  Why is that important?  See this post:
  • It’s Asynchronous by default and very performant because of it
  • It’s much less opinionated that most languages yet you can still use opinionated plug-ins if you choose
  • If you are into SOA and Micro Services (and you should be) especially at scale, Node can really make sense because:
  • The overall memory footprint of Node is small and it doesn’t rely on a web server like IIS or Apache
  • While it’s Asynchronous it does not spin up a bunch of threads that are copies of the complete application

Alright, enough talk, lets see some code.  The following example should be understandable to most .Net developers:

Define the function:

function doStuff(myParm) {
this.var1 = myParm;
return this.var1;

Call the function:

var myVar = doStuff('Hello World');

If you execute this example you should see “Hello World” as output.  The only thing that might be odd to you is the This keyword.  Basically it’s used for local function variables.  It’s easy to learn and use and once you do you wish other languages used it.  If you want to know the details you can read more here.

Much of JavaScript and Node made complete sense just coming from .Net but even though I did some Asynchronious development with .Net over the years I was not prepared for Node’s use of callbacks everywhere.  This to me was the biggest thing I had to get my head around.  There is no avoiding it so you need to figure it out if you want to develop in node.  There are lots of examples you can find online to learn callbacks, I’m going to use a couple Simple Sample Examples of callbacks that make more sense to me coming from .Net.

Define the function:

function sumFunction(arg1, arg2, callback) {
    var answer = arg1 + arg2;

Call the function:

sumFunction(5, 15, function(num) {
    console.log("The callback was called and the num varable contains: " + num);

This will output “The callback was called and the num varable contains: 20”.  In .Net you might expect the function to return answer but with Node/JavaScript when defining the function we say there are two augments to pass and the callback then instead of returning the answer we call the callback function and pass the answer to it.

It’s kind of like saying, when you call the function in addition to the arguments needed to run the function, send me a function to run, when I’m done and I’ll run that function and pass the answer to it.

When you call the function you pass the argument data (5 and 15 in this case) and tell Node/Javascript to pass the callback back to me.  You do this in the call by typing Function(variable){} The answer that would have been returned in .Net is instead calling this unnamed function “function(num){} it’s passing the variable answer to the variable num.

Now I’m going to really try to make your brain hurt.  Review this example:

var request = require('needle');

var answer;'', {"MPN":"Answer1","ITEM_DESC":"Answer One"},  function(err, resp) {
    answer = resp.body.form;
    console.log("Console.log within the callback: " + JSON.stringify(answer));

console.log("the answer variable is: " + answer);

Doesn’t look bad, right?  Lets walk through it with some traditional .Net (or most languages) synchronous logic.  First we import an API for communicating with Rest services called needle.  Then we define a variable (once you get used to not defining your variable types you start to like it.  Yeah you can run into code that only has an error during run-time but personally I have had this happen very serfdom). Next you Post JSON to a Rest service and on the callback you set the answer variable to the results you received, additionally we push it to the console, finally we write the contents of the answer variable to the console.  You would expect the following output:

Console.log within the callback: {“ITEM_DESC”:”Answer One”,”MPN”:”Answer1″}
the answer variable is: {“ITEM_DESC”:”Answer One”,”MPN”:”Answer1″}

If you are still with me, now is when your brain will start to hurt.  The following is the actual output:

the answer variable is: undefined
Console.log within the callback: {“ITEM_DESC”:”Answer One”,”MPN”:”Answer1″}

This is because everything is executing asynchronous.  When Node executes the call to the Rest service it doesn’t wait around for an answer it will let the callback handle that, it goes on to execute the next command

console.log("the answer variable is: " + answer);

which means the data has not yet been pushed to the answer variable therefore it is “undefined”.  So basically what we have learned from this is that if you want to do something with the data returned, you need to use a call back to process it.  This allows you to run synchronous processes in an asynchronous environment and not block the rest of the program from running.

If you are like me you start thinking about the code you write and think most of it needs to run in a particular order, do this, then when you get the answer do this other thing, then with that answer do yet another thing, and so on.  Trust me it’s because that’s how we learned how to code, once you start developing more with Node you’ll realize all the places with blocking code and when some things can run asynchronous.

Lets say for example you write a service that validates an order.  One thing you might do is iterate through each item and calculate the price + qty, verify the sub total, based on sub total you may call a tax service and verify tax is calculated correctly, then calculate shipping and make sure the grand total is correct.  For the most part you want to run this in order, however you could calculate tax and shipping based on the sub total asynchronously if the item total equals the sub total you already have your tax and shipping answers and you’ve saved some time, at scale you’ve saved a lot of time.  Still not convinced?  Think about this, while you are verifying the total, you can be performing address verification, credit card authorizations, phone, name and email syntax verification, stock availability checks, etc…  All at the same time without blocking.  This can turn a 10 second process into a sub 1 second process.  If you are processing a couple orders a min it’s not a big deal.  If you are processing hundreds of orders a min it’s a big deal!

Back to the problem in the last example.  As we know we can just use the callback to “do the next thing”.  The problem you run into with longer processes is callback hell.    The linked page offers some good suggestions on how to mange code better to lessen the impact.  What I have found is that most people use Promises to avoid dealing with callbacks directly and make their code more manageable.  But that’s another post.

A couple final words.  I’m new to Node and not an expert in Javascript.  Writing these posts hopefully helps others learn and helps me learn as well.  If you see errors or better patterns please comment on this post to help me and others reading this.  The last thing I want to mention regarding Node for experienced .Net developers is the IDE.  Visual Studio is the best IDE hands down, finding a good IDE for Node will really accelerate your development.  I recently reviewed many popular IDE’s and settled in on WebStorm by JetBrains.  The IDE just made scene to me coming from Visual Studio.  Again, please comment below with your opinions on IDE’s for Node.

Why you should learn JavaScript now!

Learn JavaScript
Learn JavaScript

Many people will use statistical evidence to convince you that JavaScript is the best language to learn.  They’re not wrong, it is an extremely popular language used in almost every web site and is listed as a skill in an in-sane number of job postings.  It’s also easy to get started learning JavaScript, it’s simple yet powerful.

I’m going to appeal to your geek side to convince you to learn JavaScript and hopefully convince people that an architecture using JavaScript can provide the most elegant solution end to end.

It all starts with the browser, as you know JavaScript owns the browser, with some minor exceptions it’s the only language used in the browser.  This is reason enough to learn JavaScript, especially since more and more traditional applications are migrating to the web and using the browser as the user interface.

The only real challenger to the web browser are mobile applications, the kind that run on your smartphone or tablet.  JavaScript is not only used on web pages running on mobile devices but many times it’s used to build the apps you download and run on them.  There is a popular framework PhoneGap (or Cordova the open source version) that enables JavaScript to work with the phone hardware such as Geo Location, the camera, the accelerometer, etc…

So JavaScript owns the user interface, I get it but what about all that other back end code?  I’m glad you asked!  Node.JS is one of the most exciting developments in recent geek history.  Node.JS uses Google Chrome’s V8 engine  to run JavaScript on the server side.  That’s right you can now use JavaScript for your back end code instead of languages like PHP, Java, .Net, etc…

OK so it’s cool that you can use JavaScript server side but should you?  Since it’s interpreted and designed for client side, is it slow?  You’re asking great questions, the answer is yes and no.  Yes you should and no it’s not slow.  JavaScript is non-blocking which is basically like writing code with built in threading.  (technically you can write JavaScript to be blocking if you wanted to)  This make it fast, especially for if you have a high velocity of small requests.

Microservices and SOA (Service Oriented Architecture) are quickly becoming recognized as one of the best software development architectures.  JavaScript is perfect for these architectures as it thrives on small services that can be orchestrated to comprise various applications with maximum reusability, scalability, and ease of development.  But that’s not all!  Since these architectures usually use web services to communicate, with each other, modern architectures use JSON/REST web services.  JSON happens to be the efficient and easy to use object that JavaScript uses (JSON came from JavaScript).

This is a very important fact, if your architecture uses JSON objects, there is no translation needed when developing new JavaScript services, the communication is native.  If these services support a web interface those same JSON objects can be passed up and down the stack without any translation.

So by this point you’re convinced that JavaScript makes total sense, its’ given with the UI and recent developments makes it a great back end language as well.  Not to mention sending data back and forth using JSON/REST web services.  Can it get any better?  It sure can.

Some NoSQL  databases like Couchbase (my personal favorite) store data in (you guessed it) JSON format.  Then uses something called MapReduce to query the data.  Can you guess what language MapReduce uses in Couchbase?  Yup, JavaScript!  Using this architecture you can use JavaScript and JSON for complete applications UI to database and back again.  This makes ORM’s obsolete, no need to translate between objects and SQL data structures anymore.  This makes development much faster and your applications significantly more performant.

This architecture makes real business sense.  Not only are you developing in a language that is easy to learn, there already exists a large army of JavaScript developers.  The majority of your staff can use a single language to develop complete solutions using modern architectures and databases that are not only scale better they are more performant and if architected correctly allow for more rapid development when compared to traditional architectures.

So JavaScript really is the perfect language.  Well, not always, just for most things.  It probably won’t replace R for statistical analysis, it may be a while before there is much support in the embedded industry, and it’s not designed for long running processes.  Because it’s so new on the server side, it doesn’t have as much API support as traditional languages.  That’s changing fast either with direct API support or because so many solutions now support JSON/REST APIs.

I hope you found this useful and encourage you to debate or add to the argument in the comments.