# Lockstep multiplayer first steps

In this Gamasutra article, Tundra developers explain their approach to minimize problems when developing a lockstep multiplayer platform used for their game Rapture - World Conquest. Based on that, my first approach was to create and understand a deterministic lockstep logic without even considering networking yet, to focus on one problem at a time.

My objective is to have a reproducible game that given the start state and all the players actions during time, the game can be played again and the final state will be the same.

### Lockstep logic

The first step was start by creating a logic to encapsulate the fixed game state for physics and game logic, and a lockstep to perform player actions. As I started without considering networking yet, all the player actions are directly enqueued locally by the user input or by a saved replay.

A lockstep logic means that there are some conditions that, if not met, the game should pause the simulation and wait for them. In the case of multiplayer games this is when the game have to wait for other players actions that didn't arrive in time (and where the waiting for other players dialog is shown in some games).

My code looks something like this pseudo code:

update(dt) {
if (lockstepLogic.IsLockstepTurn()) {
return;
lockstepLogic.Process();
}
// normal accumulator logic for the fixed gamestep
}

Since I create all player actions locally, the lockstep never happens right now but it is a good practice to simulate and test it anyways.

### Testing it

My first prototype using this logic is a box that moves over the screen. When the right mouse button is pressed, the game enqueues a player action to move the box to the specified position, then when the lockstep logic is processed the box receives the command and start moving to that position.

### Interpolation

The moving logic was pretty simple, based on start and destination positions and a speed, the box moves itself to the destination in a straight line. Since that logic is performed in each fixed gamestep, the player see the box jumping between positions, it works but it doesn't look so good. To improve that and make the movement smoother I created a simple interpolation code.

Interpolation depends a lot on what you are trying to interpolate, in some cases could be a simple as the code I used there but there are other cases like the bouncing ball which need more data to create a better interpolation.

Note: adding interpolation means we have now a delay of one fixed gamestep between the box position being rendered and the real position in the game since we are using previous and current positions info for the interpolation.

### My first replays

By recording all the player actions with the fixed gamestep frame they were executed, I created a basic way to replay the "game" by just reseting the game state to the initial state and start enqueing all the recorded actions in each corresponding frame.

Here is a video of the progress so far:

Yeah, I know, it's not a great thing, but at least I am starting to understand some of the challenges of making multiplayer games.

### Validating simulation

To validate the game is always performing the same simulation given the same input, I added a checksum calculation based on the game state (for now just the moving box state) which is saved from time to time to use later as validation when simulating the game again. The idea was to start defining an API to get the important game state to consider when validating the simulation, and also to start testing game state validation. The code looks like this:

update(frame) {
if (IsChecksumFrame(frame)) {
if (recording) {
checksumRecorder.RecordState(frame, CalculateChecksum());
} else {
if (!checksumValidator.IsValid(frame,
checksumRecorder.SavedChecksums, CalculateChecksum())) {
throw Exception("current game state is not valid!");
}
}
}
}

In my first tests I wasn't reseting the game to the initial state properly so my game was producing different checksums when reproducing the saved player actions, checksums validation started to work after that was fixed.

How am I calculating the Checksum? Right now I am not sure exactly what algorithm to use nor which game state should I consider for the checksum, so what I did was to encapsulate that in some interfaces and implemented a basic way to get both. For the checksum I am using a simple MD5 over a string, and for the game state, well..., a string with all important values concatenated (the moving box position, destination, if it is moving or not, etc).

string CalculateChecksum() {
string gameStateValue = game.GetGameState();
return MD5.CalculateHash(gameStateValue);
}

string GetGameState() {
string gameState = "";
foreach (object in gameObjects)
gameState += object.GetGameState();
return gameState;
}

For a future implementation what I know is that the game state should be composed with important values that can affect the simulation, so I shouldn't care about about audiovisual stuff like particles, effects and sounds.

Also, the game state concept could be used to reset to the initial game state or even for saved game states (to easily replicate some bug for example), and finally, it could be used to synchronize and validate state if for some reason I end up using a client/server architecture.

### Next frontier: Determinism?

For now I didn't explore determinism realm because the solution really depends on the game logic but at the same time I must have it clear before starting the game code. One of the next steps is probably start testing with fixed point math, not sure yet, the idea is try to follow an approach similar to the gamasutra article's of reducing non determinism problem to the minimum before going multiplayer.

If you want to take a look all the code used for this blog post, here is the link.

Example of a dynamic lockstep implementation for Unity

Lockstep Framework for Unity

Reddit post about that Lockstep Framework

Another framework named lockstep.io

VN:F [1.9.22_1171]

# Exploring Remote Multiplayer

Some time ago I’ve started to prototype a multiplayer game, it is some kind of super simplified RTS game for mobile devices where macro decisions are encapsulated into one action through a button.

First versions were prototyped in a multiplayer hot seat fashion by using only one device (a tablet or a phone), that allowed me to quickly iterate between different ideas and find fun as soon as possible. That was a successful approach since the idea of the game proved that it was indeed fun to play with friends, so the next step was to go remote multiplayer with two or more devices.

Since networking is a whole new world for me, I started by reading lots of different articles about making multiplayer games.

The first thing to know is that the common solutions around depend on each kind of game, and knowing that beforehand helps you deciding the best solution for your game, and how your game must be adapted to support it.

In my case, I am developing a really simplified version of a RTS game for mobile, similar to Clash Royale. It is a 1v1 game where each player controls multiple units by giving high level orders like “everyone attack!” or “build new supply depot”.

The common networking approach for this kind of games, where synchronizing the whole world is a bit heavy given there are tons of units, is to do a synchronized simulation where only the main actions are transmitted (to save bandwidth) and each machine/device perform the same simulation. This implies the game should be deterministic in order to avoid desynchronization between players, so given one start state of the game and a list of actions over time, the final state should be always the same.

Making a game deterministic is a really hard problem, but it also has its rewards, like being able to replay the game given the actions of each player over time. This is a great debug tool for developers and at the same time a great freature for players since it is used to see other strategies or to share a great victory with your friends, everything with almost no storage cost.

The idea is to start writing my findings in the remote multiplayer journey to share all the lessons learned.

## References

These are some of the articles I read:

What every programmer needs to know about game networking

1500 Archers on a 28.8: Network Programming in Age of Empires and Beyond

Fast-Paced Multiplayer

Why adding multiplayer makes game coding twice as much work

Core network structures for games

Making Fast-Paced Multiplayer Networked Games is Hard

How to create an online multiplayer game with Unity

Networking in Unity

Creating a Cross-Platform Multiplayer Game in Unity

Understanding Fighting Game Networking

Desyncs and FPU synchronization

Cross platform RTS synchronization and floating point indeterminism

Minimizing the Pain of Lockstep Multiplayer

The Tech of Planetary Annihilation: ChronoCam

Synchronous RTS Engines and a Tale of Desyncs

Don’t Store That in a Float

VN:F [1.9.22_1171]

# What's going on with the Super Flying Thing?

On the last weeks I was a bit distracted working on Vampire Runner and with Mad Jetpack so I ended up kinda leaving Super Flying Thing abandoned, I also have some doubts about which features to work on so I preferred to dedicate time on other projects while deciding what to do with the game.

Super Flying Thing is really fun to me, I love the concept but right now the game could be a bit boring and I want to improve that, not so sure how, but I want to try some ideas I have in mind.

The main idea of the game is you have to master your flying skills and for that you have to try and fail a lot of times. For that reason, I want to modify the levels to be smaller and harder but not frustrating since you can quickly try again and again.

Random levels are now generated using pre generated tiles (I want to talk about this in a dedicated post), so they are a bit more interesting, however they don't transmit the idea of try and fail a lot of times yet, so I have to work a bit on level generation.

The practice mode will be removed since you can practice in both challenge and random modes. However, for starters I want to add a Tutorial where you can test the controls and learn how to play to mitigate the change I plan to do over the levels.

Also, we want to try an Endless mode where you have to go as far as you can, playing through different challenges each time harder and harder.

On some levels there are lasers, moving obstacles and even portals. Despite I love all this stuff, I will probably remove them until I see how they really fit in the game.

Stars will be probably removed as well since they don't contribute nothing to the game for now. Again, this will be probably temporary until it fits in the game.

On normal game mode, the main objective will remain the same, travel from one planet to the other. However, I want to add a second objective to add challenge factor to the game, something to make the player want to try again the same level several times. One possibility is to add some kind of local competition, for example, improve the time to reach the destination planet, play against your best time, or something like this. Going further with that possibility, maybe publish that replay/best score online and compete with others.

We have to dig further in this subject since it can contribute with re playability factor.

Now that we fixed the game behaving different on different devices I will rip off the AxisController and the TiltController and probably one more, and leave only the original one plus maybe some other.

The original control was modified a bit in order to let the player control the ship better based on how new levels are going to be.

### Conclusion

That's all for now, the idea of this post is to let you know that I want to to continue this game.

Hope you liked it, even if it has nothing interesting.

VN:F [1.9.22_1171]

# Archers Vs Zombies - Dev Log - 03

In the previous post, I was looking for a tool to edit game scenes information in an easy way. Talking with kevglass at LWJGL irc channel he told me he was using Inkscape for that purpose. I also read some time ago that Rocket Bear Games was using it for as level editor as well but I forgot about it.

Inkscape is very interesting for game development because it has a lot of useful features which you could use in different ways in order to achieve what you want. It works mainly with SVG files which are XML.

In this post I will comment some of the features I am using from Inkscape. As I am new with the program, feel free to correct me if I say something wrong about it or if there are better ways or doing stuff.

### Working with different layers

The editor lets you work with different layers. These layers will be exported as different groups which could be parsed later in your game to decide different behavior. In my case, I am using two layers for now, one to put the tools (some tiles) and the other one to define the game world, as the next image shows. This is to avoid processing the tools layer when importing the SVG into the game.

Archers Vs Zombies - Inkscape - Scene Editor

### Custom XML data

Also, as mentioned in the Rocket Bear Games post, Inkscape provides an easy way to add custom XML data to the file so you can add information you will need later to build the scene in your game. Right now, I am adding information to specify the tile type of each element so they could be correctly imported later in the game.

### Parsing the SVG

Parsing the SVG is not an easy task, each node contains a lot of stuff you have to parse in order to get all the information you need. Inkscape adds extra information with its own attributes like labels or the custom XML Data we said before.

Some time ago we used a tiny SVG Java parser named SVG Salamander to make the paths for Zombie Rockers .

I tried using it again to parse Inkscape generated SVG files but I couldn't force it to avoid trying to automatically load images when parsing the XML. The project doesn't contain good documentation about customizing behavior when parsing the file (maybe it even doesn't let you) and the page is a bit outdated, also SVN for the project was not working when I tried to reach it yesterday.

After that, I found Batik from The Apache XML Graphics Project. At first glance, it looked a lot better than the other one, also it is on Maven Central.

Using it wasn't so easy as I thought, I was using the latest version deployed in the Maven central repository but when I took a look at the online documentation it wasn't the same version, the examples were outdated. Another problem of the library is that it seems AWT dependent and that could be a problem if I want to use it on Android.

Also, there were no sources nor javadocs on Maven central so I couldn't explore the library to understand the behavior easily. I was getting a bit bored and anxious to have something working, so I left the library.

At the end, I am parsing the SVG by hand but I plan to give another opportunity to both libraries.

I will talk more about Inkscape and how I am using it in the next posts.

About the camera zoom I mentioned the last post, Rubén asked me why not using multi touch well known gestures (it seems natural), I thought about adding them but I remembered some people have single touch devices so they wouldn't be able to use the zoom feature. I end making a single touch implementation, however, I have the idea to implement both solutions in the near future.

VN:F [1.9.22_1171]

# Archers Vs Zombies - Dev Log - Controls

This post is an introduction and analysis of different type of game controls I am working in order to improve the game playability.

To control the bow I need to know basically the next stuff:

• direction or angle of the shot
• power
• if it is being charging or not
• if should fire or not

Each proposed bow control provides this stuff in its own way (using one or multiple touch, using the keyboard, etc). I will explain how each one achieve that, and comment some pros and cons I think they have as controllers.

### Type 1

Control type - Example 1

The player presses one position in the screen, drags the pointer to another position and then releases it to fire the arrow. The angle is calculated by the difference vector between the pointer pressed position and the pointer released position and the power is calculated by the length of that vector.

when pointer released:
vector p0 = pointer.pressedPosition
vector p1 = pointer.releasedPosition
diff = p0.sub(p1)
angle = diff.angle()
power = diff.length()

#### Pros

• It is supposed to simulate the movement an archer does when he fires a real bow

#### Cons

• turned out to be non-intuitive

### Type 2

Control type - Example 2

The player presses some point in the screen, drags the pointer to the position he wants and then releases it to fire the arrow. Optionally, the arrow could be fired in the moment the screen is pressed instead when it is released. The angle is calculated by the difference vector between the pointer position and the bow position, and the power by its length.

when pointer released:
vector p = pointer.releasedPosition
diff = p.sub(bowPosition)
angle = diff.angle()
power = diff.length()

#### Pros

• Easy to control and provides a way to shoot really fast

### Type 3

Control Type - Example 3

Similar to the others, the player pointer is pressed, dragged an released to fire the arrow. The angle is calculated by multiplying the y coordinate of the pointer position by a factor, and the power is calculated by the x coordinate multiplied by a factor too.

when pointer released:
vector p = pointer.releasedPosition
angle = p.y * c1
power = p.x * c2

#### Pros

• Easy to control too, when you want more fire power you move to the right, when you want less you move to the left. In a similar way, if you want to increment the fire angle move the pointer up, if you want to decrement it, move the pointer down.

#### Cons

• It is not clear the relationship between the angle and the y coordinate and between the power and the x coordinate

### Type 4

It is similar to the the first type but both positions are specified by two different pointers of a multi touch device.

vector p0 = pointer0.position
vector p1 = pointer1.position
diff = p0.sub(p1)
angle = diff.angle()
power = diff.length()

#### Pros

• We are taking advantage of multi touch device capabilities
• It is supposed to simulate firing a real bow
• By holding one touch you could press and release the other to fire arrows quickly

#### Cons

• Requires a multi touch device
• Multi touch feature doesn't work so well on some multi touch devices
• In devices with small screens using multi touch could require a lot of screen space, that means less space to see what is happening in the game

### Type 5

The idea is to modify the angle of the bow by touching up/down keys and control the bow power by holding space key, the arrow is fired after space key was released (could be another key mapping).

when up pressed:
increase angle
when down pressed:
decrease angle
when space pressed:
increment power
when space released:
fire and reset power to 0

Pros

Cons

• Hardware keyboard is required, it will not work on common android devices
• Could be a bit slow for the game I have in mind

## Conclusion

After working on different types of controls, I realized that the needed stuff to control the bow could be separated in sub controllers, one for the angle, one for the power and others. Using this approach, it will be easy to create mixed controls like, for example, angle is modified by the arrow keys and power by a relative pointer position to the bow, or make a controller like type 2 where the power depends on the pressed time instead the distance of the pointer position to the bow.

For touch devices, I want to try also HUD elements like slide bars and buttons to control the bow as some games does (Minigore).

Game mechanics are not defined yet. One thing to notice is that some controls will not work with a fast paced game where you have to shoot several arrows to kill incoming enemies, other controls will not work with slow paced games where you have to aim exactly where you want each arrow and more strategy is needed like, for example, deciding which enemy to kill first.

Some of the listed types will be implemented, plus an easy way to switch between them, so they could be tested. After that, I hope you could give them a try and tell me what do you think.

UPDATE:

I added to the latest development version (probably buggy) a way switch between different bow controllers by touching a button on the top right corner of the screen. For now, you have to discover yourself each controller 😀 (I forgot to put some controller label in some place).

VN:F [1.9.22_1171]

# Archers Vs Zombies - Dev Log - 01

I am working on a new game for Android and PC (Windows, Mac and Linux) platforms. The name of the game is not clear yet, for now is Archer Vs Zombies. It is being developed using Libgdx (using its box2d port for the physics), Artemis Entity System Framework and Animation4j. I want to be blogging about the game development progress, maybe some game design decisions and how I am using the libraries, stuff like that.

### Quick Description

An archer has to defend something (could be a castle, a house, people) from enemies (zombies, vampires, etc) which are coming to steal/destroy/kill/eat brains (yeah, they are bad) by throwing arrows to them. There will be waves of enemies and different levels with different landscapes.

Here is a video of the current status of the game, so you can visualize the concept:

note: something happened with the video, it should be finished after second 20.

Here are the features I will concentrate for now:

• There are enemies which comes to kill/steal/destroy.
• Add a movable target as the first enemy prototype.
• The player can control the bow power.
• Add feedback of the current bow power (probably add an arrow in the bow when charging which moves depending on the charge).
• Restrict bow power.

I already have some ideas to add more depth to the game but I want to explain them in further posts.

The game is open source (for now?) with the codename of archervsworld. Also I have a link here if you want to test the latest PC stable version, and here to test the latest Android stable version.

Hope you like it.

VN:F [1.9.22_1171]
Rating: 5.0/5 (1 vote cast)

# Dassault Dev Diary 3 - Collision Detection

The idea of this post is to share some techniques you could use in order to optimize collision detection in your game, but without implementation detail.

Sometimes when we are developing games, part of our logic could be based on the fact that two objects are in contact or not. In Dasasult, we want to know when bullets are in contact with other objects (for example: droids, scene obstacles or the level limits) and we want to know the area where a droid can walk.

Every object we want to check collisions has a position and a polygon shape defining its form in the collision space. Collision detection between objects is performed by checking collisions between their shapes.

The cost of our collision detection by now is heavy because we are checking collisions between all objects. If we increase the number of objects, then the performance is going to be affected. So, if that is the case, then we could have in mind some optimizations to improve it.

The first one is based on the fact that an object A collides with B then B collides with A and the same when not colliding. We could have a structure to mark whenever we check an object colliding with another object and then use that mark to avoid check the inverse collision. That will let us improve a bit because we will have only half collisions detection but with the cost of memory for the new structure.

The second one is to use bounding boxes for fast intersection detection. The idea is to avoid collision detection between game objects if their bounding boxes are not colliding. The most used shapes for this purpose are: Axis Aligned Bounding Boxes (AABB), Oriented Bounding Boxes (OBB) and Spheres.

For Dassault objects we used AABBs because they are really easy to build and work with.

Bounding boxes are really good when perfect collision is too heavy, but we have a new structure for each object and we have to update it whenever the object changes its position, size or angle.

Figure: droids and obstacles bounding boxes.

The third one is based on the spatial information of the objects to avoid intersection detection with objects far from each other.

Spatial structures are used for this purpose. The idea is to divide the space in zones so we could know in any time, for example, which objects are in a given zone or which zones contains a given object. There are several types of spatial structures: Grids, Octrees/Quadtrees, Binary Space Partitioning (BSP), Kd-trees, etc.

Note: these structures are commonly used for other purposes, for example, frustrum culling and networking algorithms.

For Dassault we used Quadtrees because we have some knowledge of them and a partial implementation to start with, also they work fine with AABBs.

When using spatial structures, we could improve a lot the performance because we can avoid to check a lot of collisions, but also we are growing in the information to maintain and we should be aware that each time an object moves we have to update in which zone is it now. Each spatial structure has its own pros and cons for different cases, you should have them in mind when choosing one for your game.

The next example show a possible use of spatial information (using grid partitioning):

Figure: example of objects in different zones

If we take a look at the image, we have object 1 in zone A and B, object 2 in zone B and object 3 in zone D. In one moment we would like to detect collisions for object 1, then we check collisions only with objects in zone A and B, that is, object 2.

After you decided the spatial structure to use, collision detection could be performed like this:

for each object in my zone {
colliding = false
if (getStoredCollision(me, object) != null)
return getStoredCollision(me, object)
else if (collisionBetweenBoundingBoxes(me, object) == false)
colliding = false
else
colliding = perfectCollision(me, object)
storeCollision(me, object, colliding)
return colliding
}

Conclusion

The solution we used worked as we thought and let us to improve a bit the performance of the game. However, the current implementation could be too featureless based on your game requirements, sometimes you need more information from collisions like the points of contact, the movement direction of each colliding object, the normal vector of the contact points for each object, etc. If you want that stuff and more you could use a physics engine, for example, Box2d or Bullet Physics Library (both libraries have Java ports).

Well, hope you enjoyed the post, feel free to make a comment if not.

VN:F [1.9.22_1171]

# Dassault Dev Diary 2 - Animations

As I said on the last post, I want to talk about how animations were implemented in Dassault.

In the original game, droids are animated using one image for each frame of the animation. Those images could be all in a single file or not. Here is an example of an animation:

This solution could be expensive for Dassault because droids are rendered in several layers, so to animate a droid we need to animate each droid's layer.

Another solution, and the one used in Dassault, is to separate the droid in parts to create a hierarchy and then animate those parts by moving them inside the game.

For Dassault, the droids are separated in three parts, the body and the two legs:

And here is an example of how the parts are related to the droid:

droid {
body {
position (0,0)
}
leftleg {
position (-5,5)
}
rightleg {
position (5,5)
}
}

Where each part position is relative to the droid's position.

To perform the animation, given a specific time, we calculate the value of a property by interpolating the values of two key frames.

For example, we could animate the value of the position of the leftleg part by specifying that on 0ms it should be (0,0) and on 100ms it should be (0,-10) so, when the time is 50ms the position would be (0,-5).

Here is an example of how the animation could be specified:

walk {
body.position {
time 0 (0,0)
time 200 (0,-5)
time 400 (0,0)
time 600 (0,-5)
time 800 (0,0)
}
leftleg.position {
time 0 (0,0)
time 200 (0,-5)
time 400 (0,0)
time 800 (0,0)
}
rightleg.position {
time 0 (0,0)
time 400 (0,0)
time 600 (0,-5)
time 800 (0,0)
}
}

And here is a video showing how it looks inside the game:

This example shows how to animate positions, with the same ideas you could animate an angle, colors, alphavalues, etc.

Next time, I want to talk about collision techniques used for Dassault.

VN:F [1.9.22_1171]

# Dassault Dev Diary 1 - Using layers to compose images

Dassault is a game I started for the Game Jolt Demake Contest and it is based on the excellent game Droid Assault from Puppy Games. The contest is already finished but I will keep working on the game with the purpose of learning some techniques (some of them based on the original game) and to share my experience in doing so.

In the original game, the droids are rendered with two different colors if they are from player's team or not, this is an example:

For Dassault I wanted the colors to be based on each team's color but when having a lot of teams I don't want to have one sprite sheet for each one and I don't want to limit the teams quantity beforehand.

One solution is to have a base sprite sheet and then color it with some script, to generate a lot of sprite sheets. One problem is that it requires a lot of files and that I have to regenerate all of them if something has changed in the base sprite sheet. Also, the number of teams cannot be changed during the game.

Another solution, based on this post from Puppy Games Blog, is to render the droids in several layers, each one with its own color. With this approach, I can paint some layers with one color and the others with default color to make them look just the way I wanted. Here is an example:

++++=

Now coloring some layers:

++++=

That was the solution used and it worked right. Inside the game we render the layers in order, to produce the correct result.

To design the images in several layers we are using Gimp. I try different color palettes to see how they'll look inside the game. Then I save the layers in gray scale exporting each one in a different image file using Export Layers as PNGs python plug-in for Gimp. The images are ready to be colored inside the game.

Here are some screenshots showing how it looks inside the game:

And here you have a video:

You can try the game here. That's all for now, next time I am planning to talk about animations.

VN:F [1.9.22_1171]