Creation of a Sokoban game with jQuery

When I said there are games you must be able to make in less than a day, obviously I meant in any language.

This is the jQuery version of the Sokoban game I made in less than 2Kb.

Or, more precisely, it’s the javascript version, powered by jQuery.

You should know the rules… click in the iframe and play using WASD keys.

Let’s take look at the script:

Line 7: loading jQuery

Line 9: function to be executed when the document is ready

Lines 10-16: map initialization. Unfortunately javascript does not support multi-dimensional array creation on the fly…

Lines 17-46: drawing the map. As you can see, all map elements are divs of different classes placed according to their position in the map. Movig objects, such as the player and the crates, are stylized with an high z-index to always stay on top of the map. Various objects are mapped this way:

0: empty tile
1: wall
2: place where to drop a crate
3: crate – crate divs are created with an unique id to indentify them when it’s time to be pushed by the player
4: player
5: crate on a place where to drop a crate (3+2)
6: player on a place where to drop a crate (4+2)

Lines 47-87: Core function… checks for a possible move, eventually moves player and crates and sees if the game is solved.

A game is solved where there are not places where to drop a crate without a crate on them. That is, there isn’t any 2 in the map.

Every time I move a crate, I change its id according to its new position.

Lines 88-103: Checking for key presses.

Hope you enjoy it.