Ch004 - Building a World
Building a World

Let’s get started by creating a game world and adding a player to it. Many web developers use a code playground to quickly and easily share a working version of their code as a webpage, or part of a page. Using a code playground is much easier then needing your own webspace. In some ways, all code playgrounds are similar. These tools let you type in code, and display a preview of the resulting webpage immediately. This quick feedback is great for beginner coders. We can immediately see when we have written something properly, and when we have made a mistake that needs correcting. In this book, we are using glitch.com as our code playground.
Creating a Game Area
Our first job is to create a game area on a webpage. To create a game area, we should decide how big it should be on the screen, as well as its shape.

For our project, we will be harkening back to a golden age of video consoles: the 8-bit of Nintendo and Sega home video consoles. Game sizes are normally measured in pixels (px); Pixels are the size of the smallest dot on the screen. Because Mario is such a well known game character, we will use him as an example to get a sense of our game scale. Early Mario Bros. games had a screen size of 256 px wide by 224 px high (256 x 224). Let’s increase the game size to 400 x 300 pixels, to give us a bit more room to play. Now that we know our game size, we need to create a game space using code.
One of the great things about using a code playground is the ability to Remix the work of others and use existing code as a template starting point. Lets give it a try. Our game will be made up of Javascript, living within an HTML page that will link to the Phaser library and our own Javascript game code.
To begin:
1. Go to https://jamm-labs.github.io/ggcp/baw-chapter-starting-frame/game.js
2. Click on the fish in the top right
3. Click Remix on Glitch. At this point you should probably also click Sign In and create an account to save your work.
4. Add the following code into the game.js file under the line that says //start your code here
var game = new Phaser.Game(400, 300);
5. Click Show Live. You should see a new browser tab open and now see a black area appear on the top left of the screen.

This may not seem like much but it’s a great step forward. It means that the phaser library is up and running in your page and has created a game space ready for us to fill with interesting things.
We are now going to create a bit of code called an object that will give us a structure for a lot of our most important game elements. Write the following code in game.js underneath the line your have already written .
var playState = {};
var playState.preload = function() {
};
var playState.create = function() {
};
var playState.update = function() {
};
game.state.add("play", playState);
game.state.start("play");
Let’s explain that code a bit. The first line creates an object for the main part of our game where we play the game. This is called the playState object. It’s the only game state object we need to worry about now but we can add a game over state and welcome state later if we want to.
The three statements after it add three functions to this object. The functions here form a useful structure for our code allowing us to organise it. The structure is based around when each part of the code needs to run. The sections run in the following order;
- preload: add code here to preload images and other assets for the game
- create: this code runs after preload and is where we add images and other elements to the game
- update: this sections runs over and over again for as long as the game is playing
The last two lines add this code (a state object) to the game and say that this is the first bit of code to run when the game starts. We will explore this more later as we start to add more complicated code. For now we can type it and forget about it for a bit.
Adding a Player to the Game Area
We can add a player in a similar way. However as we are going to do more with our player we need to change how we add them a bit. Add var player; above the line where you create the playState object e.g.
var player;
var playState = {};
Putting this line where we declare the player variable outside of the playState object means that all the different functions (like preload(), create() and update() will be able to work with it. This will be useful later.
Add the following code to the **preload function
**
game.load.image("player", "https://cdn.glitch.com/5d318c12-590d-47a1-b471-92a5dc0aae9d%2Fhero_stopped.png");
And the following to the **create function
**
player = game.add.sprite(0, 0, 'player');
Your screen should now show a player added at the top left corner. The top left of the player is added at co-ordinates x:0 and y:0
Adding Gravity to our player
At the moment our Player is stuck at the top of our game. Normally in a platform game gravity acts to pull down our player towards the floor. We can add gravity to the player to make this happen. Gravity is one of the game elements that are dealt with by the Physics system. To add physics abilities to all the game world elements add the following lines right at the start of the create function code.
game.physics.startSystem(Phaser.Physics.ARCADE);
game.world.enableBody = true;
Then add the following line of code in create after where you add player to the game.
player.body.gravity.y = 500;
Your player should now fall from the top of the screen when you run your code. Gravity works! But the player falls all the way off the screen so it is no longer visible. This is not idea for out game. Later will add platforms but for now we will just stop the player from leaving the screen. We do this using the collideWorldBounds capability. Add the following line after your last one in create function.
player.body.collideWorldBounds = true;
The player should now stop when it falls to the bottom of the screen. If this all seems a bit basic to you Don’t Worry we are actually going great guns here! We’ve already got past some of the biggest barriers to getting started making a web game.
Check your Code
If you have followed this chapter correctly should should have some code like the following area - https://jamm-labs.github.io/ggcp/building-a-world-chapter/game.js
Understanding Sequencing
One of the key concepts in computer programming is the importance of the sequence of the computer commands that you write and how they are run. In each of our functions the computer - or code compiler more correctly - will read our code from the first line of the function to the last. This means that it is important to make sure our code is in a logical order. There is a good beginner resources on sequencing here - https://www.bbc.com/bitesize/guides/zsf8d2p/revision/1
To give an example we can look at the lines of code which add
player = game.add.sprite(0, 0, 'player');
player.body.gravity.y = 500;
We can see here that first the player is added to the world and second the gravity value for that player is set. What happens if we swap over the order of these two lines? Try it out put the line with gravity above the line that adds player to the game. Then click on your Show Live tab.
Because the line setting the gravity property is before the line where the player is created it means that there is an error. The screen appears but our player doesn’t load. The message here is that we need to have some awareness of what order we should be running different parts of our code and to pay attention to the sequence, the order that we put it in.
Variables and the var keyword
When coding we often create variables using the var keyword. A
Variable means something we can create and change. Variables can be used
to hold different kinds of information, numbers, words, true/false
elements, and more complicated groups of elements called objects. In our
code we create several variables **player and gravity are key ones.
**
To start using a variable we need to declare it using the var keyword. You can see that happens with player right at the start of the code. After that we can just use player to refer to the variable, we only use var when making it (declaring it). You may ask why do we list some variables at the start of the code or relevant functions. This helps make our code simple to read and understand.
Using functions and parameters
We have already written some functions in code. For the playState object we have written and added three functions to it; preload, create and update. We create and use these functions to help us to organise our code as they run in a particular order. The Phaser framework calls and runs the code in these functions one after the other as the web page loads.
As well as creating our own functions, we will also meet other functions which area already written for us that we can use. These functions are also sometimes called methods. To make things simpler in this book we will try to use only the term function.
Phaser contains pre-written functions which are bits of code that do certain jobs for us. We can recognise them by the use of brackets () after the name of the function being called. For example. here look at the following code.
game.add.sprite(0, 0, "background");
Here we use a function of game called game.add.sprite() to create and add our new variable called player to the game object. Between the brackets we including three pieces of information called parameters. In other words in this line of code we pass this function three parameters.
The parameters passed to the function here are; the x co-ordinate 0, the y co-ordinate 0, and the name of the image to add ‘background’. This particular function needs these bits of information to be able to do its job of adding the image passed to it at the right place in the game. We’ll get used to passing parameters into functions as we go along. For now just try to be aware of these terms and try to understand how they are being used when you come across them.
Let’s add some elements to make a more realistic game space. We use the platform game genre as that is easy to recognise and to create code for. Let’s create some platforms for our player to jump onto and some coins to collect.
Creating a Group for our Platforms and Ground
We already know how to add images to our game but when we add our platforms we are going to do it in a way that allows us to change the properties of all the platforms at once. You will see how this will be useful in a bit. To do this we will first create a group, and then when we create each platform we will add them to that group. To add specific platforms we now need to follow this pattern.
- load images in preload
- add images in create
- add them to the platforms group
- add code to make the player stand on the platform
First let’s add the variable platforms to the start of our code. Change the code.
var player;
so that it now reads
var player;
var platforms;
In the playState.preload function let’s load up an image for ground and a platform.
game.load.image("ground", "https://cdn.glitch.com/5d318c12-590d-47a1-b471-92a5dc0aae9d%2Fground.png");
game.load.image("grass:4x1", "https://cdn.glitch.com/5d318c12-590d-47a1-b471-92a5dc0aae9d%2Fgrass_4x1.png");
At the end of our the existing code in the plaSstate.create function let’s add the code which creates a group in our game called platforms and enables body so that it can interact with other elements in the game.
platforms = game.add.group();
platforms.enableBody = true;
Now let’s add this code after the above to create a ground for our player to stand on
var ground = platforms.create(0, 275, 'ground');
Try running your code at this point. You will see that when the player sinks down behind the floor. To avoid this in playState.update: add this code
game.physics.arcade.collide(player, platforms);
Try again and this time the player bumps the platform down out of sight. To avoid this add another line after your last one added to playState.create:.
ground = platforms.create(0, 275, 'ground');
ground.body.immovable = true;
Follow this pattern to add more platforms for the player to jump on**.**
var platform1 = platforms.create(150, 220, 'grass:4x1');
platform1.body.immovable = true;
var platform2 = platforms.create(250, 150, 'grass:4x1');
platform2.body.immovable = true;
var platform3 = platforms.create(75, 100, 'grass:4x1');
platform3.body.immovable = true;
Feel free to change the location of your three platforms to make them more challenging.
Debugging Jumping
This game actually starts with a Glitch at this point that we have to fix. There is something not right about jumping here. We can jump when ever we want. This means we can jump right up to the top of the screen as if we were flying. This isn’t what we want. We should only be able to jump when we are touching the ground. This will be is one the rules of our game and it is common to a lot of platform games. To make this happen we can use a conditional statement using if.
Change the code which controls the up keyboard key to change the statement condition in the first line to be:
if (game.input.keyboard.isDown(Phaser.Keyboard.UP) === true && player.body.touching.down === true) {
player.body.velocity.y = -300;
}
This if statement now has has two conditions that need to be true before the code in brackets will run. The user must be pressing the UP key and the player character must be touching down on one of the platforms. If they are already jumping they will be in the air, and the player.body.touching.down property will be false and the code in the conditional block won’t run.
Checking our Code
Have a look at the following Code area to check your code against what we think you should have. https://jamm-labs.github.io/ggcp/create-game-space-chapter/game.js
More on conditionals
As we can see in the code controlling jumping, there can be more conditions that needs to be true or false before a certain piece of code can run. In the last chapter we saw how the three options of if, if else and else provide a flexible way of providing different options of code to run depending on different user input and other conditions. Now let’s look at the (condition) part of the statement.
The process for this is known as True / False or Boolean Logic and even though we are dealing only with different options which are all true or false it can quickly get confusing. Let’s take a simple example where were are testing if something is true. We can use the === comparison operator to check this in our conditional testing statement. Let’s say we are testing to see if it is raining.
if (isRaining === true){
wearCoat();
}
But imagine a situation where we want to check if it is raining OR if the clouds are dark. If either is true then take a coat out. This could be checked using the || logical operator - which means OR - to check both conditions.
if (isRaining === true || isDark === true){
wearCoat();
}
However, if we want to check if it raining AND the clouds are dark and we will only then take a coat out if both are true. This might be structured like this.
if (isRaining === true && isDark === true){
wearCoat();
}
Let’s look at a table from the above resource of the logical operators used here to help understand them.
| Operator | Description | Example |
| && | and | (x < 10 && y > 1) is true |
| || | or | (x === 5 || y === 5) is false |
| ! | not | !(x === y) is true |
This is a subject that suits learning through doing, through experimenting and getting things a bit wrong and trying out different options until you get the one you want. As mentioned previously, there is a resource which is more complete here. https://www.w3schools.com/js/js_comparisons.asp