Game Development

behavioral pattern, Design Patterns, Game Development, OOP, Programming

Design patterns: State

Hi guys, I made a decision to see a different category of design patterns and this category is behavioral design patterns.

What a behavioral design pattern is. The text following is from Gang of Four.

Behavioral patterns are concerned with algorithms and the assignment of responsibilities between objects. Behavioral patterns describe not just patterns of objects or classes but also the patterns of communication between them. These patterns characterize complex control flow that’s difficult to follow at run-time. They shift your focus away from the flow of control to let you concentrate just on the way objects are interconnected.

So, today we will see the State design pattern.

What a State design pattern is. The text following is from Gang of Four.

Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

The state design pattern is one of those that is used widely in game development. It helps us to describe the different states of a game-changing object’s behavior but keeping objects loosely coupled.

For example, we have a character who is able to jump only if he is standing and not sitting, and he is able to sit only when he touches the ground.

If we try to implement this character’s behavior we will come out with a code of full “if,elseif” and multiple complex conditions that make our code ugly.

Let’s try to add some functionalities to our character, he is able to shoot only if he is standing or jumping but not when he is sitting.

As you can imagine our code is already quite complex and unwieldy in order to find a quick and easy way to add this functionality.

So, the code’s maintainability is almost unattainable, and also there are many bugs and unpredictable behaviors hidden.

For this reason, the State design pattern helps us to simplify our code. The code will be more readable and maintainable.

Let’s see the next example

Example

We will have a character with a gun. There will be 2 different behaviors of the gun. In this example, we will see only the gun’s behaviors.

So, the gun has 2 states. In the first one, the gun is loaded with ammo and ready to fire, and in the second one, it is empty of ammo.

Let’s start to design the code using the State pattern.

Interface GunState

Now, we will create the 2 classes that implement the GunState interface. ShotGunHasAmmo & ShotGunHasNoAmmo.

Finally, we implement the GunContext class in order to see a changed behavior when it changes state.

Run The code

Output:
Shotgun is in has ammo state
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Shotgun is shooting. Left Bulets 0
Shotgun is in empty of ammo state
Shotgun is empty!
Shotgun is empty!
Shotgun is in has ammo state
Shotgun is shooting. Left Bulets 3
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Append 2 bullets in Shotgun
Shotgun is shooting. Left Bulets 2
Shotgun is shooting. Left Bulets 1
Shotgun is shooting. Left Bulets 0
Shotgun is in empty of ammo state
Shotgun is empty!
Shotgun is empty!

You can download the source code from GitHub.

Android, Game Development, Java, LibGDX, scene2d

LibGDX: Scene2d – Actors Part 1

Scene2d is a higher-level framework for creating games. It’s not mandatory to use it but sometimes it is very useful because code is more friendly and simpler. It is indicated for menu, buttons, checkboxes, etc. but it’s useful for board games, character’s equipment, and more.

Scene2d is composed of 3 classes regarding Scene2d :

  1. Actor: The Actor class is a node in the graph which has a position, rectangular size, origin, scale, rotation, and color.
  2. Group: The Group class is an actor that may have child actors.
  3. Stage: The Stage class has a camera, SpriteBatch, and a root group and handles drawing the actors and distributing input events.

The stage is a container that has and handles actors. Also, it has an action method that takes a delta time as an argument and it calls the act method of every Actor, allowing the actors to take some action based on time. As you can see act method is something like the update method that we already know.

The constructor of Stage class accepts only 2 arguments, Viewport and Batch. It doesn’t need to pass the camera because Viewport handles the camera internally. The batch argument is optional as well. The Stage class handles batch internally.

So, it doesn’t need to dispose of Batch manually because the stage will. That’s only in the case that we let Stage object to handle Batch alone. On the contrary, if we pass Batch as an argument in Stage then we have to dispose of it manually. As a rule, it’s better to let Stage object to handle batch alone.

Also, it doesn’t need to use setProjectionMatrix or batch.begin() or batch.end() manually because the Stage handles these automatically.

As a result, we have a more simple and maintainable code.

Sample Code

We will see an example with the Actors. We will start with class MyActor which “extends” Actor.

The constructor of MyActor class takes 2 arguments, a Texture and a String. Also, in the constructor, we set an event using addListener for our Actor. In case the Actor is touchable, we have to set it with the following line.

A very important notice is to call setBounds() method with the right arguments.

In this example, spritePos() is where the sprite position is changed and setBounds() method is called.

The next step is to pass our actors in Stage. Take a look at the following code.

As you can see, we have to pass Viewport as an argument in Stage and actors using addActor() method.

[fun_fact]If you don’t know how to use AssetManager & AssetDescriptors take a look in LibGDX: AssetManager[/fun_fact]

In render() method:

The act method isn’t needed in our case because we don’t use Actions in this example.

If we run the code we will see the following output:

scene2d_actor_example

Clicking each asset, we will see in console the following output:

Touch down asset with name : images/character.png
Touch down asset with name : images/null.png
Touch down asset with name : images/skeleton.png

The stage can handle events right and when we touch down any of the assets an event is triggered.
You can find the LibGDX source code in LibGDXExamples!

Design Patterns, Game Development, Java, OOP, Programming, Software Engineering

Design Patterns: Dependency Injection

What Dependency Injection is. Let’s imagine an object that does a specific function. Now let’s imagine a second object that takes the first object as an argument. This object cannot function or can function partially without the first one. When this happens, it’s called Dependency Injection.

Dependency Injection is a design pattern and we want to use it when an object is dependent on another object. Doing that, we are able to enhance our code with new functionalities without changing the existing code. So, our code is maintainable and extendable while allowing our program to be loosely coupled.

There are 3 ways to perform dependency injection.

The first one is called Constructor Injection. In this case, the class takes the dependent object through the constructor.

Sample Code:

Next is Setter Injection. In this case, a class that needs an external object to work takes it from a setter method. Thus, we can pass the dependent object as an argument only if there is a need for that. Dependency Injection is optional in this case.

Sample Code:

The third one is called Interface Injection. In this case, we create an interface class that has a function that takes as argument an object.

Sample Code:

Sample Code

It would be better if we continued with an example of how to use dependency injection.

We are going to create a character for a game who is modular and we can change various things like hair color, t-shirts, head size, etc. In our case, we will see only the head size as an example. So, the user will be able to change the character’s head to a big one or a regular one.

Let’s start with our interface class which is named Head.

The next two classes will implement the Head interface creating either a big head or a regular head.

The next step is to create a player who is going to take an object of BigHead or RegularHead classes as an argument.

Let’s start with the Player interface.

The class above implements the Player interface and it creates a player either with a big head or with a regular one, depending on the class that it will take as an argument.

Finally, we will create one more interface that we will use in order to implement Dependency Injection.

As we can see, each one of the two classes above creates a Player object depending on the argument.

The last method does a print in our screen.

Output:
Hi, I am the player with a big head !
Hi, I am the player with a regular head !

You can download the source code from GitHub.

Some Other Useful Resources

http://fabien.potencier.org/what-is-dependency-injection.html
https://www.martinfowler.com/articles/injection.html
http://www.procata.com/talks/phptek-may2007-dependency.pdf

http://www.javacreed.com/why-should-we-use-dependency-injection/
http://tutorials.jenkov.com/dependency-injection/dependency-injection-containers.html

creational patterns, Design Patterns, Factory, Game Developer, Game Development, Java, OOP, Programming, Software Engineering

Design Patterns: Factory

The factory is one more design pattern that comes under creational patterns. Thus, this pattern is able to make our code less complex and it gives us the opportunity to get an object without using the “new” operator. The factory is quite simple in use.

The factory is used when there is a need to hide the way that an object instantiated and it’s complex or many dependencies are needed.

Also, as Head First: Design Patterns book refers

[quote name=””]Instantiation is an activity that shouldn’t always be done in public and can often lead to coupling problems.[/quote]

You can read more about this subject in the resources below.

javaworld.com

Head First: Design Patterns

Design Patterns: Elements of Reusable Object-Oriented Software

In other words, using the factory, different types of objects can be created and returned without using the “new” operator or be interested in how this object can be instantiated.

Through factory class, an instance of another class can be taken.

Sample Code

Let’s start analyzing the code below. We are going to create a character who is able to use a gun or his punches. So, we will start implementing these classes. At first, we will create an abstract class for Gun.

Next 2 classes extend from Gun abstract class. ShotGun and Punch classes.

Now we are ready to create our character with ActionFigure class.

In case that, we use constructor without any argument then our character is going to use Punch class.

Last but not least, we will create factory class that returns the desirable figure to us.

This class contains 2 functions, the first returns an instance of ActionFigure without a gun and the second with a gun.

Also, this design pattern is called Static Factory due to the static functions in factory. The advantage is that we don’t have to instantiate the factory in order to use createFigurePunch() and createFigureShotGun() functions.

The drawback is that we are not able to subclass and change createFigurePunch() and createFigureShotGun() functions behavior.

In continuing, we call and get desirable instances from factory using the code below.

Output:

Action figure without gun created!

Figure is shooting : Punch

figure is shooting 3 times :

Punch

Punch

Punch

Action figure with gun created!

Figure with gun is shooting : Gun is shooting. Left Boolets 2

Figure with gun is shooting 3 times: Gun is shooting. Left Boolets 1

Gun is shooting. Left Boolets 0

Gun is empty!

Figure with gun is shooting : Gun is empty!

Figure with gun reloads gun: Figure with a gun is shooting: Gun is shooting. Left Boolets 2

Conclusion

To sum up, factory is a design pattern easy in use and simplifies the code’s complexity a lot. Using “new” operator is definitely a bad approach and we have to avoid using it. Factory helps to write a more clear code with less bugs.

You can download the source code from GitHub.

creational patterns, Design Patterns, Game Development, Java, OOP, Software Engineering

Design Patterns: Prototype

The prototype is a design pattern that belongs in the “creational patterns” category. This pattern is used in order to avoid the usage of “new” operator, especially in the case there is a need to create new objects at run-time.

So, there is the possibility to clone an object instead of using the “new” operator in order to get a new object. This new object is very different from the initial object, but the new one keeps the state of the old object.

To be more precise, before cloning an object, we have to create one. That means we have to get an instance of the class using the new operator as it’s already known. Continuing, we are ready to get more instances of the object just by cloning it.

In order to clone an object, the object must always do implements Cloneable interface.

The advantage of using cloning is less costly than creating a new one with a “new” operator.

Also, an object which is Cloneable is able to be cloned every time during code execution. Usage of Cloneable is suggested on this occasion and can improve the execution time.

Equally important and useful is when a class consists of more than one state. So, it’s preferable to create instances for every single state and clone each one of them instead of using the “new” operator.

Continuing, we will see an example of using a prototype design pattern. You can download the source code from GitHub.

Prototype Example

We will use the same example that we used in Object Pooling design pattern.

So, we will have a class that it’s going to create a dot.

This class is named DotPrototype and implements Cloneable Interface as I said earlier.

You can see the source code of DotPrototype below.

As you can see this class takes only two arguments which depict a dot. Also, it accepts the dot’s color.

At the end of the class, there is a function named clone() which gets overridden.

This function calls parent function clone() returning a new instance of an object. In case that class doesn’t implement Cloneable interface then we get an exception message.

The next step is to create another class and we will implement all states of the DotPrototype class there. And we will put these states in a Hashtable in order to get one, easily and fast.

We are going to create 3 instances of DotPrototype and each one will have a different color. So, Hashtable is going to keep 3 instances, red dot, yellow and green dot.

Source code of DotSpawner

After that, we have to initialize DotSpawner class giving the command below.

DotSpawner is a static class.

We are almost ready, the last thing that we have to do is to call getDot(“Color that we have instantiated”) to get the desired instance and call clone().

So, we get a new different object but with the same state.

Output : 

prototype design pattern

Conclusion

In order to use the clone method, the class must implement Cloneable interface.

It’s useful to use a prototype pattern when there is a need to create new instances of an object during execution time. Also, when a class has many states to implement.

Using clone is faster than using the “new” operator.

Last but not least, you can see the resources below that I found very useful.

gameprogrammingpatterns.com

sourcemaking.com

oodesign.com

wikipedia.org

Android, Game Developer, Game Development, Java, LibGDX, OOP, Programming

LibGDX: AssetManager

Assets are one of the most significant and demanding things in a game. Images, music, sounds, fonts, skins are only some of the reasons that a game may respond slow and have bad behavior if they are not set up correctly.

It is acceptable to have a small delay while the assets are loading before the game starts, but from the time that the game has started, we do not want to have a lag or a delay. If so, then we face the danger of losing our users because the game becomes frustrating to them.

So, we must be very careful on how to handle our assets in our game. It’s not the only thing that we have to take into account when we develop a game but it’s sure a very important one.

It is a heavy process creating new objects at run-time, so, if we need to create new assets and dispose of some others then we face the danger of having lags or our game freezing.

We have to be very careful when we use the keyword “new” at run-time. For example, the LibGDX framework loads an image with the code below

Creating new objects is costly and has negative consequences in run-time gaming. Generally speaking, it is a good habit to evade having big constructors, synchronization calls during object construction. Instead, we can use Weak References.

Also, there are some design patterns like object pooling and prototype which we can use in order to avoid using new” keyword so as to generate new instances. You can take a look at these design patterns here and here.

Back to our subject, LibGDX provides us with the right tools to handle and use assets as efficiently as possible.

One of these tools (class) is AssetManager. It’s only a very useful class that helps us handle our assets. Every single one of the assets is loaded in memory once and we can use them as many times as we want.

It’s the best way to handle images, music, sounds, and more. Also, you can read why and how to use AssetManager in LibGDX documentation.

  • Loading of most resources is done asynchronously, so you can display a reactive loading screen while things load.
  • Assets are reference counted. If two assets A and B both depend on another asset C, C won’t be disposed of until A and B have been disposed of. This also means that if you load an asset multiple times, it will actually be shared and only take up memory once!
  • A single place to store all your assets.
  • Allows to transparently implement things like caches.

AssetManager usage is simple enough.

The first line makes a new object of AssetManager. The second line puts the image myImage.png which is a texture in the queue.

From the time we call finishLoading(), we start the loading process of the assets. The whole program is blocked until all assets are loaded.

Caveat. Method manager.load(“…”); doesn’t load any asset, instead, it puts every asset in the queue and when we call finishLoading(), it starts loading the assets.

Method get() returns an asset and we use casting in order to set image variable with an image from the manager.

Attention! Don’t use AssetManager as static.

According to the documentation, it is bad practice to use AssetManager as static due to the different lifecycles of a static and Android Activity. This approach may lead to bugs and memory leaks.

There are two ways to load assets using AssetManager. We have already seen the first using finishLoading() function. The second is update() method. Using this function we have a better control when assets are loading. We can use it with the function getProgress() which returns a percentage of loading.

Take a look in the next example of code

It is worth noting that we don’t need to use dispose() in each Texture or any asset AssetManager handles. The code is more elegant and we don’t need to write too many lines so as to dispose of each asset individually.

This whole process is very useful and a big improvement during code execution. It’s a big improvement when we have to create new instances of an asset in run-time.

Drawing With AssetManager

Continuing, we will see how we can use AssetManager with a good structure. Also, we will draw some images on our screen.

Starting with class Assets and we will declare the images paths.

AssetDescriptors

We can use get(“asset name”) method in order to get the asset and use it. It’s not the best practice, in case we want to change an asset with another one. Then we have to change each one point that we have already declared.

Another reason is when we just have a single string in get() we cannot be aware of what type of asset the get() is going to return.

So, LibGDX offers AssetDescriptor which handles situations like that.

LibGDX API Class AssetDescriptor<T> describes an asset to be loaded by its filename, type, and AssetLoaderParameters. Instances of this are used in AssetLoadingTask to load the actual asset.

Now we are ready to create a class named AssetDescriptors and we will declare every asset.

The next step is to create the right code in order to load assets in AssetManager and draw these assets on screen.

At this point, we are only going to see and analyze AssetManager and not the camera.

As we can see in the constructor we create a new instance of AssetManager.

Show() calls loadAssets() function. This function sets assets in a queue and after that, it calls finishLoading() function which blocks everything until all assets are loaded.

After that, we are ready to use all assets that are loaded in AssetManager.

Now we are ready to draw images (our assets) inside render() with the standard way, using batch.

You may have already noticed that in dispose() function we don’t dispose of every asset as we used to.

We just have to dispose of manager and all assets will be disposed of by the manager. Nice!

Using AssetManager with update()

In order to use update() method we have to remove the line below from loadAssets();

and add the code below in show() function after loadAssets() call.

You can find the whole source code in the file AssetManagerUpdateExample.java

AnnotationAssetManager

AnnotationAssetManager is another tool that comes with libgdx-utils library. It is a tool that simplifies the whole situation even more. As you can imagine we will use annotations.

Before we start we have to add the following lines in gradle file in order to download libgdx-utils library.

Now we are ready to go!

We will need one more class named AssetsAnnotation and we will use @Asset() in order to put assets in the queue. So, we don’t need to write the same code twice.

You may have already noticed that loadAssets() function is just 2 lines. We don’t need to load every single asset anymore, we just need to call AssetsAnnotation class.

Outputassetmanager examples

You can read more about AnnotationAssetManager here!

Conclusion

It is suggested to always use AssetManager in order to handle and load assets. In that way, assets are loaded once in memory and we use them as many times as we want.

Assets don’t need to be disposed of one by one. Instead of that, we just dispose the manager.

Also, it’s easy to handle our assets because they are located in one place.

The outcome is a more compact and elegant code and this leads to cleaner code. Also, there are fewer places to hide a bug.

It’s the best solution in case we have to create “new” instances of assets at run-time and not only!

You can find LibGDX examples in GitHub!

creational patterns, Design Patterns, Game Development, Java, Object Pooling, OOP, Programming

Design Patterns : Object Pooling

Object Pooling is a design pattern that belongs to creational design patterns. Creational design patterns are the ones that deal with object creation mechanism. This gives the program more flexibility in deciding which objects need to be created for a given use case.

Design pattern object pooling gives us the ability to load some instances before any object, so we are able to borrow any of the pre-loaded instances from the reusable pool class.

Using the keyword new to create multiple instances of the object every time, is costly. This cost is related to the time a new instance needs to be created.

The fact that we are able to borrow some instances of an object and return them back to the pool when we don’t need them is very useful.

Object pooling is usually used in games. For instance, in our game, there are some characters who have a gun and shoot. Every time that we use the keyword new to create a new bullet our game is becoming slower and doesn’t work as we would expect.

So, in this case, it is not only the right decision to use object pooling, but it’s mandatory.

Also, it’s a good practice to use it in our characters and some other points of our game.

Now we are ready to see a simple example of object pooling usage.

Using Object Pooling

Our game is simple, the user has to connect the dots so as to make something known to us, like an elephant, a man, flowers e.t.c.

The game is going to have a lot of levels, so, that means we will create and destroy dots all the time. So, it is a great chance to use object pooling pattern.

Let’s start with the Dot class.

As you can see this class creates only a dot. The code below creates the dot.

circle = new Ellipse2D.Float(posX, posY, radious * 2, radious * 2);

Additionally, a function named isColliding() checks if this dot intersects with a line.

The next step is to create an abstract Pool class. You can see the code below.

The constructor calls method init(). This method initializes the object with instances of Dot class.
Method addObj() is an abstract function. Also, there are 2 more methods, method size() returns the size of the object and the second removes all of the elements from objects.

DotPool class is extended by an abstract Pool class. Let’s take a look at the code :

Method addObj() adds a new instance in objects.

Method get() returns an instance of Dot if it exists, otherwise, it creates a new one. Also, it is a good practice, if there is not any available instance, to wait to get back one instead of creating a new one.

Method free(Object o) returns an instance to objects.

Last but not least, the Main class.

OUTPUT:

And this is the window that our code produces.

object pooling dot window

As you can see, Pool starts with 2 instances of Dot class. We get one instance and  1 remains in Pool. We get one more instance and we can see that size of the Pool is 0.

In the next step, we release the second instance back to the Pool, and Pool’s size is 1 again.

After that, we ask 2 more instances from Pool, but only one exists. So, Pool will create a new instance.

Now we release all the instances back to the Pool.

As you can see, Pool starts with 2 instances but in the end, it has 3. This has happened because we asked 3 instances and get() function is able to create a new instance if there is not any in Pool.

You can find the code in my GitHub account.

If there is any mistake or you have any questions, please let me know.

If you want to read more about creational patterns and object pooling you can read these books Design Patterns: Elements of Reusable Object-Oriented Software and Game Programming Patterns.

View More