Getting Started With HTML5 Game Development: Phaser

From today lets learn HTML5 browser game development – applies both to desktop as well as mobile browsers. You’ll be able to build mobile game apps and launch it to play store or app store.

phaser logo

Phaser is an open source HTML5 game framework created by Photon Storm. It’s designed to create games that will run on desktop and mobile web browsers. A lot of focus was given to performance inside of mobile web browsers, a growing and important area of web gaming.

Video Tutorial List At One Place:
Phaser Video Tutorial List: Game Framework

In this introductory video you’ll be learning:
1. How to get started with Phaser.
2. Download the library and incorporate it into your new game project.
3. Running the game inside the server – in our case, we’re making use of Node server.
4. Quick starter guide to initiate and run the game project.
5. Placing the image in cache – using preload method.
6. Placing the cached/preloaded image(sprite) on to the game stage/container – using create method.
7. Setting the game stage / container background color.
8. Resizing the stage/container and trick to make use of entire device screen for our game.

Phaser Version: 2.4.9 (immediately 2.5.0 was released, so from tomorrows video we’ll be using 2.5.0)
OS used for Demo: Windows 10
Server used: Node Server



YouTube Link: https://www.youtube.com/watch?v=SWEiIxAciUw [Watch the Video In Full Screen.]



Node Server
1. Node.js Video Tutorial List
2. Express Web Framework: Node.js

HTML File – index.html

< !DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="javascripts/library/phaser.js"></script>
</head>
<body>
     <div id="gameContainer"></div>
</body>
</html>

Start with the HTML5 doc type as the first line, as Phaser is a HTML5 Game framework. Then you need to download the phaser library, and include it inside your project. If you’re using Node server, then place the library file and all the files inside the public directory. Use phaser.js file (the unminified version) for development and phaser.min.js file (the minified version) while pushing the code to production server.

You can optionally place a div container to render the game or the game engine will consider entire html body as game stage or container. In our case, for demonstration we’ve placed a div with id gameContainer and we’ll make phaser to use this to render the game objects.

JavaScript Code – Game Code

    var game = new Phaser.Game(window.innerWidth, window.innerHeight, 
                               Phaser.AUTO, 'gameContainer', {
                   preload: preload, create: create
               });
    function preload(){
        game.load.image('logo', '/images/logo.png');  
    }
    function create(){
        game.add.sprite(10, 100, 'logo');  
        game.stage.backgroundColor = '#e7e7e7';
    }

Create a game object with the help of Phaser.Game class. You need to pass the game stage width and height, then we can let Phaser decide whether to user WebGL or canvas to render the game – using Phaser.AUTO property. Phaser gives priority to WebGL, if it’s not present then it’ll make use of Canvas. Next we can optionally specify the game container id, and then the game code.

In this example I simply wrote the code and directly passed it as an argument. This works. And this is ok, if the game code is small. But in big game projects we need to follow modularity – which I’ll teach in my next video tutorial.

A valid Phaser state must have atleast one of these methods – preload, create, update.

preload method: is used to load all the game assets. Once loaded, these assets are stored in cache.
create method: here we make use of cached assets and present them on our game stage or container. We also create other objects needed for our game.
update method: this method is repeatedly called and our game objects are constantly updated to create movements or update the game objects or objectives!

In above code, inside preload method, we are using game object and loading a image and giving it a name called logo, by making use of game.load.image() method. First parameter is a name we give it to the image or sprite as we’ll start calling it from now. The second parameter is the path of the actual image – this can even be a remote server URL. Next we place this image on our game stage using game.add.sprite() method, by using create method. I’ve also shown you how to change the background color of the stage by using game.stage.backgroundColor property.

Full Screen Game
Often time when we’re developing game for mobile device(android or iOS game app), we would want to use full screen of the device – we can achieve this by passing window.innerWidth and window.innerHeight parameter while creating game object – as shown in the code – var game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.AUTO);

Full source code

< !DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="javascripts/library/phaser.js"></script>
</head>
<body>
<div id="gameContainer"></div>
 
<script type="text/javascript">
    var game = new Phaser.Game(window.innerWidth, window.innerHeight, 
                               Phaser.AUTO, 'gameContainer', {
                    preload: preload, create: create
                });
    function preload(){
        game.load.image('logo', '/images/logo.png');  
    }
    function create(){
        game.add.sprite(10, 100, 'logo');  
        game.stage.backgroundColor = '#e7e7e7';
    }
</script>
</body>
</html>

In my next video tutorial I’ll show how to write modular code to handle big game projects – I’ll show it by using same code we used today, so that you’ll feel somewhat familiar.

Please make sure you download the phaser library and try it yourself – this looks like a small example, but worth trying, if you’re a beginner. Stay subscribed, more Phaser video tutorials are on the way.

MongoDB Management Service To Rescue Your Application!

In today’s tutorial we’ll be looking at:
Installing Python
Installing PyMongo (Note: PyMongo is a python driver for MongoDB)
..and running mms-agent from your computer(localhost)

I’m using Windows 7 64-bit machine and the installation procedure are shown for the same.

mms-on-devices

Disclaimer: This is not a paid post and neither am I using any affiliate links in this post. I found MMS(MongoDB Management Service) incredibly useful and I wish I knew about it earlier. The monitoring and alerting services can save your applications reputation, and the backup service will literally save your application in disasters situations.

Requirements
MongoDB software: MongoDB – Getting Started Guide
Python 2.7.3
Setuptools
PyMongo driver software

mms-installation-software

Why use MMS ?

  • MMS tracks the key database and hardware metrics important for managing a MongoDB deployment
  • Performance Visualization
  • Custom Alerts
  • Back-up service ..etc

MongoDB Management Service To Rescue Your Application!



YouTube Link: https://www.youtube.com/watch?v=HkvrksJL3Jg [Watch the Video In Full Screen.]



Steps
Step 1: Install Python 2.7.3 at C:\Python27
Step 2: Install setuptools
Command to install setuptools

1
2
C:\>cd Python27
C:\Python27>python D:\Python\setuptools\ez_setup.py

This installs easy_installer inside C:\Python27\Scripts folder. Easy installer helps in installing drivers.
Step 3: Now install Pythons MongoDB driver: PyMongo, with the following command.

1
2
C:\Python27>cd Scripts
C:\Python27\Scripts>easy_install PyMongo

This would install PyMongo driver

Step 4: Start MongoDB server.

Step 5: Log into your MMS account, and download the MMS-AGENT. Extract the mms-agent files into a folder. In our case, we extract it to D:\Python\mms-agent
Step 6: Now run the mms-agent with the following command

1
2
3
4
C:\>D:
D:\>cd Python
D:\Python>cd mms-agent
D:\Python\mms-agent>agent.py

This starts mms-agent.

Step 7: Go to your mms account – Fill the form with the host name, port number and other details

add-a-host-mongoDB-management-service-mms

Host Type: Standalone (for this example)
Internal Hostname: 127.0.0.1 (ip address for localhost)
Port: 27017 (default port used my MongoDB server)
DB Username and DB Password: are optional

inside-mms-account

Now it’ll start to fetch the meta data metrics via your IP address, as the agent is installed on your local machine and it knows your network IP address.

inside-mongoDB-management-service-account

Key things inside your account
Events: restart, shut-down or downtime etc
Alerts: To alert you in certain situations. You get emails for downtime etc, once setup.
Backup: It’s a premium service, which costs a little – backup service is pay-as-you-go service billed via credit card.
Users: You could invite people as admin or read only user. This way, you could bring in your team mates/colleagues to analyze and help you in performance tuning of your application.
Dashboard: You can customize your dashboard to give you quick view of key aspects of your application is a rich web console. You could have RAM usage statistics or query performance metrics etc.
Settings: Normal profile information: email id, password, phone verification etc.

Application Performance
Checking with the query performance and your application behavior from the very beginning of application development is recommended. And MMS is a perfect solution for this. This is one of the main reasons for this video tutorial. Running MMS on production servers is easy. You’ve bunch of plugins pre-installed at your host, you just need to enable it and insert the secret keys provided to you inside mms-agent file. But I would recommend you to watch for your application behavior from as early as in its development stage.

Note: You should know the norms of your application behavior, so that you can notice when there is abnormalities. MMS helps you effectively do that.

MongoDB Management Service is free service for getting metrics and setting alerts. And you only pay, if you use backup service and you pay for it as you use it.

Server Up or Down: Node.js

Using Node.js application we’ll check if a website is up and running or is it down.

check-website-up-or-down-nodejs

This is a simple application which pings server/URL and checks for the returned status code. Depending upon the status code returned, it displays message to the user on the console window.

JavaScript: Checking for status code
app.js

1
2
3
4
5
6
7
8
var http = require("http");
 
     http.get({host: "technotip.org"}, function(res){
    if( res.statusCode == 200 )
   console.log("This site is up and running!");
 else
   console.log("This site might be down "+res.statusCode);
   });

Here get() method of http object takes 2 parameters. First parameter is an object which contains host name, and the second parameter is a callback method, which gets its parameter from get() methods first parameter.

Using the res object we fetch the status code returned by the server. If the status code is 200, it means website is up and running. Else the website might be down.

Some times we get status code other than 200 and the site will still be up and running, in such cases we can display user-friendly messages and not web geek status codes!

JavaScript: Checking If website is Up or Down
app.js

1
2
3
4
5
6
7
8
9
10
11
var http = require("http");
 
 
  http.get({host: "www.technotip.org"}, function(res){
    if( res.statusCode == 200 || res.statusCode == 301 )
   console.log("Website Up and Running ..")
 else
  console.log("Website down");
 
console.log(http.STATUS_CODES[res.statusCode]);
   });

http object has yet another object nested inside it, called STATUS_CODES which has a list of status codes and its corresponding meaning: as key value pairs. Using this, we could fetch the description of the status code and display it to the user, which will be much more meaningful.

Check if the Server is Up or Down: Node.js



YouTube Link: https://www.youtube.com/watch?v=KQxVggPwDek [Watch the Video In Full Screen.]



Note: If we implement this as a web application, users could check if the website is down for everyone or is it just them.

You could even go through the entire list of all the status codes and implement a complete check and return the result to the user and not let the user guessing with the status code meaning.

Network I/O Is Unpredictable: Node.js

We’ve seen the importance of callback method in our previous video tutorials. Now lets see how networked I/O Is unpredictable.


http-module-get-method-nodejs-network-io-unpredictability

Here we request/ping for information from 3 different servers and look at its response time. Each time we send a request, we get different response time depending upon how busy the server is, its bandwidth etc.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http= require("http"),
      urls  = [ "technotip.org",
         "technotip.com",
      "www.capturecaption.com"
       ];
 
for(var i = 0; i < urls.length; i++){
ping( urls[i] );
}
 
function ping( url ){
var start = new Date();
 
http.get({ host: url }, function(res){
console.log("URL :"+url);
console.log("Response Time: "+(new Date() - start)+" ms");
});
}

Here we require http module, which is built into nodejs, and store it inside a local object called http. We also declare and initialize an array with 3 domain names. Using for loop, we loop through each URL present in the urls array and pass it to a method called ping();

Inside ping method, we record client system date in a variable before sending a request to the server(via URL). Now using http objects get method we send request to the server and see it’s response time. get method takes 2 parameter, first parameter is an object which contains host information – the host url { host: url }. Second parameter is a callback method which automatically gets an object which is returned by first parameter {host: url}. Inside the callback method, we subtract the new system date with the one we recorded before requesting for a response, this way we calculate the response time of each URL.

HTTP get method: Node.js



YouTube Link: https://www.youtube.com/watch?v=vktKMtWoPbA [Watch the Video In Full Screen.]



output
C:\node>node app.js
URL :technotip.com
Response Time: 1462 ms
URL :www.capturecaption.com
Response Time: 1993 ms
URL :technotip.org
Response Time: 2004 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1381 ms
URL :www.capturecaption.com
Response Time: 1702 ms
URL :technotip.org
Response Time: 1871 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1409 ms
URL :www.capturecaption.com
Response Time: 1628 ms
URL :technotip.org
Response Time: 2001 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1512 ms
URL :www.capturecaption.com
Response Time: 1534 ms
URL :technotip.org
Response Time: 1899 ms

Each time we execute the script, we get different response time, and the order of URLs may also differ, as we can’t predict which server will respond first.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)

In this video tutorial we illustrate both client side as well as server side validation.

Client side validation using jQuery.
Server side validation using PHP.

To Solve:
Empty values shouldn’t be registered.
Duplicate usernames must not be allowed.
Display appropriate message, in case of duplicate username.

Explanation about HTML file (index.html), Database connection file(db.php):
Registration Form Using jQuery + PHP + AJAX (PART 1)

jQuery File: Client Side Validation
my_script.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$("#submit").click( function() {
 
if( $("#username").val() == "" || $("#pass").val() == "" )
  $("#ack").html("Username/Password are mandatory fields -- Please Enter.");
else
  $.post( $("#myForm").attr("action"),
         $("#myForm :input").serializeArray(),
 function(info) {
 
   $("#ack").empty();
   $("#ack").html(info);
clear();
 });
 
$("#myForm").submit( function() {
   return false;
});
});
 
function clear() {
 
$("#myForm :input").each( function() {
      $(this).val("");
});
 
}

If the username and the password fields are empty, we display appropriate message and skip the execution of $.post() method.
This ensures that, we do not request data from the server when there is no need for it.

If the user has entered both username and password, then we execute $.post() method and pass the user entered data to process.php file.

PHP File: Server Side Validation
process.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
< ?php
      include_once('db.php');
 
  $username = mysql_real_escape_string( $_POST["username"] );
  $password = mysql_real_escape_string( md5($_POST["pass"]) );
  $fname = mysql_real_escape_string( $_POST["fname"] );
  $lname = mysql_real_escape_string( $_POST["lname"] );
 
 
  if( empty($username) || empty($password) )
  {
  echo "Username and Password are mandatory - from PHP!";
exit();
  }
 
 
 $res = mysql_query("SELECT username FROM users WHERE username='$username'");
  $row = mysql_fetch_row($res);
 
  if( $row > 0 )
    echo "Username $username has already been taken";
  else
  {
     $sql = "INSERT INTO users VALUES('',
                                           '$username', 
                                           '$password', 
                                           '$fname', 
                                           '$lname')";
    if( mysql_query($sql) )
     echo "Inserted Successfully";
   else
     echo "Insertion Failed";
}
?>

At the beginning we check if the username or the password is empty. If they are empty, we echo Username and Password are madatory – from PHP and then stop further execution of the script.

If the username and password are not empty, then we check the user entered username against the usernames present inside the database. If the username is already present inside the database, then we intimate it to the user with a customized message.

Registration Form Validation: PHP + jQuery + AJAX (PART 2)



YouTube Link: https://www.youtube.com/watch?v=dRk1r4SfSyA [Watch the Video In Full Screen.]



Why Validate both client side as well as server side ?
What if javascript has been disabled on client machine i.e., the browser ?
In this situation, our client side validation completely fails. So, server side validation is also important.

Then Why client side validation when server side validation could serve our purpose ?
This is because, client side validation is faster. i.e., if user tries to register empty data, it needs to travel across, reach the server, execute the validation rules script and then travel back to report that the user had submitted empty data and is not acceptable!
Instead of this lengthy, time consuming and costly process, we could simply write a client side validation and it responds back instantly, saving time, bandwidth and hence the cost of processing the data.