Making a LibGDX Roguelike Survival Game Part 7 – Adding Trees, Entity Sorting #gamedev

** Noticed a typo in my entity package, this has been renamed 
evoscape/core/src/uk/co/carelesslans/entity/ **

[ Full source code for this tutorial ]

EvoScape is starting to look a little like a game but we yet to have any items to interact with, if we are going to have crafting etc then we need resources, to get started we will add some trees for wood. Before we look at how we handle collisions we need to populate the island with some trees.

Screen Shot 2017-08-06 at 14.24.27

The tree images needs to be saved to assets/entities/tree.png
Add new a new class variable for the Tree texture, load it in the load_assets() method and ensure it is disposed in the dispose method:

public static Texture tree;
tree = new Texture("entities/tree.png");
Our EntityType enum needs a new type of “TREE” added for the Tree class, at the moment we do not need to use the type but it will come in useful when we want to save our game etc:

public enum EntityType {
The Tree class extends Entity, it initialises entity its public construcor then sets the type, size, position, texture and creates a new Box2D body so it has a collision box the hero cannot walk through.

The hitbox is half the width and height, here you can see the createBody method accepts another 2 parameters, these are xOffset and yOffset. These new values allow us to have better positioned hitboxes. We want the Tree hitbox to be just the size of the trunk area:

public class Tree extends Entity{
    public Tree(Vector3 pos, Box2DWorld box2d){
        type = EntityType.TREE;
        width = 8;
        height = 8;
        this.pos = pos;
        texture = Media.tree;
        body = Box2DHelper.createBody(, width/2, height/2, width/4, 0, pos, BodyDef.BodyType.StaticBody);

The Tree hitbox.
The updated class adds xOffset onto the X value and yOffset onto the Y value of the entities position in the createBody method:

public static Body createBody(World world, float width, float height, float xOffset, float yOffset, Vector3 pos, BodyDef.BodyType type) {
       Body body;
       BodyDef bodyDef = new BodyDef();
       // Updated postion code.
       bodyDef.position.set( (pos.x + width/2) + xOffset, (pos.y + height/2) + yOffset);
       bodyDef.angle = 0;
       bodyDef.fixedRotation = true;
       bodyDef.type = type;
       body = world.createBody(bodyDef);

       FixtureDef fixtureDef = new FixtureDef();
       PolygonShape boxShape = new PolygonShape();
       boxShape.setAsBox(width / 2, height / 2);

       fixtureDef.shape = boxShape;
       fixtureDef.restitution = 0.4f;


       return body;

Before Trees can be added to the Island we need an ArrayList to store them in, the array will hold a type of Entity, any class that extends Entity can be added to this list:

// Class variable
public ArrayList<Entity> entities = new ArrayList<Entity>();

Next we create a new method that will loop through all of our tiles and randomly add trees, we will look if the tile is grass before adding one also we will roll a random number and allow there to be a 10% chance of a tree being placed:

private void addEntities(Box2DWorld box2D) {
    // Loop all tiles and add random trees
    for(ArrayList<Tile>; row : chunk.tiles){
        for(Tile tile : row){
            if (tile.isGrass()){
                if(MathUtils.random(100) > 90){
                    entities.add(new Tree(tile.pos, box2D));
// As previously shown the Tree public constuctor which is called to create
// a new tree
public Tree(Vector3 pos, Box2DWorld box2d){

Calling this method and populating Trees will work but running the game they will not be drawn, we add to our render loop after the tiles have been drawn, looping and drawing the entities. The draw method within the Entity class is called unless the Tree class overrides this method:

// Draw all entities
for(Entity e: island.entities){

Running this code will show our randomly sized map and now a number of trees, this looks great until you behind a tree and find you are rendered on top of it. To overcome this we need to add the hero to the array of entities and sort it before rendering.

Screen Shot 2017-08-05 at 23.57.32

No “Z Sorting”
To sort the array of Entity we implement Comparable and compare the class to itself. With that in place we add a compareTo method that will compare the Y values:

// implement comparable
public class Entity implements Comparable<Entity> {

// New method
public int compareTo(Entity e) {
    float tempY =  e.pos.y;
    float compareY = pos.y;

    return (tempY < compareY ) ? -1: (tempY > compareY) ? 1:0 ;
After the Hero instance is created add it to the list of Island entities so that it can be sorted and drawn in order with the array.

// Island
island = new Island(box2D); 

// Hero
hero = new Hero(island.centreTile.pos, box2D);
island.entities.add(hero); // Add hero to entity array

// Before drawing the entities sort the array

Running the game we can now move behind trees:


The hero is now drawn in the correct order (based on its Y value)

Adding a reset option that re-generates the Island
Add a new boolean to the class called reset, this will be set to true on pressing ‘R’:

// New class variable
public boolean reset;

// public boolean keyUp(int keycode) {
// new key
case Keys.R:
    reset = true;
To reset everything we will need to clear down all of the bodies we have added to the world, a new method clearAllBodies handles this:

// New method to remove Box2D bodies from the World
public void clearAllBodies() {
    Array<Body> bodies = new Array<Body>();
    for(Body b: bodies){
Within our game logic (Render loop) we check this reset variable and when its true call reset on hero and island, re-add hero to entities and set reset to false:

    control.reset = false;
Create a new reset method and call this from the public constructor, this saves re-writing the same calls twice:

public Island(Box2DWorld box2D){

public void reset(Box2DWorld box2D) {
Add reset method and update the public constructor, when we reset the hero we re-position it to the centre and re-create its hitbox:

public Hero(Vector3 pos, Box2DWorld box2d){
    type = EntityType.HERO;
    width = 8;
    height = 8;
    texture = Media.hero;
    speed = 30;
    reset(box2d, pos);

public void reset(Box2DWorld box2d, Vector3 pos) {
    body = Box2DHelper.createBody(, width/2, height/2, width/4, 0, pos, BodyType.DynamicBody);

Now when we run the game and press ‘R’ the hero is placed back to the centre of the map and we generate a new island with different number of trees.


Next we will implement collision listeners so we can act on being in contact with a tree, exciting stuff!

Making a LibGDX Roguelike Survival Game Part 6 – Box2D Collisions #gamedev

[ Full source code for this tutorial ]

Currently our hero can move around disregarding the underlying map, running over grass, cliffs and water, the next step is to impose some restrictions and implement collisions. When the project was created we chose to include Box2D:

Box2D is a 2D physics library. It is one of the most popular physics libraries for 2D games and has been ported to many languages and many different engines, including libgdx.

Using LibGDX we have to create a fair amount of the game code ourselves which can be a good thing but writting your own physics engine will slow your progress significantly, Box2D will do all the heavy lifting for us.

To get started we will need a Box2D World, creating and initialising the world will initialise Box2D.  Our world is top down so we do not need any gravity, the World takes a vector for gravity and also a boolean to set if the world objects sleep. To manage Box2D we will create a new class, as we add more features it will be cleaner to keep all of this together away from the other code. (in a new package “” )

public class Box2DWorld {
  // instance of a B2D World
  public World world;
  // Used to render objects which would be invisible
  private Box2DDebugRenderer debugRenderer;

  public Box2DWorld(){
    // Initialise world with no gravity!
    world = new World(new Vector2(.0f, .0f), true);
    // Initialise debug renderer
    debugRenderer = new Box2DDebugRenderer();

This class has a tick method which will step the world and if debug is enabled draw the world shape outlines.

public void tick(OrthographicCamera camera, Control control){
  // Pass in control to check if debug is true
  if (control.debug) debugRenderer.render(world, camera.combined);
  // step the world forward in time
  world.step(, 6, 2);

The call to clearForces() should be done automatically so I will likely remove this call in another commit:

/** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The /** Manually clear the force buffer on all bodies. By default, forces are cleared automatically after each call to Step. The * default behavior is modified by calling SetAutoClearForces. The purpose of this function is to support sub-stepping. * Sub-stepping is often used to maintain a fixed sized time step under a variable frame-rate. When you perform sub-stepping * you will disable auto clearing of forces and instead call ClearForces after all sub-steps are complete in one pass of your * game loop. {@link #setAutoClearForces(boolean)} */

Next we create a helper class that can create objects for our Box2D world, to get us started we need static boxes that can be used to set a boundary around our island. 
(package “” )
The helper class allows us to create a Box2D Body, there are several types of body, we will be creating static body types only at the moment. The Box2D site fully explains creating a new body, these bodies will match the size, shape and location of our tiles. For the body to fit over the tile we have to add have the half the width or hight to the x/y position, this is due to the co-ordinates being used as the centre point.

Creating the PolygonShape we have to half the width/height due to Box2D using this value as half the size:

/** Build vertices to represent an axis-aligned box./** Build vertices to represent an axis-aligned box. * @param hx the half-width. * @param hy the half-height. */ public void setAsBox (float hx, float hy) { jniSetAsBox(addr, hx, hy); }

Here is the helper class thus far, the method we will use is static:

public class Box2DHelper {
    public static Body createBody(World world, float width, float height, Vector3 pos, BodyDef.BodyType type) {
        Body body;
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(pos.x + width/2, pos.y + height/2);
        bodyDef.angle = 0;
        bodyDef.fixedRotation = true;
        bodyDef.type = type;
        body = world.createBody(bodyDef);

        FixtureDef fixtureDef = new FixtureDef();
        PolygonShape boxShape = new PolygonShape();
        boxShape.setAsBox(width / 2, height / 2);

        fixtureDef.shape = boxShape;
        fixtureDef.restitution = 0.4f;


        return body;

We are ready to add our Box2D class

Box2DWorld box2D;

The new variable will need to be initialised within the create() method, a change to will be made to accept the box2D variable as a parameter:

// Box2D
box2D = new Box2DWorld();

// Island
island = new Island(box2D);

At the bottom of the render method we call the tick method of the Box2DWorld instance:

  // call tick method to draw debug lines
  // pass in control to check it debug is true
  box2D.tick(camera, control);
Box2DWorld is needed within the Island class, once the tiles are setup we need to loop through them and check which of them require a collision object making them inpassable.

public Island(Box2DWorld box2D){

Before looking at the new generateHitboxes method there is a small fix to and two new methods required in the class: – getTileCode should return 0” and never a null, other wise we could end up with tile codes containing ‘nul’.
isAllWater checks if the tile is water surrounded by water, notIsAllWater returns if the tile is not all water. I prefer to create methods that return the opposite value so they read better, these methods could be better named though!

public boolean isAllWater() {
    return code.equals("000000000");

public boolean notIsAllWater() {
    return !isAllWater();

With those fixes and additional methods in place we can loop the tiles in the chunk once they are generated and add collision objects where needed.

Looping all of the tiles and checking that they are not passable but not all water we are finding the edge of the island, these are the tiles that should stop the hero moving further, it would be wasteful to create objects for every water tile:

private void generateHitboxes(Box2DWorld box2D) {
  for(ArrayList<Tile> row : chunk.tiles){
    for(Tile tile : row){
      if(tile.isNotPassable() && tile.notIsAllWater()){
        Box2DHelper.createBody(, chunk.tileSize, chunk.tileSize, tile.pos, BodyType.StaticBody);

Running the game and pressing the backspace key toggles control.debug, when on the debug renderer will draw the world bodies, at the moment the hero is still OP and moves where ever they want:


Lets add a collision box for the hero so they are trapped on the island, the bodies added to the world for the tiles are not children of the Tile class, once created we cannot access them through the parent (tile), this will be addressed. When it comes to the hero we need to be able to move the body, first add a new variable to Entity class:

public Body body;

The hero will need the box2D variable passed into the public constructor so we can create the body via the world. The body for the hero is dynamic as it will need to move, we dont want the body to be the full height of the hero (wait for the image):

public Hero(Vector3 pos, Box2DWorld box2d){
  type = EntityType.HERO;
  width = 8;
  height = 8;
  this.pos.x = pos.x;
  this.pos.y = pos.y;
  texture = Media.hero;
  // We need to increase the speed!
  speed = 30;
  // Create a new Dynamic body
  body = Box2DHelper.createBody(, width, height/2, pos, BodyType.DynamicBody);

Next change the update for the Hero class, rather than moving the Entity position we move the Box2D body but setting the linear Velocity, then we set the positon of the Entity to the x and y or the body.

If we were to set the position of the Body using the hero position then we would over ride collisions and force its position:

public void update(Control control) {

  body.setLinearVelocity(dirX * speed, dirY * speed);
  pos.x = body.getPosition().x - width/2;
  pos.y = body.getPosition().y - height/4;
} – update the setup of the Hero class as it requires box2D passed in:

hero = new Hero(island.centreTile.pos, box2D);

Running the game and turning on debug we can see the hero now has a collision box which cannot pass through the other bodies:


Next we will look at adding in trees to an array of entities and sorting these so our hero can be appear in front or behind them.




Making a LibGDX Roguelike Survival Game Part 5 – Code Style #gamedev #indiedev

Thanks to @cnnranderson for bringing up the Java code style.

Code style is important and coming from a background in many languages other than Java I tend to break a lot of the advice/rules that other Java developers would follow. It was also mentioned that the Vector2 position for the hero is not required, so we can fix that and some variable / method names.

[ Full source code for this tutorial ]

The updated code removes the Vector2 and updates methods and variables so they use camelcase rather than underscores.

If you are interested in the other rules / advice please read the Java code style page.


Making a LibGDX Roguelike Survival Game Part 4 – I need a hero #gamedev #indiedev

Screen Shot 2017-08-02 at 21.28.51
[ Full source code for this tutorial ]

Most games will have a main character or a hero, for the moment ours will be this little person, they can be replaced later if necessary.

The hero will need a new class that extends Entity, it will need a new texture and ENUM type. We will need to change the keyboard inputs to move the Hero Entity and have the camera follow them.
A new enum is needed for entities, for now we only have one type of HERO:

public enum ENTITYTYPE {
This new enum type and speed can be added to Entity as class variables:

public ENTITYTYPE type;
public float speed;
Add the hero image to a new folder; “assets/entities/hero/hero.png”

Add a new Texture to this class and in the load_assets function initialise it:

public static Texture hero;
  hero = new Texture("entities/hero/hero.png");
The public constructor for our hero class sets the type to the newly defined HERO, we set the dimensions, texture, speed and position. The position is a Vector2, this has a x and y value and denotes the hero position on the map, the initial position is passed as a variable (pos) to the class.

public Hero(Vector2 pos){
  width = 8;
  height = 8;
  this.pos.x = pos.x;
  this.pos.y = pos.y;
  texture = Media.hero;
  speed = 1;

Previously we stored the on screen location in some temporary variables, these will now be tracked within our hero class and updated every frame:

public void update(Control control) {

  if (control.down) dir_y = -1 ;
  if (control.up) dir_y = 1 ;
  if (control.left) dir_x = -1;
  if (control.right) dir_x = 1;

  pos.x += dir_x * speed;
  pos.y += dir_y * speed;

We pass the control instance into the public update function and use the same logic as before to set the x and y values for the Hero Entity.
Variables to remove from class:

// Temp x and y co-ords
int x, y;

// For Movement
int direction_x, direction_y;
int speed = 1;

Add an instance of Hero to the class:

Hero hero;

Initialise the hero instance passing in the centre tile, we will need to make this variable public in order to access it.

// Hero
hero = new Hero(island.centre_tile.pos);

Now we have the Hero class we can also remove code from the render function of the gameclass:

// This now exists in the Hero class
if (control.down) direction_y = -1 ;
if (control.up) direction_y = 1 ;
if (control.left) direction_x = -1;
if (control.right) direction_x = 1;

// Camera position will need to use the hero Vector2
camera.position.x += direction_x * speed;
camera.position.y += direction_y * speed;

The new render code to update the hero, camera position and draw our hero:

camera.position.x = hero.pos.x;
camera.position.y = hero.pos.y;


We call the Hero update function every frame and pass in the control instance so we can check the WASD or arrow keys are pressed and change the positions accordingly. The draw function for the Hero is the default function held in the Entity class. If everything is correct we should now be able to move our hero around the screen, the camera position is set to that of the hero:

This appears ok but the camera position is incorrect, the image below shows that snapping to the x and y positions of the hero the camera is placed at the bottom left of the image.

To overcome this we can add new functions to the Hero class that return the correct values and call these from the render function of the gameclass:

public float get_camera_x() {
  return pos.x + width/2;

public float get_camera_y() {
  return pos.y + height/2;

// Render Loop for
camera.position.x = hero.get_camera_x();
camera.position.y = hero.get_camera_y();

To take this one step further lets look at a function available on the camera position called Lerp. Further reading on Interpolation. This basically moves the camera toward the Hero’s position slower than the hero has moved, so we get a nice smooth/delayed camera movement.

Rather than setting the x and y values of the camera.position we can call camera.position.lerp, this requires a Vector3 rather than Vector2 so we will need to make some small changes.
Add a new Vector3 variable, a Vector3 holds x,y and z values, we wont need the z value so can just set this to 0 and ignore it.

public class Entity {
  public Vector2 pos;
  public Vector3 pos3;

  // initialise the new variable in the public constructor
  pos3 = new Vector3();

When we call the Hero update function we can set the Vector3 variable using the Vector2 that has already been updated after checking the for keyboard inputs:

pos3.x = pos.x;
pos3.y = pos.y;

Moving back to after the hero.update function is called we can set the camera position using the new Vector3 variable:

camera.position.lerp(hero.pos3, .1f);

The .1f defines the speed at which the camera catches up with the hero position, 0.1 (f stands for float) should give a steady speed, as long as the speed is less than the hero’s speed we will see some delay.

Final resultlerp.gif

We now have a randomly sized island in the sea, a hero that can move and a camera that follows, next we will look at using Box2D to handle our collisions and make sure our hero cannot walk on water.







Making a LibGDX Roguelike Survival Game Part 3 – Loading Media refactored #gamedev

LibGDX offers an asset manager that can help take care of loading and getting textures etc, feel free to take a look at this, the wiki page shows exactly how it is used. The main benefit is the asynchronous loading of assets and the ability to display a loading bar:

“Loading of most resources is done asynchronously, so you can display a reactive loading screen while things load”

Screen Shot 2017-08-02 at 15.43.37.png

[ Full source code for this tutorial ]

Our game has very few assets which are all very small in size, for now we can move the loading of Textures to a new class. In the main package we will add a new file, we will move all of the Textures defined in into this new class.

// class variables

public static Texture grass_01, grass_02, grass_03, grass_04;
public static Texture grass_left, grass_right;
public static Texture grass_left_upper_edge, grass_right_upper_edge;
public static Texture grass_top, grass_top_right, grass_top_left;
public static Texture water_01, water_02, water_03, water_04;
public static Texture cliff, water;

There is a static function in the Media class (load_assets) which will initialise all of our textures both are defined as static:

public static void load_assets(){
  grass_01 = new Texture("8x8/grass/grass_01.png");
  grass_02 = new Texture("8x8/grass/grass_02.png");

These images will not change and we only want to load them once, as they are so small there is no need to dispose of them mid game, we can call this method from are main in the Create() method and our images will be ready to use:


We can remove the old reference to loading images (also remove the function form this calss) so the public function now looks like this:

public Island(){

To fix all of the references to the textures that are no longer declared in this class we reference them via the Media class (not an instance of it):

tile.secondary_texture = Media.grass_top_right;

Once all of the references are updated the game should run as it did previously, going forward this will make the assets a little easier to manage as they will all be in one place.

This class will make it easy to add new textures and even switch between different tile sets without having to change the island, chunk or tile classes at all.


Making a LibGDX Roguelike Survival Game Part 2 – Adding a simple Island #gamedev

The tiles used for this game are available here Open Game Art tile set, Open Game Art has some really great tile sets worth using; especially when you are prototyping. This is an example from the site showing what can be achieved with this tile set:

[ Full source code for this tutorial ]

For this part of the tutorial we will review the new classes, Entity, Chunk, Tile and Island, these are used to generate a simple island/ map which can be rendered to the screen.

The key variables for the entity class are as follows:

public Vector2 pos;
public Texture texture;
public float width;
public float height;

Almost all objects have position, width, height and a texture, this is enough information to draw an image to the screen at a certain and co-ordinate. The class has a simple draw function which can be called by classes we create that extend Entity, we can override this method if more logic etc is needed in the draw function:

public void draw(SpriteBatch batch){
  batch.draw(texture, pos.x, pos.y, width, height);

An Enums class was created to hold all the enumerators we will need, at the moment we only need some TILETYPE‘s so we can set the type of our tiles, grass, water and cliff.

The three new classes for defining, generating and drawing the island are added to a new package named “map”. Packages are used to organise related classes (like a folder), even a small game can become over loaded with classes quite quickly.
This holds information on an individual tile (square space) which extends Entity; giving access to all of the properties of that class:

public class Tile extends Entity {

When we initiate a new tile we pass in its location, size, type and texture, the size is basically the scale, if we decide on a smaller/larger tile size later we can easily experiment changing only the size. Calling super() will initiate the Entity (calls the Entity public function).

public Tile(float x, float y, int size, TILETYPE type, Texture texture){
  pos.x = x*size;
  pos.y = y*size;
  this.size = size;
  this.texture = texture;
  this.col = (int) x;
  this.row = (int) y;
  this.type = type;
  this.code = "";

There are a number of boolean functions that make testing tiles more readable e.g tile.is_grass() or tile.is_water(), is_passable(), this becomes useful when we have a lot of code that checks a tile is passable, changes to the passable logic can be maintained in place e.g:

public boolean is_grass() {
  return type == TILETYPE.GRASS;
A chunk will hold an array of arrays of tiles, it can useful to split the chunk into rows for rendering order and for selecting tiles, you do not have to do this and could just have one big array of tiles; ArrayList, the structure:

                Tile, Tile, Tile
                Tile, Tile, Tile
                Tile, Tile , Tile

Chunk public constructor accepts the number of rows, columns and the size of the tiles (tiles are square):

public Chunk(int number_rows, int number_cols, int tile_size ){
  tiles = new ArrayList&amp;amp;lt;ArrayList&amp;amp;gt;();
  this.number_rows = number_rows;
  this.number_cols = number_cols;
  this.tile_size = tile_size;

We have some useful functions in the chunk class, both require a row and column integer; get_tile returns a tile and get_tile_code returns the code for a tile. Later when we allow interaction with tiles or need to check the tile the hero is on we can calculate the row and column by the cursor or hero x and y positions.

Tile Code
Creating a code to describe a tiles neighbours allows us to make graphic and logic decisions. The centre tile show below has a code of “111000000”, we read the code left to right one row at a time, the three tiles above are all passable so get set to 1, the cliffs and water are all 0’s.


This method can be repeated to achieve all sorts, for example you could find all grass touching water and turn it into sand.
This class will create a new chunk and populate it with tiles, there is logic to first fill the chunk with water tiles, then find the centre and create a grass island. There is some code present which can be refactored and moved into other classes later. Often the first draft or prototype code is messy especially in a game jam or challenge.

To hide some of the complexity the public constructor for the island class calls three functions:

public Island(){

* Not everyone will like the naming conventions I use, I work with Ruby, Go, PHP,, C# and Java so use a mixture sorry! :Fixed in part 5 *

The images should really be loaded in another class, this will be address in the next part of this series. We setup our images as LibGDX Textures. Further information on loading files available on the wiki, when you are writing a game for mobile or HTML you will need to look at the File Handler, we can get away with a relative path for our images though:

grass_01 = new Texture("8x8/grass/grass_01.png");

The next step is to create a chunk and fill it with tiles. For now we will go with a chunk size of 33 (a random number I selected, we can revisit this), the tiles are size 8, to create an island we:

  • Generate a random number 5 to 8 for half the height and width in tiles
  • Find the centre row and column
  • Calculate first and last row and columns

This defines a randomly (within set bounds) sized square which we can place in the middle of the chunk.

chunk = new Chunk(33,33, 8);

int current_row = 0;
int rng_w = MathUtils.random(5,8);
int rng_h = MathUtils.random(5,8);

int centre_tile_row = chunk.number_rows / 2;
int centre_tile_col = chunk.number_cols /2;
int first_tile_row = centre_tile_row - (rng_h);

int max_row = centre_tile_row + rng_h;
int min_row = centre_tile_row - rng_h;
int max_col = centre_tile_col + rng_w;
int min_col = centre_tile_col - rng_w;

To create all the tiles we can use a two for loops, for example:

int rows = 2;
int columns = 2;

for (int r = 0; r &lt; rows; r++){ // Loop for rows
  for (int c = 0; c &lt; columns; c++){ // loop for columns
    System.out.println("Row: " + r + " Column: " + c);

This would output (2 x 2 map, 8 tiles):

Row: 0 Column: 0
Row: 0 Column: 1
Row: 1 Column: 0
Row: 1 Column: 1

The map generation works the same, its starts by creating a new tile inside of second for loop and making that WATER by default, random_water() is called to set the texture, this makes the map more interesting by varying the water image used, as the random int is 0 to 20 and only 2, 3, 4 select alternative images most water tiles will be water_01 texture.

// Create TILE
Tile tile = new Tile(col, row, chunk.tile_size, TILETYPE.WATER, random_water());

// Random Texture
private Texture random_water(){
Texture water;

int tile = MathUtils.random(20);
switch (tile) {
    case 1: water = water_01;
    case 2: water = water_02;
    case 3: water = water_03;
    case 4: water = water_04;
    default: water = water_01;
    return water;

When looping through the tiles the max and min columns and row variables can be used to check if the current row and column are inside of values, if they are then the tile can be changed to GRASS

if(row &gt; min_row &amp;&amp; row &lt; max_row &amp;&amp; col &gt; min_col &amp;&amp; col &lt; max_col){
    tile.texture = random_grass();
    tile.type = TILETYPE.GRASS;

We store the lowest row of grass tiles, if we are currently processing those they we can make the type a CLIFF:

if(row == first_tile_row + 1){
  tile.texture = cliff;
  tile.type = TILETYPE.CLIFF;
} else {
  // Chance to add trees etc

We have to use first_tile_row + 1 as we have row > min_row and not  row >= min_row.

The code for adding the tiles to a row and adding the rows to the chunk works like this:

if current row
        add new tile to the row array
if current row and column are the final then add the row array to the chunk
        set current row number
        add row to chunk
        clear array row (new array)
        add tile to array row

Here is the actual code that builds the array of array of tiles:

if(current_row == row){
  // Add tile to current row

  // Last row and column?
  if (row == chunk.number_rows - 1 &amp;&amp; col == chunk.number_cols - 1){
} else {
  // New row
  current_row = row;

  // Add row to chunk

  // Clear chunk row
  chunk_row = new ArrayList();

  // Add first tile to the new row

Now that the tiles all of the tiles exist the tile codes can be calculated,

for(ArrayList row : chunk.tiles){
  for(Tile tile : row){
    // Check all surrounding tiles and set 1 for pass 0 for non pass
    // 0 0 0
    // 0 X 0
    // 0 0 0

    int[] rows = {1,0,-1};
    int[] cols = {-1,0,1};

    for(int r: rows){
      for(int c: cols){
        tile.code += chunk.get_tile_code(tile.row + r, tile.col + c);

As we only have one chunk at the moment we loop all tiles in the array’s of rows, when we have multiple chunks we would need another for loop to do this for each chunk. For each tile we need to get all of the neighbouring tiles, int[] rows = {1,0,-1} these numbers are used to represent one row above, same row and the row below the current, we have the came for columns, two for loops allows us to get a reference to all eight surrounding tiles plus itself.

Once the Tile object has a code we can check if it requires an additional image, we do this by checking if the tiles code matches any in the arrays created in the earlier.

  tile.secondary_texture = grass_left;
} else if (Arrays.asList(a_grass_right).contains(tile.code)){
  tile.secondary_texture = grass_right;

When we allow non square island shapes these arrays will be extended and more arrays needed for other edges that will be required.

Going back to the main class we need to make some changes and use this new Island class to create our map.

// Lower speed to 1
int speed = 1;

// A new Class variable Island
Island island;

// Render Loop, clear BLACK, 0, 0, 0);

// draw code - loop chunks and draw tiles
// Draw all tiles in the chunk / chunk rows
for(ArrayList row : island.chunk){
  for(Tile tile : row){
    batch.draw(tile.texture, tile.pos.x, tile.pos.y, tile.size, tile.size);
    if (tile.secondary_texture != null) batch.draw(tile.secondary_texture, tile.pos.x, tile.pos.y, tile.size, tile.size);

There is no culling, all tiles will be rendered, this can be addressed when there are more chunks. With the changes the main gameclass running the app should produce a map that you can move around using the arrow keys or WASD:


In part 3 we will refactor the images into a new class and add our hero.

Remember to check out the full source code: [ Github Repository ]

Making a LibGDX Roguelike Survival Game Part 1 #gamedev

After failing to complete the 7 Day Roguelike challenge I was left with some working code for a simple pixel art game that had the basics that might help new game developers.

I plan on developing this game further, demonstrating some basic techniques and hopefully motivate people to make their own games.

source code for this post is available on Github

Screen Shot 2017-03-16 at 00.34.48

7DRL Game

To start you will need to download LibGDX setup application and generate a new project, there is information on getting setup on the LibGDX website. I will be using Eclipse Luna as my editor.

Here is my project setup, to keep this less complicated I am only launching this application on the desktop, I used a random name generator which came up with EvoScape.


Once you have created and imported your project into Eclipse (Gradle Porject) or your preferred editor run the application as a Java App, you should see this:


If you have worked with LibGDX previously I am sure you have seen this screen many times! There are only three files changed / created for this first part of the tutorial:

Add these two lines to the launcher so the game height and width are set:

config.width = 800;
config.height = 600;

Apart from the standard Texture and Spritebatch variables that LibGDX add as default these class variables are defined:

OrthographicCamera camera;
Control control;

// Display Size
private int displayW;
private int displayH;

// Temp x and y co-ords
int x, y;

// For Movement
int direction_x, direction_y;
int speed = 3;

Control is our own class used to handle keyboard input, the Orthographic-camera will handle the viewport, other variables are used to hold the screen size and some temporary values to track the position of the camera.

displayW =;
displayH =;

// For 800x600 we will get 266*200
int h = (int) (displayH/Math.floor(displayH/160));
int w = (int) (displayW/(displayH/ (displayH/Math.floor(displayH/160))));

camera = new OrthographicCamera(w,h);
camera.zoom = .4f;

// Used to capture Keyboard Input
control = new Control(displayW, displayH, camera);
Gdx.input.setInputProcessor(control); is used to get the width and height of the screen, we have set the screen size to 800 by 600 but we can allow the user to resize the screen or go full screen, these values can later be updated when the screen size changes.

There are many ways to set up the OrthographicCamera, depending on the type of game you may want different sized viewports, check the LibGDX wiki for additional information. It is also worth looking at the viewport options but for the moment this simple setup is fine. The camera also has the ability to zoom in/out.

Before looking at the render loop of the main game class lets take a look at

public class Control extends InputAdapter implements InputProcessor {

It is important the class that handles keyboard input extends and implements the above classes, the editor will ask us to add the unimplemented methods after we change our class to extent and implement the LibGDX classes, keyDown and keyUp are what we will use at this point. Using a simple switch statement the class booleans can be set or functions called when certain buttons are pressed/released:

switch (keycode) {
  case Keys.DOWN:
    down = false;
  case Keys.UP:
    up = false;

WASD and the arrow keys set the up,down,left, right values to true on press and false on release, these boolean values can be used to determine if movement should occur. Backspace is used to toggle debug, this will be useful for displaying collision hit-boxes and displaying debug info later on and esc key is set to exit the application. The other functions already added will be explained in another post.

Looking back to the file and the render funciton:

// Reset the direction values

if(control.down) direction_y = -1 ;
if(control.up) direction_y = 1 ;
if(control.left) direction_x = -1;
if(control.right) direction_x = 1;

camera.position.x += direction_x * speed;
camera.position.y += direction_y * speed;

batch.setBlendFunction(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);

batch.draw(img, 0, 0);

The render function is called 60 times every second, LibGDX defaults to 60 FPS. Here we reset the current direction in x (horizontal) and y (vertical) to 0, then given up, down, left, right are pressed (checked via the Control Class) the direction variables are set accordingly, the camera x and y positions are added to using the value and a speed multiplier. After changing the camera in anyway we have to call .update() for the changes to be applied to the camera.

The SpriteBatch projection is then set to that of the camera before drawing the default LibGDX logo, running the application you should be able to move the camera arond and exit using esc:


In part two we will look at creating a small island, using a simple chunk system.




Zero Hour Gamedev

I have been toying with Java game code for a few years now, entered a few game jams and started multiple projects that are all on hold, this has all been a learning expereince but it is time to create a game how ever long that takes! With a young baby to care for I only find the odd hour to write code.

I would like to make a top down shooter, inspired by retro games such as Chaos Engine, Universal Warrior, Micro Machines, GTA 1 but also newer titles like Nuclear Throne. At the moment I have the start of some systems; vehicle (7 types), lighting, chunk/map, player, inventory and time.

All the Gifs!

Box2D is a great 2D physics engine ported to LiGDX, I followed this tutorial to make a vehicle, well a box with 4 wheels that sort of acted like a car. Here you are seeing two scenes being rendered, Box2D’s debug renderer showing the outlines of bodies and also a separate 3D camera overlaying 3D objects:

I then created some vehicles to replace the debug lines, these are just concepts at the moment and need work:

I have never really played with 3D but as I only really need to use 3D as a visual overlay its not too difficult. I implemented a cube builder which creates a cube made up of many other smaller cubes, the function shown here generates a cube split by a random number, I considered a Minecraft style method of building the environment, tested out culling/caching models so this would run for large cities. Once I have a clearer vision for the style of the game then I can create some 3D objects and texture/skin them.

Damage is not currently visible but I have deferred the Box2D listener events to the car class collision object, this captures what was collided with and the speed of the collison. I then got carried away with Box2D joints and started to make all sorts of weird trailers and trains but only shared the caravan, it handles terrible but will have some purpose in the game:

Next I experimented with lighting, Box2D lights is simply to use and works well with Box2D objects had some fun revisiting trig to calulate the position of the light in relation to the car:

Not sure the lighting suits a pixel art game, I posted on Java Gaming for some advice with Nuclear Throne style lights, Orange Pascal the developer behind so many great games ( linked me to a tutorial he had posted, I have not really experimneted much with this but it works. There is a day/night cycle in place at the moment, I have to keep the 2D and 3D lighting in sync to achive this but that is pretty straight forward.

This is all I have at the moment, had a lot of fun prototyping, a long way to go but feel this is worth this is the type of game I would like to commit too.

It is ok to fail #7DRL

After noticing some Twitter friends were taking part in a seven day rogue-like challenge I decided to give it a go, knowing that I would fail from the start. I have a 6 month old daughter who takes up all of my time but I do have the odd hour to dev at night… rather than sleep!

My idea was a simple rogue-like, as you play and level up a random island that you start on grows in size and spawns new items and resources.

I created a simple chunk manager which only held one chunk; an array of tiles. Each tile has a texture(s) and also a box2D collision box. I decided to use box2D to manage the collisions rather than roll my own solution.

Found a nice Tileset on Open Game Art and started replacing water and grass tile placeholders; made a good start at using all of the tileset:

Made a start adding random items to the map (trees) and notifying the objects of collisions via box2D collision listeners:

Screen Shot 2017-03-16 at 00.34.48

Given I was only spending an hour or two each evening working on this I made some decent progress and made sure the code was clean and efficient, only actually managed 3/4 days out of the seven but am happy with what I got done and will work on this along side other prototypes.

I enjoyed starting a project from scratch and learning more about box2D collisions, there are some great tutorials available at iForce2D, worth checking out. There is no harm in starting something you know you will fail from the start given you learn by doing so.

Hacking my baby cam (Motorola MBP853)

Late August my daughter was born, I bought a wifi webcam to put into her room, one which boasted a feature packed mobile phone app for remote viewing, pan, tilt, room temperature and more.


The mobile app to control this webcam was broken from day one, the service did come back online a few days later and has worked quite well since but I had to question what I would do if the camera connectivity software failed.

I decided to find out how to use the camera as a dedicated IP device, there was no information from the manual or the supplier so I went digging.


Find the IP
My first step was to check my router maintenance page to identify the device IP address, this was the only unknown item in the list:

Screen Shot 2017-01-11 at 22.07.21.png

Using the Mac Network Utiliy I scanned the IP and discovered a web service on port 80:

Port Scan has started…

Port Scanning host:

Open TCP Port: 80     http


Test Page
After playing (tried a few obvious page names) about I discovered a file ““, this appeared to be a test page for the webcam, probably used at the factory to ensure the camera is fully functioning, although the video did not load I was able to move the camera, although the move function had no auto stop and the servo sounded like it might break!


Clicking the centre arrow stopped the camera from trying to over rotate, at this point I was a little worried that a page existed with full access to a camera which would be pointed at my child, all you needed was access to the local network.

Viewing the source of the page its quite easy to see the available functions and how to control the camera:

The send_command function code: AJAX_get(‘/?action=command&command=’+ cmd)

The video player which did not function showed us the URL required to watch the stream although it is hardcoded “rtsp://”.

Updating the IP I was unable to view the video as it was secured, I put the URL into Google and came across an article with much more detail about hacking the a similar Motorola camera

Wifi Setup
 It is possible to configure the network settings via wifisetup.html:

Screen Shot 2017-01-11 at 22.28.33.png

Viewing the Video on a Mobile

The article tells you that the video can be viewed if you pass the credentials: rtsp://user:pass@

The Real Time Streaming Protocol (RTSP) is a network control protocol designed for use in entertainment and communications systems to control streaming media servers. The protocol is used for establishing and controlling media sessions between end points.


Searching the Apple App Store for RTSP you will find several viewers, adding the correct URL to the app I installed on my iPhone made it possible to view the camera feed, while a username and password was required it was very insecure and every device would have the same config.


I now have a method to use and configure my webcam without relying on the Hubble software, this is especially useful when the service is down or if it is every pay to use.

The device needs to be made more secure, I will look into changing the username and password or contact the supplier to see if they will provide firmware updates, these test files should not have been left on the device.

I have the option to use the feed on a spare monitor in my study which will be useful or even produce my own apps.