HTML5 multiplayer Snake game with Node.js and WebSocket

Why Node.js is good choice for browser game?


Since front-end logic of game was written in JavaScript, it will be great to share the same lines of code with server. For example, detection of collision with other snakes should be validated on both application sides.

Problem…

Logic on browser side must not expose any server-specific processes or data – register of all connected clients, clients IP etc.

… and the solution:

JavaScript’s overloading during the runtime will be salvation here. File ./shared/SnakeGameCore.js contains core logic related to: moving snake, going through the walls, colliding with other players and all constant values. The same file is use on the client side, however on the server side method processMove() has attached extra logic.
When snake eat some block, there should appear another one, but logic behind – choosing new coordinates – should stay just for server. proxyGameBoardMethods() alter method from shared file, adding new action!

Source code

That little project (so far) use only vanilla JS, however node server requires 2 additional packages: colors and websocket (use npm colors websocket ).
To run it, just go to server/ directory and run node SnakeGameServer.js .
On client side, remember to update IP address of your server in app/index.html .
The source is available at github.com/rinz/snake .
Any comments or ideas are welcomed!

Posted in Frameworks, JavaScript, Node.JS | Leave a comment

Micro ORM in Python

Probably as most of us, I hate adding new 3rd-party libraries to achieve some simple functionality, like (in that case) writing some entities to database. Also, I never did pure SQL insert via Python. But, I am big fan of Django build-in ORM, so I tried develop similar API:

 
t = Test(db)	
t.age = 45
t.name = "John"
t.job_title = "Smith"
Test.save(t)
 

Firstly, we will used a little wrapper around database connection, to use as follows:

 
db = Database("localhost", "root", "", "ex1")
 

That is probably very ugly part of my example because db object will be treat as a global one.
Let’s see at base Table class, from which every entity object should inherit:

 
class Table(): 

	db = None
	ID = None

	def __init__(self, db):
		self.db = db

	def __getitem__(self, k):
		return self

	@classmethod
	def select(cls):
		cursor = db.conn.cursor()
		cursor.execute("SELECT * FROM %s;" % cls.__name__)

		result_array =  [] 
		for row in cursor.fetchall():

			result_array.append(cls(db, *row))

		return result_array

	@staticmethod
	def save(o):
		cursor = db.conn.cursor()
		sql = "INSERT INTO %s(%s) VALUES (%s);" % ((o.__class__.__name__,) + (",".join(o.values),) + (o.values_t,))

		format_array =  [] 
		for key in  o.values:
			format_array.append(o.__dict__ [key] ) 

		cursor.execute(sql, tuple(format_array))
		db.conn.commit()
 

Decorator classmethod makes method static and get its classname as a first argument ( cls ), which we use to map received record to create new object current class.

 
class Test(Table):

	name = None
	age = None
	job_title = None

	#required configuration field needed by base (Table) class
	values = ("name", "age", "job_title")
	values_t = "%s, %s, %s"

	def __init__(self, db = None, id = None, name = None, age = None, job_title = None):

		self.ID = id
		self.name = name
		self.age = age
		self.job_title = job_title

		Table.__init__(self, db)

	def __str__(self):
		return "#%s\t{Name: %s, Age: %s, Job title: %s}" % (self.ID, self.name, str(self.age), self.job_title)
 

Test is example class inherits from Table , it consist 3 field. All of them need to be listed in values tuple, and all of their types must be listed in values_t tuple.
Using select method via Test class, results cls parameter will get actual class name.

The whole code is available at github.com .

Posted in Python | Leave a comment

Git (pre) commit hook to put revision number in source file

Revision identifier in source code – especially in web apps – is pretty useful. Combined to automatic deployment, you could easy check if latest one is deployed.

So, how it could be accomplished in Git?
All hooks are stored in $PROJECT/.git/hooks/ , we are looking for pre-commit . Unfortunately, Git hasn’t nice, incremented ids. My workaround is simply count all commits (and subtract 2).

pre-commit file:

 #!/bin/sh

revision_number=`git shortlog | wc -l`; 

exec ./.git/hooks/replace_revision.py $((revision_number - 2))

git update-index --again 

replace_revision.py is simple loop which replace previous comment which contains revision number:

 
#!/usr/bin/env python
	
import fileinput
import sys

import os

def replaceAll(file):
    for line in fileinput.input(file, inplace=1):
        if "<!-- revision " in line:
            line = "<!-- revision #%s -->\n" % str(sys.argv [1] )
        sys.stdout.write(line)
		
replaceAll("app/index.html")
 
Posted in Git | Leave a comment

Closure in Java 6

There is a way to encapsulate variable’s value into definition another method. Of course, it is far less flexible than “real” closure, like that one in JavaScript… but in my humble opinion it is still closure!
Keyword final and new inner class are required:

 
public static void main(String []  args) {

	final String SECRET = "HELLO CLOSURE";

	class InnerSecretClass{

		public String getSecret(){
			return SECRET;
		}
	}

	System.out.println(new InnerSecretClass().getSecret());

}
 
Posted in Java | 2 Comments

Google Reader add-on – feeds social sorting bookmarklet

My friend reads a lot of feeds (RSS) thus he is looking for a solution to filter they by popularity. Easiest way to achieve it, is to use Facebook’s likes and Twitter’s tweets (of course). I wrote a little piece of JavaScript to bring “social” points to every news from your reader.

That is what it looks like: .

How to use it? Just create new bookmark in your browser with location URL as following:

after that, load Google Reader, choose some RSS and click bookmark. Two buttons will appear – one for likes and one for tweets.

Script is not entirely client-side, I use json-longurl.appspot.com service to expand shorten urls, (like that ones from feedproxy.google.com).

Source code is available on github , feel free to fork and patch.

Posted in functional programming, jquery | Leave a comment

Very nice book to read (still) – “Silence on the wire”.

It was not easy to get it, I have been waiting for it few months, until it finally shows up in my RSS reader. Unfortunately, I paid more than it cost 7 years ago, but I was really curious why that book is so… legendary.
Worth to say, author is also pretty much respected . I was lucky enough to read it in author’s native language – polish.

Book present absolutely surprisingly, new look at network security. If you would like to know:

  • how pseudo-random number generator could betray your OS?
  • how your browser could be recognized without cookies?
  • which (and how many) bits could be undefined in every single IP packet? (and why it is dangerous)

To be honest, before I read “Silence on the wire” my network knowledge were poor – I didn’t use network programming in any bigger project, now I am inspired to dig topic deeper.

Posted in Books, network, security | Leave a comment

Reason I have loved functional programming #2 – anonymous (lambda) functions

The more time I spend with functional programming (in JavaScript), the more I like it. Sophisticated but clear and short solution bring my face some sort of evil-genius smile. A lot of satisfaction also. Here is that kind piece of code.
My goal was to achieve, clicking on one button will copy current level input box value, to all inputs below. Let’s say I have 12 inputs for each month:

 
<ul>
    <li id="jan">
        January:
        <input type="text" />
        <button>Copy</button>            
    </li>
    <li id="feb">
        February:
        <input type="text" />
        <button>Copy</button>           
    </li>
    (...)
 

Instead of mapping current id to below elements, I used functional paradigm – create appropriate function on the fly:

 
$(function() {
    var months =  ["jan", "feb", "mar", "apr", "may", "jul", "aug", "sep", "oct", "nov", "dec"] ;

    var generate_copy_function = function(start) {
        return function() {
            var current_value = $("#" + months [start]  + " input").val();


            for (var i = start; i < months.length; i++) {
                $("#" + months [i]  + " input").val(current_value);
            }
        }
    }
            
    for (var m in months) {
        $("#" + months [m]  + " button").click(generate_copy_function(m));
    }
})
 

The big advantage of this solution is that you create your own customized function, adjusted to the
specific needs of the script. generate_copy_function() encapsulate “start” index, thus we don’t need bother about properly argument and properly switch to dispatch it – each generated function is as small as it could be. Really nice, isn’t it?

Live demo: http://jsfiddle.net/fk2Xd/ .

Posted in functional programming, JavaScript, jquery | Leave a comment

Join-K game problem from Google Code Jam

In that post, I will present my attempt to solve problem from Google Code Jam (2010) – Rotate . In about week, new edition GCJ will start so I decided take the challenge. Let’s solve one riddle from previous edition, to warm up brain. For my solution I chose python – I consider it as ideal tool for algorithm’s proof-of-concept, although I am not very advance python programmer.

My first noteworthy idea is that, we don’t really need to rotate our matrix, all we need to do is change gravity line – to the right border of checkboard.

Relative positions of all pieces will be the same as we really rotate matrix. It saves a lot of operation.
Now let’s gravity takes effect. It have to do 2 things:

  • removes all empty field between any 2 pieces and
     
                            self.matrix [y] .pop(x)
     
  • move the whole row to the right side
     
                            self.matrix [y] .insert(0, ".")
     

I did it in the following way – after checking if there is really cause to move Xst piece:

Last step, will be of course looking for the winner. Nothing special here, for each non-empty field, I invoke checkKMatrix() method, to check sub-matrix starting from x & y. To more readable code, I used exception instead of bunch of “ifs”, which slows down execution of course. As following (micro) tests shows, exceptions slow down algorithms a lot !

 
>>> timeit.Timer(lambda :  [raiseAndcatchException(x) for x in range(10)] ).timeit()
20.328131673448752
>>> timeit.Timer(lambda :  [check3conditions(x) for x in range(10)] ).timeit()
3.606481800403799
 

One another nice optimization what we could do. Consider following case: There is no reason to move all rows to right border, much better will be move only one mismatched row to the left. Generalizing, to better performance we should find the most filled column going from right to left, and align another rows to it.

That is all what I could figure out to make the best solution Join-K problem. My latest version of code could be find at my github account.

Posted in Algorithms, Python | Tagged | 2 Comments

Keep thinking

We are programmers, but most of the time we spend on learning new framework/language, implementing some functionality… or finding bug. Thus, whenever I found some online algorithms riddles site I try solve something. Recently, I found coderbyte.com . Problems are not complicated, but nice and clean solutions are not so obvious to achieve. Additional, for all riddles there are some amount of time to solve.

And here is my solution for 1st guest riddle – tell me if you got better.

PS. Anyone, know good wordpress spoiler plugin which works with formatted “code block”?

Posted in Algorithms | Leave a comment

Passing context to another (with dojo) – simple closure example.

Recently, I had to develop some components using Dojo framework. Unfortunately, until then, my Javascript experience include only jQuery, thus I have not been using pure JS. My component should be widget representing one wizard step – the final one. It had to be part of whole wizard object of course.

After fill up correctly our widget forms, I should trigger action which close the whole wizard (method hide , defined in parent wizard object). The problem: how to define function (which must be passed to last widget) which will be able close parent widget?

Of course, solution will be closure :

 
...
	doneFunctionClosure: function(){
		var that = this;
		return {
			doneFunction: function(){
				that.dialog.hide();
			},
		};
	},
...
 

Now, I could pass it to my widget by following: doneFunctionClosure().doneFunction .

That was my first real world example of js closure, and I am proud of that piece of code.

Anyone who also would like to extend their javascript knowledge, and looking for some not-for-dummies article, I recommend JavaScript Garden .

Posted in JavaScript, Languages | Tagged | Leave a comment