Monthly Archives: June 2015

Tail call optimization in ECMAScript 6

By Axel Rauschmayer

ECMAScript 6 offers tail call optimization, where you can make some function calls without growing the call stack. This blog post explains how that works and what benefits it brings.

What is tail call optimization?

To understand what tail call optimization (TCO) is, we will examine the following piece of code. I’ll first explain how it is executed without TCO and then with TCO.

    function id(x) {
        return x; // (A)
    }
    function f(a) {
        let b = a + 1;
        return id(b); // (B)
    }
    console.log(f(2)); // (C)

Normal execution

Let’s assume there is a JavaScript engine that manages function calls by storing local variables and return addresses on a stack. How would such an engine execute the code?

Step 1. Initially, there are only the global variables id and f on the stack.

The block of stack entries encodes the state (local variables, including parameters) of the current scope and is called a stack frame.

Step 2. In line C, f() is called: First, the location to return to is saved on the stack. Then f‘s parameters are allocated and execution jumps to its body. The stack now looks as follows.

There are now two frames on the stack: One for the global scope (bottom) and one for f() (top). f‘s stack frame includes the return address, line C.

Step 3. id() is called in line B. Again, a stack frame is created that contains the return address and id‘s parameter.

Step 4. In line A, the result x is returned. id‘s stack frame is removed and execution jumps to the return address, line B. (There are several ways in which returning a value could be handled. Two common solutions are to leave the result on a stack or to hand it over in a register. I ignore this part of execution here.)

The stack now looks as follows:

Step 5. In line B, the value that was returned by id is returned to f‘s caller. Again, the topmost stack frame is removed and execution jumps to the return address, line C.

Step 6. Line C receives the value 3 and logs it.

Tail call optimization

    function id(x) {
        return x; // (A)
    }
    function f(a) {
        let b = a + 1;
        return id(b); // (B)
    }
    console.log(f(2)); // (C)

If you look at the previous section then there is one step that is unnecessary – step 5. All that happens in line B is that the value returned by id() is passed on to line C. Ideally, id() could do that itself and the intermediate step could be skipped.

We can make this happen by implementing the function call in line B differently. Before the call happens, the stack looks as follows.

If we examine the call we see that it is the very last action in f(). Once id() is done, the only remaining action performed by f() is to pass id‘s result to f‘s caller. Therefore, f‘s variables are not needed, anymore and its stack frame can be removed before making the call. The return address given to id() is f‘s return address, line C. During the execution of id(), the stack looks like this:

Then id() returns the value 3. You could say that it returns that value for f(), because it transports it to f‘s caller, line C.

Let’s review: The function call in line B is a tail call. Such a call can be done with zero stack growth. To find out whether a function call is a tail call, we must check whether it is in a tail position (i.e., the last action in a function). How that is done is explained in the next section.

Checking whether a function call is in a tail position

We have just learned that tail calls are function calls that can be executed more efficiently. But what counts as a tail call?

First, the way in which you call a function does not matter. The following calls can all be optimized if they appear in a tail position:

  • Function call: func(···)
  • Dispatched method call: obj.method(···)
  • Direct method call via call(): func.call(···)
  • Direct method call via apply(): func.apply(···)

Tail calls in expressions

Arrow functions can have expressions as bodies. For tail call optimization, we therefore have to figure out where function calls are in tail positions in expressions. Only the following expressions can contain tail calls:

  • The conditional operator (? :)
  • The logical Or operator (||)
  • The logical And operator (&&)
  • The comma operator (,)

Let’s look at an example for each one of them.

The conditional operator (? :)
    const a = x => x ? f() : g();

Both f() and g() are in tail position.

The logical Or operator (||)
    const a = () => f() || g();

f() is not in a tail position, but g() is in a tail position. To see why, take a look at the following code, which is equivalent to the previous code:

    const a = () => {
        let fResult = f(); // not a tail call
        if (fResult) {
            return fResult;
        } else {
            return g(); // tail call
        }
    };

The result of the logical Or operator depends on the result of f(), which is why that function call is not in a tail position (the caller does something with it other than returning it). However, g() is in a tail position.

The logical And operator
    const a = () => f() && g();

f() is not in a tail position, but g() is in a tail position. To see why, take a look at the following code, which is equivalent to the previous code:

    const a = () => {
        let fResult = f(); // not a tail call
        if (!fResult) {
            return fResult;
        } else {
            return g(); // tail call
        }
    };

The result of the logical And operator depends on the result of f(), which is why that function call is not in a tail position (the caller does something with it other than returning it). However, g() is in a tail position.

The comma operator (,)
    const a = () => (f() , g());

f() is not in a tail position, but g() is in a tail position. To see why, take a look at the following code, which is equivalent to the previous code:

    const a = () => {
        f();
        return g();
    }

Tail calls in statements

For statements, the following rules apply.

Only these compound statements can have tail calls:

  • if: in either the “then” clause or the “else” clause.
  • do-while, while, for, with: in their bodies.
  • switch: in its body.
  • try-catch: only in the catch clause. The try clause has the catch clause as a context that can’t be optimized away.
  • try-finally, try-catch-finally: only in the finally clause, which is a context of the other clauses that can’t be optimized away.

Of all the atomic (non-compound) statements, only return can contain a tail call. All other statements have context that can’t be optimized away. The following statement contains a tail call if expr contains a tail call.

    return "expr»;

Tail call optimization can only be made in strict mode

In non-strict mode, most engines have the following two properties that allow you to examine the call stack:

  • func.arguments: contains the arguments of the most recent invocation of func.
  • func.caller: refers to the function that most recently called func.

With tail call optimization, these properties don’t work, because the information that they rely on may have been removed. Therefore, strict mode forbids these properties (as described in the language specification) and tail call optimization only works in strict mode.

Pitfall: solo function calls are never in tail position

The function call bar() in the following code is not in tail position:

    function foo() {
        bar(); // this is not a tail call in JS
    }

The reason is that the last action of foo() is not the function call bar(), it is (implicitly) returning undefined. In other words, foo() behaves like this:

    function foo() {
        bar();
        return undefined;
    }

Callers can rely on foo() always returning undefined. If bar() were to return a result for foo(), due to tail call optimization, then that would change foo‘s behavior.

Therefore, if we want bar() to be a tail call, we have to change foo() as follows.

    function foo() {
        return bar(); // tail call
    }

Tail-recursive functions

A function is tail-recursive if the main recursive calls it makes are in tail positions.

For example, the following function is not tail recursive, because the main recursive call in line A is not in a tail position:

    function factorial(x) {
        if (x <= 0) {
            return 1;
        } else {
            return x * factorial(x-1); // (A)
        }
    }

factorial() can be implemented via a tail-recursive helper function facRec(). The main recursive call in line A is in a tail position.

    function factorial(n) {
        return facRec(n, 1);
    }
    function facRec(x, acc) {
        if (x <= 1) {
            return acc;
        } else {
            return facRec(x-1, i*acc); // (A)
        }
    }

That is, some non-tail-recursive functions can be transformed into tail-recursive functions.

Tail-recursive loops

Tail call optimization makes it possible to implement loops via recursion without growing the stack. The following are two examples.

forEach()
    function forEach(arr, callback, start = 0) {
        if (0 <= start && start < arr.length) {
            callback(arr[start], start, arr);
            return forEach(arr, callback, start+1); // tail call
        }
    }
    forEach(['a', 'b'], (elem, i) => console.log(`${i}. ${elem}`));
    
    // Output:
    // 0. a
    // 1. b
findIndex()
    function findIndex(arr, predicate, start = 0) {
        if (0 <= start && start < arr.length) {
            if (predicate(arr[start])) {
                return start;
            }
            return findIndex(arr, predicate, start+1); // tail call
        }
    }
    findIndex(['a', 'b'], x => x === 'b'); // 1

Source:: 2ality

35 Handy Chrome Extensions And Apps For Developers

By Danny Markov

Main

In this post we present to you a list of 35 handy extensions and apps for Chrome that are must have for web developers and designers. They serve a variety of purposes, from testing HTTP requests, to making cool looking screenshots. Check them out!

Design Tools

1. Image Tool

Imagetool is a chrome app that helps you easily read and understand design specs. It allows you to inspect images and interpret them by using one of a number of tools. A great helper for turning designs into HTML.

Image Tool

2. CSS-Shack

This is a powerful Chrome app in which you can create designs and then export them into a CSS file. It can be used for experimentation or for creating and maintaining a style guide for a web site. It supports layers and design tools like the ones you usually find in professional image editing software.

CSS-Shack

CSS-Shack

3. Marmoset

Marmoset is a unique app that receives code and outputs superb snapshots for demos and mock ups. It also has cool themes and effects for you to play around with. It is perfect for intro images and illustrations for articles and blog posts.

Marmoset

Marmoset

4. WhatFont

A quick way to look up what fonts are used in a page by simply hovering over the text element. It also detects the services used for serving the web fonts. Supports Typekit and Google Font API.

WhatFont

WhatFont

5. Window Resizer

A great tool for building responsive designs that resizes your browser’s window. Choose from a list of popular devices or add custom ones for quick access to a certain resolution.

Window Resize

Window Resizer

6. ColorZilla

A compilation of color tools that enable you to pick colors, generate gradients and more, all in your browser.

ColorZilla

ColorZilla

7. Page Ruler

A tool for precise measuring of the elements on any web page. You can select a region or input the dimensions of the selected area manually. You can change the color of the selected area.

Page Ruler

Page Ruler

8. Pallette

This extension allows you to take any image in your browser and see what colors its made out of.

Pallette

Pallette

9. PerfectPixel

PerfectPixel puts a semi-transparent image overlay over the top of the developed HTML, enabling users to perform per pixel comparison between the two.

PerfectPixel

PerfectPixel

Development Tools

10. Chrome MySQL Admin

A MySQL client with everything you need to manage your MySQL databases and tables. You can connect to and administer databases, run queries and browse result sets in a fast and snappy interface.

Chrome MySQL Admin

Chrome MySQL Admin

11. JSON Formatter

Takes a JSON and displays it in an easy to read, nicely aligned format. You can collapse parts of the JSON and follow URLs.

JSON Formatter

JSON Formatter

12. Web Developer

This is a must have extension for every web developer. By clicking this extension’s badge button you gain access to a huge number of power tools. An amazingly powerful ally to all developers and designers.

Web Developer

Web Developer

13. Grunt Devtools

Extends Chrome’s Developer Tools by adding the option to run all kinds of Grunt tasks.

Grunt Devtools

Grunt Devtools

14. PHP Console

Adds PHP support to the DevTools console so that you can handle errors, execute PHP scripts and more. Requires a server side PHP library.

PHP Console

PHP Console

15. Python

Python interactive interpreter for Chrome. Perfect for testing out code snippets in a Python console. This extension is the full version of python 2.7 compiled using native client.

Python

Python

16. Form Filler

Fills all form inputs in a page with dummy data. This is a handy tool to have when testing form validation and backend scripts. You can configure the test data that this extension generates.

Form Filler

Form Filler

Code Editors

17. Caret

An open source text and code editor similar to Sublime Text. It’s packed with all kinds of features that you’d normally find in a native development environment – a big list of supported languages, code completion, multiple cursors, etc. It is great for working on a Chromebook.

Caret

Caret

18. Text

This app is a compact text editor with a beautiful, clean design and no distracting features. It supports syntax highlighting and can save directly to Google Drive.

Text

Text

19. Nitrous Lite

A free, cloud based service which creates a fully functioning development environment in your browser. It offers a built-in code editor, a Linux terminal and the option to collaborate with other developers in real time.

Nitrous Lite

Nitrous Lite

20. Chrome Dev Editor

A code editor that runs in your browser, made by Google. Its original purpose is for building Chrome Apps, but it can be used for general web development. It supports JavaScript syntax highlighting, Polymer templates and version control integration with Git, Bower and Pub.

Chrome Dev Editor

Chrome Dev Editor

Network Tools

21. Postman

An advanced tool for monitoring and improving API workflow. Build and document your requests, switch context easily and test everything to foolproof your APIs.

Postman

Postman

22. DHC – REST/HTTP API Client

An app that allows users to send, receive and manipulate HTTP/REST requests and responses. It has a lot of built-in features like history, a local repository to save requests in, and so on. It is simpler than Postman and is great for a quick network request.

DHC - REST/HTTP API Client

DHC – REST/HTTP API Client

23. Cookies

An easy-to-use Cookie Editor that helps you manage all cookies stored in your browser or bake new ones.

Cookies

Cookies

24. AJAX Debugger

Logs all AJAX activity to the Dev Tools Console, allowing inspection of their HTTP status, size and response time

AJAX Debugger

AJAX Debugger

Utilities

25. Cog – System Info Viewer

An app that shows basic information about your computer’s hardware and software in a clean and beautiful interface. You can check your cpu and memory usage, processor type and OS.

Cog

Cog

26. Session Buddy

A great extension for power users. If you frequently have 20 open tabs or more, give this one a try. You can save tabs, organize them and recover sessions after a browser crash. You can easily export sessions as text or json and import them.

Session Buddy

Session Buddy

27. Lucidchart Diagrams

A nice tool for building flowcharts and other diagrams. It doesn’t require an internet connection and can export your charts to PDF, PNG, and JPG. You can use it to augment your presentations, documents and homework assignments.

Lucidchart Diagrams

Lucidchart Diagrams

28. Hasher

Hasher computes cryptographic hashes such as MD5 and SHA-1. It’s entirely implemented in JavaScript and all calculations are performed on the client side.

Hasher

Hasher

29. The Great Suspender

Another one for your tabs. It automatically suspends unused tabs to save on system memory. If you need the tab later, simply focus it and refresh. A great tool for memory constrained systems.

The Great Suspender

The Great Suspender

30. Alchemize

A well made app that can minify or beautify code. It works offline, has a simple drag and drop interface and supports a range of XML, HTML, CSS, JavaScript and JSON formats.

Alchemize

Alchemize

31. Secure Shell

An xterm-compatible terminal emulator in Chrome. Can be used as a stand-alone SSH client and works in the browser and in Chrome books.

Secure Shell

Secure Shell

32. Appspector

When this extension is enabled, an icon will appear on the address bar, indicating all web frameworks running on the current website.

Appspector

Appspector

33. Check My Links

The extension crawls through your webpage and checks for broken links.

Check My Links

Check My Links

Fun

34. Floating YouTube

A resizable YouTube player, which can be pinned on top of all other windows. This is perfect for chronic procrastinators and music lovers.

Floating YouTube

Floating YouTube

35. Bacon Ipsum

A tastier version of Latin. The “Give me bacon” button doesn’t give you any actual bacon which is really disappointing.

Bacon Ipsum

Bacon Ipsum

Source:: Tutorialzine.com

WebAssembly: a binary format for the web

By Axel Rauschmayer

WebAssembly (short: wasm) is a new binary format for the web, created by Google, Microsoft, Mozilla and others. It will be used for performance critical code and to compile other languages (especially C/C++) to the web platform. It can be seen as a next step for asm.js [2].

asm.js

Most JavaScript engines have the following compilation pipeline:

JavaScript source → bytecode → machine code

The idea of asm.js is to code JavaScript in such a way that engines produce machine code that is as efficient as possible. That is, you kind of try to bypass the first compilation step. The results are impressive: if one compiles C++ to asm.js one can reach 70% of native speed in web browsers.

WebAssembly: the next step for asm.js

Initially, WebAssembly is (roughly) a binary format for delivering asm.js code. The two main advantages of such a format are:

  • Faster loading. Especially with large code bases and mobile devices, parsing becomes a bottleneck: “On mobile, large compiled codes can easily take 20–40s just to parse” (WebAssembly FAQ). First experiments show that WebAssembly can be loaded more than 20 times faster, because the work for parsing is minimal.

  • Evolving WebAssembly is simpler: The way that asm.js is currently written is constrained by having to run fast as normal JavaScript (in legacy engines) and by having to support ahead of time compilation within JavaScript syntax.

Legacy engines will be supported via a JavaScript library that translates WebAssembly (binary) to asm.js (source code). First indications are that that is reasonably fast.

WebAssembly does not replace JavaScript

The previous diagram (which is a much simplified depiction of reality) should make it obvious that WebAssembly is not a replacement for JavaScript, it is a new feature of JavaScript engines that builds on their infrastructures. That means that it will fit well into the web platform:

  • It will have the same evolution strategy as JavaScript: everything is always backward-compatible, there is no explicit versioning, code uses feature testing to determine how it should run.
  • It will execute in the same semantic universe as JavaScript and allow synchronous calls to and from JavaScript (including browser APIs).
  • Security will be handled like in JavaScript, via same-origin and permissions security policies.

The nice thing is that WebAssembly removes the burden from JavaScript to be a good compilation target for other languages. For example, the following two methods were only added to ES6 to support asm.js well:

  • Math.fround(x) rounds x to a 32 bit float.
  • Math.imul(x,y) multiplies the two integers x and y.

The big picture

  • Performance critical functionality (games, video and image decoders, etc.) will be implemented via WebAssembly, either by hand-coding it or by yet-to-be-invented languages that are slightly higher-level.

  • External code bases, especially those in C/C++, will be easy to port to the web platform, via WebAssembly.

  • Other than that, JavaScript will continue to evolve and will probably remain a popular way of implementing web apps.

The future

The initial focus is for WebAssembly to be a compilation target for C/C++. Longer term, more features supporting other languages will be added, including the ability to create garbage-collected data (currently, asm.js creates and manages its own heap).

What is different this time?

Why should WebAssembly succeed where previous attempts (such as Adobe Flash and Google Portable Native Client) have failed? There are three reasons:

  • First, this is a collaborative effort, no single company goes it alone. At the moment, the following projects are involved: Firefox, Chromium, Edge and WebKit.

  • Second, the interoperability with the web platform and JavaScript is excellent. Using WebAssembly code from JavaScript will be as simple as importing a module.

  • Third, this is not about replacing JavaScript engines, it is more about adding a new feature to them. That greatly reduces the amount of work to implement WebAssembly and should help with getting the support of the web development community.

A few more interesting tidbits

  • You’ll eventually be able to debug a WebAssembly binary via the source code that was compiled to it. That mechanism will be an evolution of source maps [3] that provide similar services for JavaScript.

  • WebAssembly binaries will encode abstract syntax trees. That is, they are not a linear format like stack- or register-based bytecode. Not surprisingly, the format looks much like asm.js: roughly, a statically typed version of JavaScript without objects.

  • There will be a text format for WebAssembly. It will mirror the semantics of the binaries and contain a tree of statements and expressions.

Further reading

  1. WebAssembly” by Luke Wagner
  2. asm.js: closing the gap between JavaScript and native
  3. Introduction to JavaScript Source Maps” by Ryan Seddon on HTML5 Rocks

Source:: 2ality

Making Your First HTML5 Game With Phaser

By Danny Markov

html5-game-phaser

Everybody loves classic games. How many of you remember the retro snake game from old Nokia phones? We sure do. This is why for this lesson we decided to recreate it using HTML5. There is a great open source game development framework called Phaser that we will use.

You will learn about sprites, game states and how to use the preload, create and update methods. Here’s what the final version of the game we’re building looks like:

Setup

Download a zip archive with the file structure of the game here. It contains all the image assets needed for the game but no code. We will be writing this next.

Now open index.html, add a title for your page and create links to all the JS files. Later, to play the game, just open this file in your browser.

<!doctype html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Snake</title>
    <script src="assets/js/phaser.min.js"></script>
    <script src="assets/js/menu.js"></script>
    <script src="assets/js/game.js"></script>
    <script src="assets/js/game_over.js"></script>
    <script src="assets/js/main.js"></script>
</head>
<body>

</body>
</html>

Your directory should look like this:

Directory Tree

Directory Tree

How the game is organized

Phaser games are organized around states. Think of states in Phaser as the different parts of a game. Here are the states of our game:

  • The Menu state. It is handled by menu.js, and only displays the start image. When it is clicked, the game transitions to the Game state.
  • Game state. It is handled by game.js. This is the actual play area of the game. You control the snake, eat apples and have lots of fun. When you die, you transition to the Game_Over state.
  • Game_Over state. It shows gameover.png and displays your last score. When it is clicked you transition to the Game state.

main.js is our main JavaScript file. This is the place where we will create a new game instance and add a menu state.

1. Loading an image

Right now, our game doesn’t do anything. Let’s code the Menu state, and make it display the title screen.

During the setup we included the Phaser library in our HTML file. This gives us a global object called Phaser. Through it, we can access the library’s methods and functions for building games.

Now we will use the global Phaser object, and create a new game instance. This is an object which represents our entire game. We will add the states to it.

main.js

var game;

// Create a new game instance 600px wide and 450px tall:
game = new Phaser.Game(600, 450, Phaser.AUTO, '');

// First parameter is how our state will be called.
// Second parameter is an object containing the needed methods for state functionality
game.state.add('Menu', Menu);

game.state.start('Menu');

Now we need to initialize our Menu state object. In menu.js define a new object and add the functions below. When the state is started, the preload function will be called first, loading all the needed assets for our game. Once preloading finishes, create gets called, initializing the playing field and everything we want on it:

menu.js

var Menu = {

    preload : function() {
        // Loading images is required so that later on we can create sprites based on the them.
        // The first argument is how our image will be refered to, 
        // the second one is the path to our file.
        game.load.image('menu', './assets/images/menu.png');
    },

    create: function () {
        // Add a sprite to your game, here the sprite will be the game's logo
        // Parameters are : X , Y , image name (see above) 
        this.add.sprite(0, 0, 'menu');
    }

};

Because of browser security restrictions, to start the game you’ll need a locally running web server. This page from the Phaser guidelines has plenty of options for all operating systems – here. In other words, it won’t work if you simply double click your index.html.

If everything has been done right, a page with the the start screen should appear in your browser.

Rendering an image

2. Drawing the snake

As we mentioned earlier, the Game state is where the actual game play happens. This is also the place where we will draw the snake. Like we did with the Menu state, we need to register the Game state with the global game object in main.js. Here is how your code should look like:

main.js

var game;

game = new Phaser.Game(600, 450, Phaser.AUTO, '');

game.state.add('Menu', Menu);

// Adding the Game state.
game.state.add('Game', Game);

game.state.start('Menu');

We’ll also want to add some code in menu.js to let us start the Game state when it is clicked. For this purpose, we will replace the sprite with a button. Adding a button is basically the same as adding a sprite, you only need to provide a function to be called when it is clicked. Here is the final menu.js code:

menu.js

var Menu = {

    preload : function() {
        // Load all the needed resources for the menu.
        game.load.image('menu', './assets/images/menu.png');
    },

    create: function () {

        // Add menu screen.
        // It will act as a button to start the game.
        this.add.button(0, 0, 'menu', this.startGame, this);

    },

    startGame: function () {

        // Change the state to the actual game.
        this.state.start('Game');

    }

};

We can now proceed with coding the Game state and drawing the snake. The structure is similar to the one of the Menu state.

game.js

var snake, apple, squareSize, score, speed,
    updateDelay, direction, new_direction,
    addNew, cursors;

var Game = {

    preload : function() {
        // Here we load all the needed resources for the level.
        // In our case, that's just two squares - one for the snake body and one for the apple.
        game.load.image('snake', './assets/images/snake.png');
        game.load.image('apple', './assets/images/apple.png');
    },

    create : function() {

        // By setting up global variables in the create function, we initialise them on game start.
        // We need them to be globally available so that the update function can alter them.

        snake = [];                     // This will work as a stack, containing the parts of our snake
        apple = {};                     // An object for the apple;
        squareSize = 15;                // The length of a side of the squares. Our image is 15x15 pixels.
        score = 0;                      // Game score.
        speed = 0;                      // Game speed.
        updateDelay = 0;                // A variable for control over update rates.
        direction = 'right';            // The direction of our snake.
        new_direction = null;           // A buffer to store the new direction into.
        addNew = false;                 // A variable used when an apple has been eaten.

        // Set up a Phaser controller for keyboard input.
        cursors = game.input.keyboard.createCursorKeys();

        game.stage.backgroundColor = '#061f27';

        // Generate the initial snake stack. Our snake will be 10 elements long.
        // Beginning at X=150 Y=150 and increasing the X on every iteration.
        for(var i = 0; i < 10; i++){
            snake[i] = game.add.sprite(150+i*squareSize, 150, 'snake');  // Parameters are (X coordinate, Y coordinate, image)
        }


        // Genereate the first apple.
        this.generateApple();


        // Add Text to top of game.
        textStyle_Key = { font: "bold 14px sans-serif", fill: "#46c0f9", align: "center" };
        textStyle_Value = { font: "bold 18px sans-serif", fill: "#fff", align: "center" };

        // Score.
        game.add.text(30, 20, "SCORE", textStyle_Key);
        scoreTextValue = game.add.text(90, 18, score.toString(), textStyle_Value);
        // Speed.
        game.add.text(500, 20, "SPEED", textStyle_Key);
        speedTextValue = game.add.text(558, 18, speed.toString(), textStyle_Value);

    },



    update: function() {
        // The update function is called constantly at a high rate (somewhere around 60fps),
        // updating the game field every time.
        // We are going to leave that one empty for now.
    },


    generateApple: function(){

        // Chose a random place on the grid.
        // X is between 0 and 585 (39*15)
        // Y is between 0 and 435 (29*15)

        var randomX = Math.floor(Math.random() * 40 ) * squareSize,
            randomY = Math.floor(Math.random() * 30 ) * squareSize;

        // Add a new apple.
        apple = game.add.sprite(randomX, randomY, 'apple');
    }

};

Here is how the snake and apple should look like:

Drawing the snake

3. Movement and control

To make the snake move we’ll be working in the update function of game.js.

First of all, we create event listeners for controlling the direction of the snake with the arrow keys.

The actual movement is a bit complex, since update is triggered at a very quick rate, and if we move the snake every time it’s called we would end up with one uncontrollably speedy reptile. To change this, we’ve set up an if statement that checks weather this is the 10th consecutive call of update() using a counter variable called updateDelay.

If it really is the 10th call, we remove the last square of our snake (first element in the stack), give it new coordinates according to the current direction and place it in front of the head of the snake (top of the stack). Here’s how the code looks like:

update: function() {

    // Handle arrow key presses, while not allowing illegal direction changes that will kill the player.

    if (cursors.right.isDown && direction!='left')
    {
        new_direction = 'right';
    }
    else if (cursors.left.isDown && direction!='right')
    {
        new_direction = 'left';
    }
    else if (cursors.up.isDown && direction!='down')
    {
        new_direction = 'up';
    }
    else if (cursors.down.isDown && direction!='up')
    {
        new_direction = 'down';
    }


    // Since the update function of Phaser has an update rate of around 60 FPS,
    // we need to slow that down make the game playable.

    // Increase a counter on every update call.
    updateDelay++;

    // Do game stuff only if the counter is aliquot to 10.
    if (updateDelay % 10 == 0) {


        // Snake movement

        var firstCell = snake[snake.length - 1],
            lastCell = snake.shift(),
            oldLastCellx = lastCell.x,
            oldLastCelly = lastCell.y;

        // If a new direction has been chosen from the keyboard, make it the direction of the snake now.
        if(new_direction){
            direction = new_direction;
            new_direction = null;
        }


        // Change the last cell's coordinates relative to the head of the snake, according to the direction.

        if(direction == 'right'){

            lastCell.x = firstCell.x + 15;
            lastCell.y = firstCell.y;
        }
        else if(direction == 'left'){
            lastCell.x = firstCell.x - 15;
            lastCell.y = firstCell.y;
        }
        else if(direction == 'up'){
            lastCell.x = firstCell.x;
            lastCell.y = firstCell.y - 15;
        }
        else if(direction == 'down'){
            lastCell.x = firstCell.x;
            lastCell.y = firstCell.y + 15;
        }


        // Place the last cell in the front of the stack.
        // Mark it the first cell.

        snake.push(lastCell);
        firstCell = lastCell;

    }
    
}

Try and control the snake via the arrow keys on your keyboard.

Movement and control

4. Collision detection

A game in which the snake is roaming freely in the playing field is not much fun. We need to detect when the snake comes in contact with a wall, an apple or itself. This is called collision detection.

This is usually done by using a physics engine, of which the Phaser framework supports a few. But they are too complex for a simple game like this. We will instead do our own collision detection by comparing coordinates.

In the update function, after the code for moving the snake, we call a number of methods. They will compare coordinates to tell us if a collision has occurred.

update: function() {

        // Snake movement
        // ...
        // End of snake movement

        // Increase length of snake if an apple had been eaten.
        // Create a block in the back of the snake with the old position of the previous last block
        // (it has moved now along with the rest of the snake).

        if(addNew){
            snake.unshift(game.add.sprite(oldLastCellx, oldLastCelly, 'snake'));
            addNew = false;
        }

        // Check for apple collision.
        this.appleCollision();

        // Check for collision with self. Parameter is the head of the snake.
        this.selfCollision(firstCell);

        // Check with collision with wall. Parameter is the head of the snake.
        this.wallCollision(firstCell);
    }


},

appleCollision: function() {

    // Check if any part of the snake is overlapping the apple.
    // This is needed if the apple spawns inside of the snake.
    for(var i = 0; i < snake.length; i++){
        if(snake[i].x == apple.x && snake[i].y == apple.y){

            // Next time the snake moves, a new block will be added to its length.
            addNew = true;

            // Destroy the old apple.
            apple.destroy();

            // Make a new one.
            this.generateApple();

            // Increase score.
            score++;

            // Refresh scoreboard.
            scoreTextValue.text = score.toString();

        }
    }

},

selfCollision: function(head) {

    // Check if the head of the snake overlaps with any part of the snake.
    for(var i = 0; i < snake.length - 1; i++){
        if(head.x == snake[i].x && head.y == snake[i].y){

            // If so, go to game over screen.
            game.state.start('Game_Over');
        }
    }

},

wallCollision: function(head) {

    // Check if the head of the snake is in the boundaries of the game field.

    if(head.x >= 600 || head.x < 0 || head.y >= 450 || head.y < 0){


        // If it's not in, we've hit a wall. Go to game over screen.
        game.state.start('Game_Over');
    }

}

When the snake collides with the apple we increase the score and the length of the snake. But when a collision with the wall or the snake body occurs, we should end the game. To do this, we need to make the Game_Over state. Again, we need to register it with main.js. Add this line near the bottom of that file:

main.js

game.state.add('Game_Over', Game_Over);

And the state itself:

game_over.js

var Game_Over = {

    preload : function() {
        // Load the needed image for this game screen.
        game.load.image('gameover', './assets/images/gameover.png');
    },

    create : function() {

        // Create button to start game like in Menu.
        this.add.button(0, 0, 'gameover', this.startGame, this);

        // Add text with information about the score from last game.
        game.add.text(235, 350, "LAST SCORE", { font: "bold 16px sans-serif", fill: "#46c0f9", align: "center"});
        game.add.text(350, 348, score.toString(), { font: "bold 20px sans-serif", fill: "#fff", align: "center" });

    },

    startGame: function () {

        // Change the state back to Game.
        this.state.start('Game');

    }

};

Collision detection

That’s it! Our game is ready!

Further reading

We hope that you liked our simple game and learned a lot while following our tutorial. There is much more to learn about Phaser:

Source:: Tutorialzine.com

Announcing “Exploring ES6”

By Axel Rauschmayer

I’m glad to announce that the first version of my book “Exploring ES6” is finally finished! It was much more work than I anticipated – the PDF has over 460 pages! I’m really happy with how it turned out.

The complete contents of the book are available online, for free. The ebook version (PDF, EPUB, MOBI) costs about $30 (depending on the VAT in your country, you can pay more to support my work).

“Exploring ES6” is a living book: you can buy it now and will receive free updates until it is completely done. That may take a while, possibly until 2016. Once the book is done, there will also be a print version. New material will often be published on 2ality, before it is added to the book.

For all further information on ”Exploring ES6”, please consult its website.

Source:: 2ality

12 Time-Saving Bootstrap Examples

By Danny Markov

bootstrap-examples

This week on Tutorialzine we’ve prepared for you a list of 15 examples of copy-paste-able code that you can use in your next Bootstrap powered project. We’ve tried to select practical resources that will save you from referencing Bootstrap’s docs and designing trivial components.

To use these examples just grab their HTML (some have a bit of CSS as well), and put them in your project. Enjoy!

1. Login form in modal

A compact login and registration form in a modal. Perfect for “please log in to continue” pop-ups .

Login Form in Modal

2. Bootstrap Timeline

A cool structure for showing events chronologically in a clear and understandable way.

Bootstrap Timeline

Bootstrap Timeline

3. Hosting Pricing Table

A well designed elegant layout for a pricing table with icons, buttons and highlighting.

Hosting Pricing Table

Hosting Pricing Table

4. Forum

Responsive forum topics template that utilities Bootstrap’s classes very well to create this clean layout with only 5 lines of additional CSS selectors.

Forum

Forum

5. Simple resume template

A well organised resume with separated topics, progress bars and social media buttons.

Simple Resume Template

Simple Resume Template

6. Credit Card Form

A small form for online purchase information. Keep in mind, this is only an HTML snippet and there is no card number validation.

Credit Card Form

Credit Card Form

7. Stylish skills listing

This snippet features responsive panels with smooth, CSS only, on-hover effects.

Stylish skills listing

Stylish Skills Listing

8. Responsive pricing tables

Compact pricing tables with different color variations that are easy to customize and adapt to your design.

Responsive Pricing Tables

Responsive Pricing Tables

9. Sign in + sign up form

A log in / register form with separate tabs for each and a payment section. No validation provided.

Sign in + sign up form

Sign In + Sign Up Form

10. Twitter Feed

A compact twitter feed with a form for new posts and a list of tweets.

Twitter Feed

Twitter Feed

11. Responsive Parallax Navbar Logo

A bootstrap navigation bar example where the logo changes size on window scroll. Although this example uses bootstrap components for the layout, all the actual work is done via JavaScript, so make sure you insert that into your code.

Responsive Parallax Navbar Logo

Responsive Parallax Navbar Logo

12. Simple Portfilo With Modals

A nice little cats portfolio demonstrating Bootsrap’s modal functionality.

Simple portfolio with modals

Simple Portfolio With Modals

This concludes our list!

We hope you’ve found these premade component layouts useful for your projects, as the backbone of a more advanced design, or simply as inspiration. Also, check out our list of 50 Must-have plugins for extending Twitter Bootstrap, if you are interested in adding even more cool features to Bootstrap’s arsenal.

Source:: Tutorialzine.com