Category

Tutorial

Phaser Game Part 1: Set up Node Js Server and PhaserJs

This post is part of a series of blog posts aimed to describe the step by step process of creating an browser game with PhaserJs using the latest ECMAscript standards.

This post in particular will set up the basic requirement for the game (server and file structure).

The Tech stack

For this game, I am going to use NodeJs and Express as our back-end server.  I usually use side project like this to gain experience on new territory, but this does not indicate that other servers may be less suitable.

Most of the game and all the game engine, are handled by the browser ( hence the name browser game) and therefore the Server does not play a key part and using nodeJs may actually be a good lightweight option.

The Javascript will be written using the latest ECMAscript 6 standards (please check current support from other blog post). This will enable us to investigate and lean the new standards, while developing the game. (Achieving two objects at once).

Set up the Work Station

Folder Structure

Game

->Server.js

->Index.html

->Assets //This will include all the images and sprites

->Js //This will include all the js file required for our game

->External //This will include the phaser.js library

NodeJs

To install node js you need to download the latest stable version from the Node.js download page. The installation process is quite simple and quick.

After installing node, we will then be able to install all necessary packages by using the NPM software registry, directly from the command prompt.

Express

The first requirement for our small server, will actually require us to install an NPM package called express. This package is one of the most comprehensive web application framework available for NodeJs. To install it you will need to enter the following in your command prompt window:

Install Express
 
cd c:/game/
npm install express

If you are not familiar with the command prompt, in the above snip of code we have firstly navigated to a specific folder, then run the “npm install” command specifiying the name of the package we wanted to install “express”.

This is all that is needed to install new packages using the NPM (Node Package Manager).

Code Editor

There is no requirement for  a code editor. PhaserJs can be ever be developer in a basic notepad.

For personal experience I would suggest one of the following:

  • Visual Studio Code
  • Atom
  • Sublime
  • Nodepad++

Basic Server

To create a web server using Node and Express we just need a couple of lines of code. More information can be found on the express website.

The following code need to be inserted in the file names Server.js.

Basic express server
 
//Example usage in the command prompt
//node Server.js
// Parameters
const port = 880; //Specify a port for our web server
const express = require('express'); //load express with the use of requireJs
var app = express(); //Create an instance of the express library
app.use(express.static(__dirname + '/'));//Serving static files
app.listen(port, function() { //Listener for specified port
    console.log("Server running at: http://localhost:" + port)
});

The code is heavily documented for illustration purpose. Please also note the use of the “const” type.

To run our server we just need to enter the following in our command prompt

run express server
 
node Server.js

Web page

Now that our server is now ready, it is time to create our first webpage.

To do so, just enter the following in the Index.html file:

Basic Index page
 
<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8" />
    <title>My Game with PhaserJs</title>
</head>
<body>
    <h1>Welcome to my game</h1>
    <p>This is my game page.</p>
</body>
</html>

PhaserJs

It is time to add the PhaserJs library in our folders. To do so, visit the phaser JS website. There are many ways to download the library, either by npm command, or by cloning the repository from Git.

After downloading the library, please place the minified file “phaser.min.js” in the external folder to have it ready to be used in our next post.

Conclusion

Our server is now running (by using the command above) and we can access out newly created server by accessing “localhost:880” in our web browser.

This post was needed to set the scaffolding for out game.

 

Javascript Class: ECMAScript standards

 Javascript class

Using javascript class will really improve your code readability, structure and making it shareable with others. ( see my other post: Coding standards: Meaningful Names in Javascript).

For many back end developers, this post would have probably been written over 10 years ago, as classes have always been present in many programming language ( c++, c# and java, etc..). Classes in javascript on the other hand, have just recently been introduced in the ECMAScript 6 release of 2015 and have not yet hit developers keyboards.

This post is aimed aimed to give an introduction to classes and it does not go in many details.

ECMAScrips for Javascript and its advantages

JavaScript does not have the best reputation amongst coding languages, but finally after the long waited version of the ECMAScript standard and good browser support, there is some light at the end of the tunnel, and it is time to deep into the enormous amount of changes that made into the standards.

In recent years, JavaScript developers have been busy creating a multitude of “hacks” and libraries to help us fulfil lack of features that made it hard produce a clean and structured code.

In June 2015 the ECMAScript standards 6 have finally provided a multitude of improvement to one of the most used language in the world, followed by a much smaller release (ECMAScript 7 in June 2016).

ECMAScript 6, took over 4 years to reach our desks, but it didn’t fail to impress and with current browsers finally introducing support for most of the changes, developers are now ready to get their hands dirty and help to improve JavaScript reputation.

Browser Support

Browser support has recently made a fantastic improvement, giving us all a chance to start and implement the great majority of the ECMAScript standards, without worry.

At the time of this post being published (June/2107) the support on desktop is almost complete ( click for full support table):

Edge

FireFox

Chrome

Safari

IE11

As shown by the table above, the support on desktop browser is quite complete, except the odd IE11 with an unacceptable level of support below 15%.

For mobile the situation is quite similar:

Android

iOS

Chrome

Almost full support for the most common browser except on android where just a quarter of features are supported.

Classes Before ECMAScript 6

Even if Javascript class have not been precisely available, developers across the countries have implemented them by using functions, scope, prototype and many other method. This has lead to a multitude of different approaches being adopted by programmers, making the dream of having a possible “standards” a myth.

In this post we will start from an existing small “class” written before the ECMAScript 6, and then implement the newly introduced “classes features” to show the power and structure that they provide to your code.

The code below is an algebra helper for rectangles.

Rectangle
 
var rectangle = function(width, height){
    var self= {};
    self.width = width,
    self.height = height;
    
    var calculateArea = function(){
        var area = 0;
        area = (self.width * self.height);
        return area;
    }
    var calculatePerimeter = function(){
        var perimeter = 0;
        perimeter = (self.width + self.height) * 2;
        return perimeter;
    }
    var getHeight = function(){
        return self.height;
    }
    var setHeight = function(height){
        self.width = height ;
    }
  
  return {
    calculatePerimeter: calculatePerimeter,
    calculateArea: calculateArea,
    getHeight: getHeight,
    setHeight: setHeight
  }
};

Classes in ECMAScript 6

In this section we are going to update the above code to use the javascript class feature.

Class

The first thing that we will have to do is create a base class called rectangle.

base class
 
class rectangle{
    
}

Contructor

Then we will create a constructor. In the previous version of Javscript to emulate the constructor we would have had to create an init function or a self calling function within the method. ( none of this example is shown above as this cover the basic to assign some values).

javascript constructor
 
  constructor(width, height){
 this._width = width;
 this._height = height;
 }

Getter and Setter

Our class is starting to take share, we will now implement the GET and SET methods

Javascrtipt get methods
 
   get height(){
        return this._height;
    }
    set height(height){
        this._height = height;
    }

This methods have been introduced in the ECMAScript 2015. They are commonly used across different programming language and do not require a function call to be initialised. An example usage of the above would be:

get and set
 
var r = new rectangle(10, 5);
r.getHeight;// Output 5
r.setHeight = 10
r.getHeight;//Will output 10

Methods declaration

Class methods have not changed and the declaration is very similar to the one showed in the initial javascript example. The main difference to note is that every method declared within a function will actually be set to PUBLIC. There are rumours of the implementation of public variables and methods for the next ECMA release ( Javascript new private class field). There are currently 4 different “solution” to make standards private methods, and they are all out of the scope of this post.

Method declared within a class will not require the “function” word, and do not require to be returned or specifically made available as they will be available as part of the object immediately after initialisation. Our example will be:

class methods
 
    calculateArea(){
        var area = 0;
        area = (this._width * this._height);
        return area;
    }
    calculatePerimeter(){
        var perimeter = 0;
        perimeter = (this._width + this._height) * 2;
        return perimeter;
    }

Conclusion

This post is aimed at sparkling some curiosity, and give just a small definition of javascript class. The final result is:

final
 
class rectangle{
    constructor(width, height){
        this._width = width;
        this._height = height;
    }
    get getHeight(){
        return this._height;
    }
    set setHeight(height){
        this._height = height;
    }
    calculateArea(){
        var area = 0;
        area = (this._width * this._height);
        return area;
    }
    calculatePerimeter(){
        var perimeter = 0;
        perimeter = (this._width + this._height) * 2;
        return perimeter;
    }
}
var r = new rectangle(10, 5);
r.getHeight;// Output 5
r.setHeight = 10
r.getHeight;//Will output 10

Classes are maybe still not fully ready for big production environment ( mainly because of the absence of a private field), but we should start to use them to get confident in using them when time comes. There are still some amazing features like inheritance ( that has not been covered in this post) that make class worth using.

I personally like the use of class because they force to structure the code differently. They put a big distinction between normal functions and big chunk of work and are perfect to get around Object orientated programming.

I will keep posting my finding on the ECMAscript 6 and future release as for my opinion this is the real future of javascript.

The power of mentoring

Intro

What a better way than start this post with this amazing quote from P. Collins. Teaching and mentoring is not sorely aimed at sharing your knowledge for others to learn, but it is the process in which you personally develop.

“In learning you will teach, and in teaching you will learn.” Phil Collins

It is well known that the IT industry is filled with many people suffering from “The imposter sindrome”, but in many instances these individuals are the best that the market is able to offer, and lean them toward a mentoring career, can be an eye opening experience.

What is mentoring

I have been looking for a nice definition for mentoring, and I finally found one that was short and concise on the oxforddictionaries.com

An experienced and trusted adviser.

I like this quote because it does not go in details, neither does it mention higher qualification or age or company position. It focuses on what really matter Experience and trust.

Experience and trust

Experience is of course a core required for mentorship, as a mentor is supposed to “guide” an individual toward an improvement of some sort. But this experience is not specific to one skill(more details below). During my last 4 years at Vizolution I have been able to be thought by some great mentors, each of which have inspired me in different ways, but what was really great was seeing employers coming in, learn, and share that knowledge with other people.

To mentor someone you need to have some skills to share. What this mean is that you could be very good in keeping notes, and therefore still be able to mentor and support a very disorganised Senior developer, or you could have adapted to scrum faster than your fellow colleagues and help them to get up to speed ( both true stories).

I really think that teaching and mentoring are completely two different way of sharing knowledge. When using the word mentoring, you are implying that you are taking “ownership” of an individual supporting him/her all the way, while teaching is just about knowledge transfer, and does not focus on how much the audience assimilate.

How to mentor

I personally love to mentor, but even more being mentored as I like to see how different people approach this subject and try to learn on the way.

To mentor people you do not need a bright star on your shirt, or a cool Job title on your name badge, what you really need is a state of mind, one that will put other people before any sort of priority, because as I said before you are taking ownership of someone skills and therefore have a duty to support them every step of the way.

I have always enjoyed teaching other people what I knew, but it has just been recently that I have been able to learn how to mentor people. I am currently supporting over 40 developers, and I try to build a specific road map for each of them to help them improve where they need it the most.

Lead the way

There are many different example that I could share, but the message is always the same, lead the way and make sure you are being followed (always make sure you are not talking by yourself, involve the person, test how much they are learning, let them take control).

If you are dealing with a junior developer, instead than just show the correct code to complete a task, you should first of all try to understand the thought that went behind his/her solution, and try to guide the programmer by showing  them the possible improvements and the different paths that could have been taken, so that the correct code becomes just a simple tool of a greater lesson.

Of course the mentoring tactic need to change depending from the individual. Some people want to be supported and helped and don’t really value themselves, but there could be other that are very confident and need a lighter support, they may not even know that you are mentoring them, but this is when mentoring really stands out.

Why do mentoring

It take time, energy, it is very difficult and sometime the person that you are mentoring may not even be aware of it, so why should you even bother.

Personally I think that a great mentor, is a great leader. Mentoring is the best way to learn your strength and your weakness. It help you with personal development and improves your existing skills.

I talked about “the imposter syndrome” above, because developers are well know for not being very social, and in many cases this is also accompanied by a sense of failure. Unfortunately, this developers, are usually the most skilled, but their knowledge is not shared. I have seen the great effect of mentoring on a specific individual, starting to share his personal skills made him realise how good it was, he improved his self esteem, and made him a key employed in the company. We usually focus too much on the core skills (in this case coding), and we forget that people may need help in different areas.

Who can mentor

It should be clear by now, that everyone should mentor. We may all do it differently, and some of us may not succeed at it at first time, but this does not mean that mentoring is not for you.

As mentioned above, I love to being mentored, I like to find the strength in people and let them teach me what their really know by sharing their love for something.  It is not important if they are junior, senior, or even if they do not work in my same sector, if someone has a specific skills that is worth sharing, it is important to accept your weakness and ask for support.

Conclusion

I am currently the technical lead, but this does not stop me going to admit that there are developers that are better than me in specific skills, and this is what mentoring did to me.

Mentoring and being mentored showed me my weakness, but it also showed that there is not harm in being open about them, because I also know to have many different strength. This state of mind is what helped me and there is no better or easier way to achieve it than by offering your help and open yourself to support others.

Transactional email made easy – Postmark

Every developer in their career has been asked to build a transactional email at least once. It usually starts with a simple request like:

Please could you send a simple email when a contact form is submitted, something very simple, nothing special.

A few minutes search on Google or Stackoverflow and “snap”, we find perfectly what we need, the php mail function just does what we need right? The description says “Sends an email” what can go wrong?! Well LOTS.

So we have then starter to create our own implementation of a safe mail sender, we start to create templates, we improve our knowledge of crazy workaround needed for HTML formatting in emails and of course they end in the spam, no matter how clear the content is and our previous excitement just turned into our biggest nightmare.

Don’t reinvent the wheel

Unfortunately the reason why I am writing this post, is because I have been there. I have gone through all the nightmares explained above, and trust my words when I say the word nightmares.

There are company that with great product and the right marketing campaigns, have been able to became the leading providers in the industry (eg. WordPress, Mailchimp, etc..).

Today I am going to share with you what I found to be one of the best provider in transactional email that maybe and hopefully be part of that “right marketing campaigns” that can helps them.

Mail sent and delivered.. hassle free!

Over a year ago, I was ask to implement an easy to use way to create Email templates, that would be reliable, easy to change (code free) and with added analytics. (the conversation started with the sentence shared above.. it was supposed to be an easy job they said 🙂 ).

Postmark was my final choice and I have no regret as it has not only delivered all it was required for me, but it also provides fantastic customer service ( fast and reliable) with affordable plans (They provide initial 25000 email free, plus extra free token that are provided as the service get used more, that is more than enough for a small/medium company).

See to believe

I am going to post below a small example taken directly form my project by creating a very simple email template and show the code required to deliver it. There will be no explanation on how to create an account, and how to fetch the unique key, as the documentation of the website is just great on that.

Step 1 – Create the template

Login into your account and then click on the “Add a new template” button situated in the template section.

postmark crreate templace
Postmark create template screenshots

 

Postmark provides you with a list of templates. Each of the templates provides a very details post with all the information required to create your own version of the template with tons of tips around email requirements, but it also give you the ability to use the open source templates provided by them, or of course start from a blank canvas.

For the purpose of this example we are going to use the existing Welcome template.

Step 2 – Modify the template

Postmark template example
Postmark template example

The Web App provides a very easy to use IDE, everything is within reach, and the template provides you with all the basic structure and example needed.

This editor provides you with a Template name, Subject line, HTML editor, live preview, a variables object, ability to fill the email with test data to see how the email layout will react, a “Send Test” button to see what an email really look like and to finish off, an “API snippets” .

 

postmakr api snippets
postmark api snippets

The snippets provide you with everything you need, all the code has been dynamically filled with your account information, the template id and also all the variables.

The code is provided in 5 different languages curl, Ruby, C#, PHP and Node.js.

If this snippets is not enough, you can be assured to be supported by a great customer service ( I had a lovely personal experience and I deals with 3 different people).

 

 

Step 3 – The code

After creating your HTML template and setting the right variables and small details, there is nothing else left than copy this snippets into the portion of your code than handles the email and replace the variable with actual values.

PHP snippets
 
// Create Client
$client = new PostmarkClient("000000000000-0000-00000000000");
// Make a request
$sendResult = $client->sendEmailWithTemplate(
  "sender@example.com",
  "recipient@example.com", 
  1526526,
  [
  "name" => $_POST["name"],
"username" => $_POST["username"]
]);
?>

That is it, no more code required.

Conclusion

I am usually reluctant to use external tools or API as it makes your product fragile, but there are some cases where the risk is worth while, and this is one of them.

The tons of hours I saved after introducing Postmark and clear way to use it has made this a must have for every of my project small or big.

In this post I have really just touched the surface, as the Web App offers many more features and benefits ( for example low possibility of spam because they make sure no one uses the APP for spams emails and they do any effort to keep the servers clears), and hope after trying it out, you will share my same view.

Reference:

Postmark – https://postmarkapp.com/

image from postmarkapp website

"