Collisions trouble.


About lately occurred collision problems.

At first I was satisfied with a first solution for collisions resolving: checking collisions after one movement iteration. What is a movement iteration: a constant time during which objects change their position, normally by moving to the next tile. If an object has a different speed, than it moves at that time a different number of tiles. This ‘movement iteration’ concept gives me more control about game flow: one movement iteration, one positions change for every object.

But lately more situations started coming up. So here are those situations with collisions check implementation explanation.


First situation shows a variant which was mistakenly assumed to be the only one. Both objects end their movement on one tile. Both are reported to CollisionHandler:

var GAME_POS =;
prepareArray(this.tilesToHandle, GAME_POS.x,
var ARR = this.tilesToHandle[GAME_POS.x][GAME_POS.y];
var TILE = this.tilesManager.get(GAME_POS.x, GAME_POS.y);

And later every tile is used to make an every to every collision test.

Second situation shows that collisions can occur during movement iteration: when objects are passing each other during normal movement or when one object has bigger speed and passes other object during position change. This forced me to implement something I wanted to avoid: checking collisions on every update(). And this means to get all objects and check every vs every if there are no collisions.

var collObjects = this.gameObjectsManager.getAllWithout(
for (var i = 0; i < collObjects.length; i++)
        for (var j = i + 1; j < collObjects.length; j++) {
                this.onCollision, null, this);

After that, collected colliding pairs have to be merged in collision groups: one group represents objects which are colliding at the exact moment of time in the same spot. So in the end these groups can be passed to CollisionHandler and handled in the same way as collision between objects ending their movement on the same tile.

Third situation: when object is starting movement from the same position as the position of an another object. It’s not a collision, because collision between those objects was already handled. The difference between those objects positions is calculated: if it’s small enough, it means that during collision check, this collision will be ignored.

RunPigsRun: about the progress.


A little report on a progress.

I had some issues with collisions, as it turned out, I haven’t taken into account collisions between objects passing each other. Previously, collisions were only checked, when objects were ending their movement on a tile. It’s a game’s clock: one movement iteration (movement from one tile to another, also with a different speed).

When I have introduced Enemy objects (objects killing Heroes) it turned out, that there is no collision detection between objects passing each other… Collisions where checked when all objects finished their movement on a target tile. I’ve fixed that lately and now collisions events are distinguished on:

  • those fired, whenever collision between objects occur
  • and on those fired, when both objects end their movement on the same tile.

Maybe next time I’ll explain the reason behind this concept.

I have made code easier by introducing ‘void’ type fields, to check collisions for objects which bounces off outside the road. In this way empty fields are also participating in collision tests.

The next thing is choosing tools by a player. The set of available tools is limited and separate for every level (a different set for each level). When player exceeds the limit, the first chosen tool is erased to make room for a new choice. It allows to change decision with a minimum clicking.

Also tools have different modes: e.g. Signpost tool (which changes Hero’s direction) can be rotated. Player changes tool’s mode by choosing again the same field: tool’s next state is chosen and after choosing all the states, the tool is removed. In this way player by a single operation can either change tool’s mode or remove it. It’s an important concept, as more tools will have their modes too.

Clear conditions about lose/win introduced. Now whenever Hero dies (falls into the water/is killed by the enemy/bounces outside the road) the game is lost: black rectangle displayed and level is restarted. Player wins when all the heroes finish their movement on the Exit fields.

Thoughts flow. Inner monologue.


This post is related to Dajsiepoznac16 contest in the same way as every IT project/design process/task I was participating in. Whenever any process, which requires planning, is started, I open a text editor and start taking notes. I need this to organize thoughts, ideas, plans, concepts.

Storing ideas

For every project I have a separate file, where everything which comes to mind can be stored. I don’t believe in storing ideas in a head: memory can’t be trusted in this one. Besides: notes can be organized, tagged… and reviewed without a doubt, that something is missing. Notepad is a trusted place. Write down and forget. Your thoughts will remain here.

Head is not the best place to store ideas.

What has to be done?

If I start e.g. a new feature, I’m trying to answer a “what has to be done right now?” question. Every problem, no matter how big, can be divided into concrete steps. In this way, I’m not working on a project: I’m working on a concrete problem, which has clear ‘it’s done’ definition. And one more time: defining these clear steps, can be achieved, by writing down whatever related to solved problem comes to mind. By having the flow of thoughts about the project, the concrete steps emerge spontaneously.

The worst thing is to not know, what has to be done right NOW.

Written down…

It’s said, that to increase a probability of achieving something, it has to be written down. The same goes with planning: thoughts written down are concrete, can be reviewed, modified, updated, commented… they’re becoming more real. It’s almost like planning in a head has no advantage over taking notes. What more, freedom of letting thoughts flow, unblocks other thoughts. The process of one idea chasing the other idea can be sometimes surprising.

Writing things down, can be sometimes an only way to come up with some ideas.


Writing things down with pen and paper has this obvious downside, that it’s incredibly slow. It can be said, almost without a doubt, that taking notes on a keyboard, will be always more effective, as the speed of typing is almost as fast as the speed of thoughts.


I’m using Emacs with OrgMode, which allows to take notes arranged in nested headlines in a surprisingly easy and fast way. It can be seen, that notes are organized in headlines (every ellipsis means, that headline can be unfolded to reveal either more headlines or conrete notes). I think that any software, which allows to write and organize notes fast, will do the trick.

Finding Your ideas is important.

It’s all about the freedom of recording whatever comes to mind.

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