David Granado

David Granado

"Snake" (2009): My "Hello World" of Games and Javascript

Play Snake (2009)

Back in 2009, Chrome was brand-spankin’ new. Though it would be a while before it became the polished juggernaut it is today, its V8 engine had just fired a warning shot across the bow of Microsoft and Mozilla. You could tell that shit was about to get realz!

I was still a junior developer at the time trying to make heads or tails of all this inter-webz stuff. But a coworker of mine was really starting to focus his attention on javascript. With his help, I was able to really get my head around crazy things like anonymous functions, closures, and function scope.

But to really solidify things, I decided to make a game. Not only would I begin to really learn javascript, but I’d also get to play around with that new-fangled canvas tag!

Armed with my trusty Firebug, it took me two or three evenings to finish.

When I pulled this up, I had my barf bag ready. Code just a year old has the potential to make me queasy. Surely this would be visual food poisoning!

However, I’m pleasantly surprised. Sure, there are a million things I’d do differently. But considering how junior I was at the time, I’d say that it wasn’t that bad of a job.

Implementation notes

The play field is divided up into a grid. The snake itself has a list of coordinates, a direction, and a maximum length. On each tick, the snake adds the adjacent grid coordinate to its list. If the size of the list exceeds the max length, then the tail is removed. This gives the effect of the snake growing out of the ground at the start of the game.

Then, of course, the rest of the checks also happen after the list is updated. Does the new position overlap a piece of food? Does it intersect with another point in the list? Does it go out of bounds?

If you’re curious, the source is available on GitLab.

Fork it on GitLab