How to win the game 2048

Here is the strategy I used to beat the popular 2048 game. It is not a guaranteed win, but I have achieved multiple scores over 10’000 points and won two times.

Tile Movement

It is very important to never use all 4 directions in one game. Choose 3 directions and only use these. I always go for left, up and right, meaning I never press down.

Priorities

Most guides will tell you to choose a corner and try to hold your biggest tile there. This will most likely fail, so try to always keep the biggest tiles on top of your board. After around 5000 points you should avoid having a 2 or 4 in your top two rows, because you just can’t combine them with a 128 (or a bigger tile of course) any time soon.

End

As soon as you have a 1024 and two 512 tiles everything I said above becomes irrelevant and you should try to combine those to a 2048, therefore winning the game.

Now there is an algorithm that has a 90% win rate, programmed by the creator of 2048, Gabriele Cirulli. You can check out the 2048 AI here and a Stackoverflow question regarding this issue here.

What are anonymous self-invoking functions in JavaScript?

Have you ever been confused by something like this?

(function() { 
    console.log('hello world');
})();

This function invokes itself after it has been declared, meaning it calls itself right after you have declared it. All we are doing is wrapping the function into parentheses and then call it like you would call any function with (). Think of it this way:

(function)();

Some people use .call() (which does exactly the same), because the other syntax can be confusing for people who have just started with JavaScript:

(function).call();

To finish this post off, let us have a look at a real world example of an anonymous, self-invoking function:

var list = (function() {
    // declare variables that cannot be used outside of the function scope
    var x = 10;
    var y = 20;

    return [x, y];
})();

// correctly logs [10, 20]
console.log(list);

// throws a reference error
console.log(x);

for-Loop with Delay in JavaScript

I had multiple JavaScript beginners come to me and ask me this question:
How can I create a for-loop with x ms delay in between?

This code is what most have come up with (for quick readers: not what you are looking for!):

for (var index = 1; index <= 50; index++) {
    setTimeout(function() {
        console.log(index);
    }, 100);    
}

Now this prints "50" fifty times, because a for-loop is synchronous while setTimout is asynchronous. This means that the for-loop is finished very fast and has startet 50 setTimeouts. After 100ms all of those setTimeout functions will fire together, therefore printing "50" fifty times. Note that the var-keyword binds variables to the function scope, not the current block scope like in other languages.

In order to create a for-loop with actual delay - in our case printing a number, waiting 100ms and printing the next number - you need to create a self-invoking, recursive function. Don't worry, it's not that hard.

var maxLoops = 50;
var counter = 0;

(function next() {
    if (counter++ >= maxLoops) return;

    setTimeout(function() {
        console.log(counter);
        next();
    }, 100);
})();

Here we declare two variables, maxLoops and counter. These are for keeping track of how many times the function has called itself. Afterwards we create the function "next", put it in brackets and call it immediately. This is why it's called a self-invoking function.

The if-statement does two things. First of all it counts up our counter variable using the ++ operator. It also returns the function if it has been called 50 times, therefore stopping the loop.

The last part is the most important. We create our setTimeout function and then call next() after the number has been printed. And that's how you create a for-loop with delay in JavaScript.

Here is an even shorter, but harder to understand solution:

(function next(counter, maxLoops) {
    // break if maxLoops has been reached
    if (counter++ >= maxLoops) return;

    setTimeout(function() {
        console.log(counter);

        // call next() recursively
        next(counter, maxLoops);
    }, 100);
})(0, 50);

Simple Registry Pattern Implementation in JavaScript

Have you ever had to deal with something like this?

switch (input) {
    case '200':
        correspondingEvent = 'success';
        break;
    case '404':
        correspondingEvent = 'error';
        break;
    case '500':
        correspondingEvent = 'error';
        break;     
    // etc...
}

A huge switch statement that you cannot dynamically change. There is a design pattern called Registry Pattern for exactly this case. It is basically an object/array which maps different conditions.

Here is a JavaScript implementation of said pattern:

var registry = {
    '200': 'success',
    '404': 'error',
    '500': 'error',
    '403': 'error',
};

var input = '200', correspondingEvent;

if (input in registry) {
    correspondingEvent = registry[input];   
} else {
    // handle invalid input   
}

Adding or removing new cases is very easy:

registry['401'] = 'error';
delete registry['401'];

I would like to thank Christian Strotz for opening my eyes on this one, since I originally used an array instead of an object. (like in most other programming languages).

My Sublime Text 2 Configuration

Here is my Sublime Text 2 configuration file. Install these packages before applying it:

  • Github Color Theme
  • Theme – Centurion
{
  "bold_folder_labels": true,
  "color_scheme": "Packages/Github Color Theme/GitHub.tmTheme",
  "drag_text": false,
  "folder_exclude_patterns": [
    ".svn",
    ".git",
    ".hg",
    "CVS",
    ".sass-cache"
  ],
  "font_size": 10,
  "highlight_line": true,
  "line_padding_bottom": 2,
  "line_padding_top": 2,  
  "show_tab_close_buttons": false,
  "tab_size": 2,
  "theme": "Centurion.sublime-theme",
  "translate_tabs_to_spaces": true,
  "use_tab_stops": true,
  "word_wrap": true
}

Screenshot of the editor (looks very similar on OS X)

dark theme

Smallest JavaScript FizzBuzz solution possible?

Maybe you have seen this kind of viral picture about a guy who gets asked to program FizzBuzz in a job interview.

My friend and I tried to make the smallest possible JavaScript FizzBuzz solution possible. Here were our requirements:

  • Print numbers from 1 to 100
  • If a number is dividable by 3, print “Fizz” instead
  • If a number is dividable by 5, print “Buzz” instead
  • If a number is dividable by 3 and 5, print “FizzBuzz” instead
  • Print using console.log
  • Pure JavaScript only

First Try (101 characters)

for(n=1;n<=100;++n){s="";if(!(n%3))s="Fizz";if(!(n%5))s+="Buzz";else if(n%3&&n%5)s=n;console.log(s);}

Uses a simple if-else clause and appends the strings "Fizz" and "Buzz", so we don't need an extra "FizzBuzz" in our code.

Second Try (69 characters)

for(n=1;n<101;++n)console.log(((n%3)?'':'Fizz')+((n%5)?'':'Buzz')||n)

30 characters shorter! This uses some neat tricks in JavaScript. console.log logs the return value of a || operator. The || operator evaluates the left -and right-handed side of it and returns the first true value. An empty string is considered false in JavaScript, therefore it would print the number if the number is not dividable.

Third Try (64 characters)

for(n=0;++n<101;)console.log((n%3?'':'Fizz')+(n%5?'':'Buzz')||n)

Have a look at the for-loop on this one. Using the pre-increment operator ++ we don't need the last argument in our for-loop. We were also able to remove the parentheses in the ternary statements.

Can you make it even shorter? Reply down below!

Emulate Interfaces in JavaScript with interface.js

Interfaces are something you don’t actually need in a loosely typed language like JavaScript, but sometimes it’s nice to make sure that some methods really exist. This is where interface-js comes in handy. You can create new interfaces like this:

var IAnimal = new Interface([ 'roar', 'sleep' ]);

When you are creating your class, you can use it like this:

var Tiger = function() {

  // Implement the interface 'IAnimal'
  IAnimal.implement(this);
};

Tiger.prototype.roar = function() {
  console.log('ROARRR');  
};

‘Tiger’ does not implement the method ‘sleep’, so it throws an error:

InterfaceException: Missing the following method: 'sleep'

The source code for interface-js is available on GitHub. Pull requests are welcome!

Real JavaScript Enums with enum.js

I stayed at home yesterday and had nothing to do, so I tried to implement enums in pure JavaScript. It worked quite well as you can see on my GitHub profile.

Let’s get straight to the point:

var Days = new Enum([ 'Monday', 'Tuesday', 'Wednesday' ]); // to be continued

Usage:

var inputDay = Days.Monday;
return (inputDay === Days.Monday) // returns true

It provides a useful .toString() method:

console.log( Days.Monday.toString() ); // logs 'Monday'

It is also protected against overwriting by using Object.freeze. If you don’t want to freeze it, you can pass it as an option when you’re creating the enum:

var Days = new Enum([ 'Monday', 'Tuesday', 'Wednesday' ], { finalize: false });

enum.js is very small and has no dependencies. Grab the source code from the GitHub repo and start creating JavaScript enums today!

Understanding Backbone View Events

When you are using Backbone, you’ve surely heard of the useful DOM-bound events provided by Backbone.View. Here is an example of such an event:

var someView = Backbone.View.extend({

  el: 'section#content',

  events: {
    'click button#save':    'saveSomething'
  },

  saveSomething: function(event) {
    // do work
  }

});

These events work only if you’ve provided the ‘el’ attribute. It represents the current context of your view. Events also require jQuery, since it uses its $.on() method to bind events to the DOM.

How it actually works

Backbone first parses your input string with this regular expression:

/^(\S+)\s*(.*)$/

It breaks the string into two parts; The event name and the selector. Example:

click button#save

--> eventName: 'click'
--> selector: 'button#save'

That’s basically it. Now it just calls jQuerys $.on() like this:

this.$el.on(eventName, selector, method);

…and your event is bound to the DOM. As you can see, events can only be bound to elements within the context of your view (‘el’ attribute). This approach allows you to use any event that jQuery provides.

Events are automatically bound after the ‘render’ method. If you need to call it by hand, you can use delegateEvents.

How to use Underscore.js Templates in your Application

Recently I’ve posted about Mustache.js, a logic-less templating engine in JavaScript. Now, if you need advanced templates with logic, you can use Underscore.js. If you are using Backbone.js, you have it included anyways.

Here’s some test data I’ve made for generating HTML with the _.template() method from Underscore.js:

var collection = [
    {
        name: 'Patrick',
        age: 19,
        lastMatches: [
            {
                champion: 'Jax',
                hasWon: true
            },
            {
                champion: 'Vayne',
                hasWon: true
            }
        ]
    },
    {
        name: 'Kha',
        age: 18,
        lastMatches: [
            {
                champion: 'Ezreal',
                hasWon: false
            },
            {
                champion: 'Lee Sin',
                hasWon: true
            }
        ]
    },
    {
        name: 'Abu',
        age: 17,
        lastMatches: [
            {
                champion: 'Elise',
                hasWon: true
            },
            {
                champion: 'Shaco',
                hasWon: false
            }
        ]
    }
];

Now here is the corresponding Underscore template that you could include in a templates.html file.

<script type="text/template" class="template">
     <p> <%= name %> </p>
     <ul>
         <% _.each(lastMatches, function(match) { %>
             <% var color = (match.hasWon) ? 'green' : 'red'; %>
             <li class="<%= color %>"> <%= match.champion %> </li> 
         <% }); %>
     </ul>
</script>

By using these ERB-style delimiters <% %>, you can have JavaScript code in your template. Printing out a single variable is really easy:

<%= color %>

Finally, all we have to do is combining those pieces of code:

var compileHTML = _.template(jQuery("script.template").html())

_.each(collection, function(entity) {
   this.$el.append(compileHTML(entity)); 
});

See? Dead easy. Since we are using this template more than once, I’ve compiled it into the variable ‘compileHTML’. This speeds everything up. If you need to know something else, have a look at the documentation of Underscore.js.