RunPigsRun: handling collisions.


Collisions in RunPigsRun

One of the things that gives me some confidence about finishing this project is the form of its gameplay. Objects are moved from field to field in a predictable way. Collisions are checked after all the objects finish their movement, which simplifies the work.

Which collisions are already handled?

  1. Hero + Bouncer
    • changes object’s speed
    • plays scaling animation for the bouncer
  2. Hero + Void field; Hero + Water field
    • removes hero from the game
    • reports game’s loss
    • plays field’s scale animation
  3. Hero + Exit
    • removes hero from the game
    • reports that hero was saved

How it’s implemented

I really like Javascript’s duck typing. Earlier Mr. Czocher reported in comments, that I should checkout Typescript, which (I assume from the introduction videos) will make code more standardized e.g. by interfaces. I’m really curious if it will not lower the speed of coding, as with my current code organization I’m having a really small amount of bugs and generally work goes smooth. That was just a small digression. What I want to say, that with Javascript’s conventions I’ve come up with a nice way to define functions handling collisions between pair of objects.

First: objects which ends their movement outside of the map are removed. Before that, CollisionsHandler sends signal about object which is about to be removed and GameResultResolver checks if it’s not a Hero.

 * Every remove should go through here to ensure signal dispatch.
CollisionsHandler.prototype.handleRemove = 
  // dispatch signal BEFORE removing object

GameResultResolver.prototype.slotObjectRemoved = 
function(OBJECT) {
  if (OBJECT.type === GOT.HERO)
    this.resultObject.loss = true;

Next all the objects on the tile are compared between each other with handleCollisionPair().

CollisionsHandler.prototype.handleTileCollisions = 
function(TILE) {
  for (var I = 0; I < TILE.length; I++)
    for (var J = I + 1; J < TILE.length; J++) {
      // unique pair (no two objects compared more than once)
      RESULTS = handleCollisionPair(TILE[I], TILE[J]);
      if (RESULTS === undefined) {
        console.error("RESULTS === undefined");
      for (var R in RESULTS)


Now the heart of this post. I was wondering how to write simple code, which will:

  • handle collision result between a pair of objects
  • take into account that the order of passed objects is not predictable (is it HERO vs BOUNCER or BOUNCER vs HERO?)

The solution is quite elegant in my opinion: objects’ type names are used to locate the name of the function returning collision result.

 * Get collision function name by concating object type names 
 * sorted alphabetically.
function getCollisionFunctionName(OBJ_A, OBJ_B) {
  return "collision" + ((OBJ_A.type < OBJ_B.type) ?
    OBJ_A.type + OBJ_B.type :
    OBJ_B.type + OBJ_A.type);

So: collision between ‘hero’ and ‘t_bouncer’ gives the same function name as collision between ‘t_bouncer’ and ‘hero’. In this case: collisionherot_bouncer(). handleCollisionPair() returns the result of such function and passed arguments are also sorted alphabetically, which ensures that collision function is invoked always in the same way:

function handleCollisionPair(OBJ_A, OBJ_B) {
  var fname = getCollisionFunctionName(OBJ_A, OBJ_B);
  if (typeof window[fname] !== 'function')
    console.error("no colision function: " + fname);
  if (OBJ_A.type < OBJ_B.type)
    return window[fname](OBJ_A, OBJ_B);
    return window[fname](OBJ_B, OBJ_A); // switch objects (alphabetical order)

Collision results

Functions checking collision result return an array of CollisionResult objects which keep data about objects modified as a result of the collision, type of operation which should be performed and optional arguments.

function CollisionResult(OBJECT, OPERATION, ARG) {
  this.object = OBJECT;
  this.operation = OPERATION;
  this.arg = ARG;

  REMOVE: "remove",
  RESCUE: "rescue", // rescue object (hero)
  SCALE_ANIMATION: "scaleAnim", // temporary firework
  SPEED_CHANGE: "speed"

Example of function resolving collision between HERO and BOUNCER:

function collisionherot_bouncer(HERO, TOOL_BOUNCER) {
  return [
    new CollisionResult(
    new CollisionResult(

Easy and clear: collision changes Hero’s speed (bounce) and plays scale animation for bouncer. Now every object from the array is passed to handleCollisionResult().

CollisionsHandler.prototype.handleCollisionResult = 
function(RESULT) {
  switch (RESULT.operation) {
      this.handleRemove(RESULT.object, "objectRemoved");
      RESULT.object.startScaleAnimation(, RESULT.arg);
      if (RESULT.object.type === GOT.HERO)
        this.handleRemove(RESULT.object, "objectRescued");
      console.error("not implemented: " + RESULT.operation);

In the end.

If the new object is introduced, e.g ‘superObject’, and collision between this object and ‘hero’ object should be handled, only the…

function collisionherosuperobject(HERO, SUPEROBJECT) {
  return [];

returning the array of collision results, should be added.

New collision = new function. Easy.

Tiled Editor: composing levels.


What is it?

Phaser framework supports loading data about the maps from a couple of formats. As RunPigsRun is not a complicated game with levels built from tiles, Tiled map editor is a sufficient choice.

How does it work?

First an image presenting a tileset is needed, I’ve got mine from here: (by: As I’ve mentioned earlier: don’t care how the set looks (although it’s nice). After importing image to program, three types of layers from which level can be built are available:

  1. Background Layer. Tiles on this layer are intended to be used as a background: in the game they will be only displayed. Even putting them in editor reminds drawing with a brush.
  2. Object Layer. Used to create concrete objects represented by a tile image. Such objects can be translated/rotated. They are named and put into an objects tree. In contrary to Background Layer, created objects are exported with information like: position, id of a tile in a tileset or custom properties (properties set by us).
  3. Image Layer. Don’t know, never used it. Probably used to insert an image.


After level is finished, it can be exported to many formats. Some of them are easily parsed by Phaser.


First: loading background. Few lines and we’re good to go:

// loading map: =
        'level' + this.levelId); 
// loading image for background:
        'basictiles', assetsConstants.SPREADSHEET_BASIC); 
        scaleConstants.GAME_W, scaleConstants.GAME_H, 

After that, the image has to be scaled and translated. For these I’m using constants:

  • this.tilemapLayers[i].scale.x = scaleConstants.MAIN_SCALE (scale for every visually measurable number in a game, like distances or object’s dimensions)
  • this.tilemapLayers[i].x = scaleConstants.GAME_OFFSET_X * scaleConstants.TILE_SIZE_SCALED (position = map offset in tiles * scaled tile dimensions)

Next: loading objects (like roads or an exit).

var objectsLevel =;
for (var i = 0; i < objectsLevel.length; i++)

Written function tileObjectToGameObjectParams converts loaded Tiled object to my GameObjectParams used to describe object created by a GameObjectsManager.

Custom Properties

Right now one object in a game needs an extra attentions: a hut. It has a capacity parameter, which describes how many heroes it will create. Tiled allows to add such ‘Custom Property’ to an object, and later that property if of course shipped along with the other data.

GameObjectsManagerHuts.prototype.countHeroes = function() {
        var cnt = 0;
        for (var i in this.objects)
                cnt += parseInt(
        return cnt;

In the end

Tiled is a concrete piece of software: does its job very well. An easy and a pleasant way to compose a level with a background and objects.

written in Emacs with org2blog mode

RunPigsRun: the code organization.


As this is my second project in Javascript, I’ve manage to achieve code organization/conventions, which helps me to move through code quickly and make it less error prone. I was mainly inspired by some games from There will be nothing revolutionary nor even advanced here.


I’m a fanatic of decomposing code into classes, every time, everywhere. Class should be concrete, specialized, well named and decomposed into specialized functions. If class is getting big, part of its functionality should be extracted into another classes.

Everything above is crystal clear, yet generally JS is strangely considered as a language, where everything should be accessible from everywhere, and code is just one big sequence of monstrous functions which are so, so, so… SO hard to read. Sometimes it’s even impossible to track paired brackets. Anyway: readability first… as the famous quoute says:

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

Generally I’m organizing code into directories to simulate something like packages… Next: I’m writing quite a lot of constructor classes. New concept = new class. New specialized functionality = new class.

If a new function is not depending on a class, I’m putting it in a different file. E.g. having MovementManager class, some help functions are needed like movementDirectionOpposite (returning opposite direction), which is used only by MovementManager. Hence this function is not using class, it lands in a separate file moveFunctions.js.

Object orientation

I’m carefully tracking how classes are connected with composition and how they are communicating with each other, so general objective oriented programming principles are followed. Drawing UML class diagrams is a helpful way of tracking if the code organization is kept clean.

Composition vs inheritance

I’m not using inheritance through prototypes, as I agree, that inheritance is (generally) only good for type casting done in other languages. For now, composition solves every problem and makes code easily understandable.


Constant variables are indicated by using uppercase. Used also in function arguments, to not to accidentally modify unwanted object, which was a reason of many hard to track errors (example of such struggle:

When a value (int/string) is used more than one time, then it’s frozen with Object.freeze. E.g defining GameObject types:

GameObjectType = Object.freeze({
        VOID: "void", // for empty fields
        HUT: "hut",
        HERO: "hero",
        ROAD: "road",
        BRIDGE: "bridge",
        WATER: "water",
        SIGN: "sign",
        TOOL_BOUNCER: "t_bouncer",
        TOOL_DUMMY: "t_dummy"
GOT = GameObjectType; // alias

Later instead of writing:

if (OBJECT.type === "hero") {

a constant is used…

if (OBJECT.type === GOT.HERO) {

… which assures, that no typo is made.

Further reading

I’m aware that some further reading awaits to improve code organization and its readability and my current Javascript knowledge needs a lot of improvement. Candidates for a study in a nearest future:

  • JavaScript: The Good Parts, Douglas Crockford
  • JavaScript Patterns, Stoyan Stefanov
  • Maintainable JavaScript, Nicholas C. Zakas
  • Speaking JavaScript. An In-Depth Guide for Programmers, Axel Rauschmayer

written in Emacs with org2blog mode

Beeminder: a healthy sting.


Previously described Rescuetime is doing almost a perfect job. You can track Your daily productivity and weekly goals (remember how You can create ‘Software Development’ objective?). But what if You fail to achieve Your personal vow, to work on a software project X hours a week? Ha! Nothing! Maybe You feel a little bad, that’s all.

I’ve heard that in one office, when someone had sworn, he had to put some cash in a jar. It’s the same like saying to someone ‘punch me, if I ever do X again’. Or when You make an agreement with someone, to not to come back to a bad habit (smoking maybe?) as long as he/she does something similar, which is important to You, in return. A public agreement… someone is watching You, so it’s harder to break the rules!

How about something guarding our goal to spend X hours a week on a software development? Let me introduce You to …

… “A kick in the pants!”


Beeminder is a service allowing to create weekly goals on doing anything quantifiable. Users have to report their progress on a website or with a dedicated mobile application. Current status can be tracked, by reading how much we have to do, to make our objectives valid. If we are approaching the deadline, Beeminder starts to go crazy and reminds us to get to work by sending emails and by displaying regular popups on a mobile (e.g 12h left for Goal X). This is how the goals summary look like on a mobile:


It’s crystal clear what the status is. Some data has to be reported manually (like how much we’ve read today) and some is gathered by Beeminder automatically, when we are using supported external service.

“Follow through or pay the price.”

Now this is a part, which may seem controversial, or rather ‘stupid’, as say most of the people for whom I’ve told about Beeminder. How user is punished for not reporting data on time? By money taken away from the credit card. We are setting how much will be lost, and these are small, but yet motivating amounts (like 5$, 10$). There has to be that little noticeable punishment.

Personally I’m not so motivated by the money loss (but to be honest, it’s taking some part in a Beeminder challenge too). Rather by the failure, which is felt, when application is showing skull and crossbones on a goal entry icon. Then an extra week is added to the deadline, so the user has a bigger chance to stay on a goal track. And it feels bad, because the wonderful rhythm of a regular work is lost.

“Light a fire under your own butt…”

When it’s about goals, which cannot be verified by a Beeminder, users can be tempted to log a false data. But then: what’s the point of using this service anyway?

As mentioned, there are also services, which will report data automatically and one of them is the previously introduced Rescuetime. Software Development goal can be connected with Beeminder and voilà! There is no escape now from not spending a set time with our project.

I’ve had a couple of situations, when I had to rush back home, to work a required amount of time with Run Pigs Run. I’m sure that many times I would give up. Definitely my progress would be less effective.

And still: I’ve set not so challenging amount of daily time: only 1.5 hours! Of course i can work e.g 4.5 hours on Sunday and have more flexible week. It has to be mentioned, that Rescuetime is quite accurate… probably very accurate. It’s not enough to be focused on a specific program. Client checks if You’re typing something or moving mouse. Sometimes a 5 minute break is taken, sometimes we have to stop and think… Both services know no mercy! Only active time is recorded, so sometimes extra 20-30% time with writing is needed to meet goal’s requirements.

“BEEhave yourself!”

If it’s about contest, I’m also using Beeminder to track how many posts I’ve written. Goal: two posts a week. It’s a good way to be sure, that at least this amount is released.

In bee end…

I realize that the part with money loss could be the only part which makes You to not even take Beeminder into consideration. And it’s understandable. The thing which service’s authors are describing as ‘interesting’ (watch the Nice Lady’s introduction video on a website) is probably the thing which could scare the most. As I’ve mentioned: it’s working for me, I’m always pledging the lowest 5$, but it’s not the main reason, why I’m using this service. It’s just a good piece of software with a handy reminder and accurate measurement tool which can be integrated with other services.

Rescuetime. To the rescue.


I would like to share some informations about one of the tools I’m using to keep the track of my progress on my ‘Run Pigs Run’ project.

As an introdcution: I think that this description of some ‘productive’ evenings can sound very familiar to many of us.

The story.

You’re reserving the whole evening to work on something. On Your hobby project (‘Dajsiepoznac’ project, maybe?), on Your homework etc. You’ve already refused Your friends to go out, because ‘sorry, I’ve got work to do’. And You start. Editor started, music playlist chosen, coffee ready… You’re really pumped up, this will be a productive evening. Start. It’s going pretty well, until the first problems occur. You’re suddenly not so very enthusiastic and it’s not a nice feeling: it appears that You have to do some extra work to push Your progress further. Maybe extra research is needed, maybe using new programming tool requires to read some documentation, maybe a bug appeared and You even have no idea how to start to fix it. So to forget about all that, You’re switching quickly to Youtube/FB/whatever to ease the stress. After 15 minutes You’re coming back. Working 5 minutes to make some progress… good, You’re feeling better. Maybe a little reward: switching back to entertaining article/video. Back to work. And so on.

Maybe I’ve described this in a bizarre way, but this is how it looked a lot of times in my case. Nowadays I’m more aware, but still similar situations happen. I had always asked myself: how much of this evening was really productive? And many times I was terrified, realizing that probably If I was more focused and more willing to sweat, I would do the same work in about 2 hours. Of course I’m generalizing, but I gained a real enlightenment on how much sugar is in sugar, when I started o use Rescuetime.

The solution.

I don’t think You’ll find a better tool to measure Your productivity. Rescuetime gathers information about which program is currently active and measures time You’ve spend on it. Using RT for a half a year now, I can say it’s a quite accurate tool. Programs and websites are categorized into ‘Very Productive’, ‘Productive’, ‘Neutral’, ‘Distracting’ and ‘Very Distracting’.

In the end of the day You can see (in a form of nice graphs) on what really You’ve spend your time. And it can be quite surprising, when reality appears to be different than what we sometimes define as a ‘productive day’.


Rescuetime provides also ‘Focus Mode’, which will block any distracting websites in Your browser for some period of time. Popup is displayed, when focus time is over. So You can browse documentation, read tutorials and so on, but e.g social networking sites will be blocked. Omitting this function, ‘Focus Mode’ is just a time measuring tool. But this is a key to a real productivity: just turn on the clock with an attitude ‘I’m really focusing right now’. It can be surprising how much can be done in just 30 minutes of uninterrupted work. It’s a good idea to organize programming session in this way: 30-40 minutes of hard work, break, repeat. And when the popup ‘Focus Session is over’ appears… it’s a really nice feeling. And sometimes focus session is going so well, that we will naturally want to extend it.

Make goals (the best part)

Rescuetime allows to create goals, e.g ‘X hours a day on activities in category Y’. If You want to measure Your time spent on a software development, create category ‘Software Development’ and customize list of programs/websites which are falling into this category. For my current project things in ‘Software Development’ category are: ‘Sublime’, ‘Tiled’, ‘Umlet’, ‘’, ‘Emacs’ (for taking notes).


And now You can honestly tell Yourself: ‘I’ve spent X hours on a software development’.

written in Emacs with org2blog mode

Dajsiepoznac: about the project.


The reason

I’ve started ‘RunPigsRun’ (probably temporary title) about two months ago, I’m developing it quite regularly. But: a lot work ahead.

Project is written in Javascript, the language I’m still learning (I’ve learnt the basics from here I’m using the Phaser framework. I’ve finished one project in this framework, it’s available here:

My aim is to:

  • write a not so complicated game
  • it has to be entertaining
  • it has to look nice (I’ll have i big help at this point)
  • it has to be finished entirely

The rules

The gameplay will take place on the levels composed from tiles (10×10). Level is occupied by pigs, wolves, roads, obstacles, traps and other objects. Player can start the game and observe its course. Pigs start to run (hence the game’s title: clever, eh??), wolves start to chase them and so on. Without the intervention, pigs end their existence by drowning/ being caught by wolves/and maybe by other, more spectacular ways. The player’s task is to use available tools and rescue all the pigs by helping them leaving the level. E.g. pigs are running into the water: put a trampoline to make them jump over. Or put a signpost, which will direct pink heroes on the safe path.

Current progress:


I know it does not look appealing, and I don’t care. It’s meaningless to focus on that in the beginning. Gameplay has to be programmed in the first place. Special effects, graphics and other biscuit in the end. I’m using free tilesets downloaded from here.

The style and inspiration

If it’s about the plot… has anyone played ‘Pooyan’? It’s a NES game about shooting wolves falling down holding balloons. It had a marvelous animation with wolf chased by pigs with drums and.. (maybe just check it out Anyway: it’s only about the general atmosphere of the gameplay and the never ending, world wide conflict between pigs and wolves.


If it’s about the more important part – the mechanics – maybe someone played ‘The Incredible Machine’ ( Well, I haven’t. But: I’ve seen my friend playing, when I was something like 9 years old and I still remember the idea. Customize the level with available tools, start game and wait, if configuration, which You’ve chosen, will do the trick.


written in Emacs with org2blog mode

Hello Dajsiepoznac.


Recently I’ve sent my project “Run Pigs Run” as an entry for polish “Daj Się Poznać” (“Get Yourself To Know”) contest, organized by Maciek Aniserowicz. It has already over 200 registered projects. Long story short: as a participator I have to:

  • work regularly on my project for about three months, counting from the beginning of march
  • write at least two posts weekly about progress/thoughts/programming quirks connected with my work on a project

I’m very thrilled about the idea, hope to stick to the plan.

written in Emacs with org2blog mode

Hello reference.

Switching daily from C++ (day work) to JS (hobby project) results in happily careless programming. I’m so thrilled with duck typing, that in some functions it’s seems to be obvious, that passed object argument is a reference and yet, when I’m writing function using a reference only to check something, sometimes I’m forgetting that I’m performing an operation on a “living being”:

TilesManager.prototype.getAdjacent = function(gamePos, direction) {
	switch (direction) {
		case MovementDirections.U:
		case MovementDirections.R:
		case MovementDirections.D:
		case MovementDirections.L:
	return this.get(gamePos[0], gamePos[1]);

gamePos modified outside. A moment ago function was receiving two numbers (not objects) posX, posY and everything was a-ok (pass by value).

Ok, “let’s make gamePos uppercase (ergo suggest DON’T F TOUCH THIS), make a copy at the beginning and use it instead:

TilesManager.prototype.getAdjacent = function(GAME_POS, direction) {
	gamePos = GAME_POS;
	switch (direction) {
		case MovementDirections.U:

No. Still having a reference: the gamePos IS the GAME_POS. So let’s make a copy. Stackoverflow to the rescue.

As a js beginner I’m surprised: there is no ‘proper’ way to clone objects. Conclusion from the Stack (I’ve packed solution into a function):

function cloneProperties(TO_CLONE) {
	return JSON.parse(JSON.stringify(TO_CLONE));

TilesManager.prototype.getAdjacent = function(GAME_POS, direction) {
	gamePos = cloneProperties(GAME_POS);

Only properties copied, no functions. Will do. Phew. Valuable lesson.