# A* Pathfinding In Game

I wrote a post on implementing a simple A* Pathfinding algorithm a couple months ago. When I went to add it to my game I ran into some interesting differences I wanted to write an update on.

Here is the algorithm working on my game server. Both player and NPC are red blocks. When the player is within viewable range of the NPC, the NPC will start chasing it.

The pathfinding algorithm allows the NPC to maneuver around blocked tiles.

## Coordinate to Tile Mapping

One thing I discovered while incorporating it into my game was my simple example had a 1:1 coordinates to tile ratio. Coordinates 0,0 was the first tile, and 0,1 was the second tile. When tiles were 16×16 pixels, the coordinate to index mapping broke.

To address this, I needed to pass  map width and map height in tiles, as well as the tile size so it was known when a new row started and the bounds of the map.

I did this by creating a map struct that contained the width, height, size, and pointer to the tile vector.

```struct GameMap {
GameMap() {}
GameMap(int _map_width, int _map_height, int _tile_size, std::vector<unsigned int>* _tiles) : map_width(_map_width), map_height(_map_height), tile_size(_tile_size), tiles(_tiles) {}
int map_width = 0;
int map_height = 0;
int tile_size = 0;
std::vector<unsigned int>* tiles;
};```

# October Development Progress

This is the first of my weekly reviews. I’m starting this to help keep track of what I’m doing and and to set forward goals.

The past two weeks have been a mix of new and old projects, including business-oriented project planning web applications, a World of Warcraft data sync, and two game development projects.

## Asana Features

I use Asana to manage my teams tasks. Asana is very simple and flexible, but is missing some features we need to keep track of our sprints and better organize our tasks and Kanban board.

Sprint Reporting

One of these missing features is a burndown chart based off of effort estimation. I’ve been building out our own burndown chart in an Electron app using Google Charts to display the statistics and feeding in the task data from Asana using their API. At this time I’ve got the chart but also a break out of the effort we’ve committed and the effort we’ve knocked out.

This has already proven to be really helpful, as we now have an easy way to track our progress and see the sum of effort completed at the end of the week.

Asana Bot

Asana supports custom fields, but doesn’t allow us to make them required. Requiring the effort estimation for a new task would be ideal. In addition there are a few other events where I would want additional info provided, such as when a task is labeled as blocked, a due date is passed, or a new task is added to the sprint.

To solve these problems, I’m building out a Slack chat bot using the Botkit framework. So far I’ve been learning the ropes of what the chat bot can do and building out the groundwork.

# Global Game Jam 2018

Global Game Jam 2018 took place at the end of January. It was hosted locally here in Sacramento at Square One Clubs. I participated as much as I could, but unfortunately I had some family obligations that prevented me from making it down to the site.

For my game, I created a first person puzzler in a 3D world. I used it as an opportunity to get more familiar with Blender and Unreal Engine. With this being a learning experience, I didn’t get as far as I would with tech I was already familiar with. Overall, it felt like a success. I am now much more comfortable making shapes and applying textures in Blender. I also learned what is lost while exporting a blender project into Unreal, such as shaders that are closely tied to the rendering engine.

Alright, so lets take a peek and go over some stuff!

My game takes place in a testing grounds with various platforms and standing orbs. In this first iteration, it takes place in space, but after building out the platforms that idea didn’t seem to pan out so well, for reasons I’ll go into shortly. The skybox texture was created using a premade texture from SpaceScape, a free tool for creating space skyboxes.

Unreal is a very powerful engine with some very useful tools in prototyping a scene. You can create shapes in the scene on the fly. Unfortunately (at least as far as I know) those custom shapes, known as brushes, are their own object type and I couldn’t find an easy way to convert them into components for reuse. I imagine it’s possible, the answer just wasn’t easily at hand. I created the octagon platforms and the orb with stand using brushes.

# Out of Phase: Race Conditions and Shared Mutexes

This is part of a series for the Out of Phase game project that reflects on various stages, covering pros and cons of the creative process and implementation of the game.

Last year I started porting over the backend of my game from Python to C++. The reason for this move ties into my long-term goals as a game developer. Programming a multiplayer server has been something that has intrigued me for a while. The idea of creating a virtual environment that is continuously running and allows multiple players to interact with that environment in real time is fascinating to me.

At this time, my game will only support two players, but I would like to play around with adding more.  I’m doubtful this will be a massively multiplayer game, like World of Warcraft or Elder Scrolls Online, since that would be a huge amount of effort. So maybe up to four players.

Real-time games that support multiple players typically require some special handling of synchronizing the game state as it is updated from the player’s clients. Without synchronizing, race conditions will occur which will result in erroneous and unpredictable ways.

So in this post, I’ll be covering how to avoid race conditions in C++ threads by using locks and mutexes.

### Race Conditions

Let’s take a code snippet as an example (this is make believe pseudo code):

```void attackGoblin(Monster* goblin) {
int health = goblin->getHealth();
health -= 10;
goblin->setHealth(health);
}```

Race Condition 1

Ok. So the problem here is what happens when two players are attacking this goblin at the same time. Just because this code is wrapped in a function, doesn’t mean each block of code gets executed sequentially. It’s possible that the lines of code being run between each player may be executed in a mixed order.

Let’s assume that goblin->getHealth  and goblin->setHealth  read and write the current health value from or to memory. (But they don’t use synchronization)

Two players are attacking a goblin with 500 health. Both players inflict 30 damage at the same time. We expect the goblin’s health to drop down to 440, but instead, it only drops down to 470. What happened?

```(thread 1) int health = goblin->getHealth(); // getHealth returns 500
(thread 2) int health = goblin->getHealth(); // getHealth() returns 500
(thread 2) goblin->setHealth(health); // Goblin health is now 470
(thread 1) goblin->setHealth(health); // Goblin health is still 470```

Where did the damage go? Well, it got overwritten because the instructions weren’t synchronized. Each thread keeps a separate copy of health and when the goblin’s health is changed in one of the threads, it never updates in the other.

# RPG Slots Progress – Cocos2d Review

I started developing a slots game using the Cocos2d C++ SDK. Cocos2d is an opensource game development framework that support C++, Objective-C, and JavaScript. Eventually, this game will evolve into a slots RPG, like King Cashing and King Cashing 2. For now it uses a pretty generic reels and a match 3 mechanic that matches on the same row as well as cells on adjacent rows. For score, it keeps experience points, since this will transition to the RPG slots.

Source for the project can be found here. As of this writing, it’s in early development.

Like many game frameworks, Cocos2d has many helper functions that allow for quick game prototyping. Scenes are easy to construct, and assets, sprites, and audio can be added using built in Cocos2d objects. It even supports the ability to add custom shaders.

### Extending Sprites

I found quickly that I needed to create custom objects that extended sprites. In this project there two classes that extend cocos2d::sprite ; the reel, and the HUD.

Grouping elements within sprites helped with organizing code and separation of concern. I did run into strange memory errors when trying to add certain objects, such as cocos2d::Label , directly to the scene while also having a pointer to it in the scene.

Autorelease

The Cocos2d C++ framework uses a smart-pointer technique to automatically destroy dynamically allocated objects when its internal reference count is 0. This relieves pressure in remembering to destroy objects and worrying about pointer ownership. Though cyclical dependencies still need to be avoided.

The built-in Cocos2d objects are automatically added to the autorelease pool, so there is no need to use the new  keyword. In my project, I have an object that extends the Cocos2d sprite. So there’s some boilerplate code that I needed to add so my object would be added to the autorelease pool.

```ReelSprite* ReelSprite::create(const std::string& filename, std::vector<int> _cells)
{
ReelSprite* mainSprite = new ReelSprite();

mainSprite->init(filename);
mainSprite->autorelease(); // <-- ADD TO AUTORELEASE POOL
mainSprite->cells = _cells;

return mainSprite;
}```

ReelSprite::create  is a static method that follows the Cocos2d convention of constructing an object and adding it to the autorelease pool. mainSprite->autorelease()  is the line that actually adds the object to the autorelease pool, so that it does not have to be manually destroyed.

# Out of Phase: Genre Considerations

This is part of a series for the Out of Phase game project that reflects on various stages, covering pros and cons of the creative process and implementation of the game. The first post can be found here.

Deciding what type of game you’re creating can be difficult while the concept is in its infancy. There’s so many ideas you want to use, and many of those may conflict with each other at first, requiring some compromise in order for them to gel

In Out of Phase, there was a struggle to combine puzzle and action mechanics.I was trying to integrate elements from the two genres that I knew were successful by themselves, but incompatible with each other. To resolve this, I had to consider what experience I wanted to give the player and how the mechanics from each genre would contribute to that experience.

Some ideas I had to let go of, as they were too far from the vision, and other ideas had to be reworked to fit the core game concept. Here’s a reflection of that journey.

## Puzzles

First I’ll start off with what kind of puzzler this is not, but what I originally thought it was going to be.

Some of my favorite games are point-and-click puzzlers, such as Myst or Escape the Room games such as Crimson Room. In these types of games, the player can progress at their leisure. While there may be action sequences, they usually don’t require interaction from the player, though there are some exceptions where the player must make a timed decision during the action sequence. The timing is typically pretty lax however.

Games like Myst, Crimson Room, or even The 7th Guest are what I would consider leisure puzzlers. They are typically slower paced compared to an action game and focus more on immersion and an experience. Death in these games are pretty rare, and are based off of a decision and not action, so the player is given a high level of safety while exploring the worlds. The focus of these games is on immersing the player into a fantasy world, and death or abrupt twitch mechanics tend to draw the player out.

While these games are fun, they weren’t the style I was looking for. Instead, I wanted to go with something more real time and physical, like Maniac Mansion or the more recent Ib. I wanted to give the player a different feeling of tension that they may need to react fast to avoid getting injured or killed, which deviated from leisure puzzlers.

This was a point of conflict in my early design brainstorming, because I liked the pacing and immersion of the leisure puzzlers. However, every time I tried to settle on removing action from the game, it felt incomplete. So I moved onto a different type of puzzler, one which was more physical and time sensitive.

In the first prototype I started with a very basic series of chambers and hallways that contain puzzles. This is what was implemented at the the Global Game Jam, and I had the beginnings of what was like a Portal clone, with pressure plates and objects that could be pushed onto them.

Where it differed from Portal (besides no portals!) is some objects and parts of the maps would be different between the players, in some cases requiring the players to communicate and discover the difference in order to complete the puzzle.

There would be furnished rooms with interactive objects, like a record player that would play music, light switches, and paintings. The player would need to interact with certain objects and in some cases complete a sequence in order to progress through the game.

With these ideas, this game was becoming more like Ib, where core gameplay involved adventuring through the levels and discovery. There would be some action sequences, but the player had to evade dangers, opposed to attacking those dangers.

The game concept already sounded fun, and there were so many possibilities for puzzles. Yet, there were some things that didn’t feel right. I didn’t want the player to be totally defenseless, I wanted to let them fight back. I also needed something that gave the game some replay value after the puzzles were figured out, so my focus began to shift.

# Out of Phase: Global Game Jam 2015

This is the first post in a series that will reflect on the project from various stages, covering pros and cons of the creative process and implementation of the game. This review is a long time coming, it was originally started right after the 2015 Global Game Jam.

In January I broke a lull by participating in the annual 48 hour Global Game Jam. Prior to this jam, it had been some time since prototyping a game of my own. Game jams in general are a great opportunity to break creators block and start fresh.

I started a project called Out of Phase. The original idea was to create a two player game that involved a series of puzzles contained within chambers, similar to Portal 2. There was a twist, where the environment was slightly different between the two players, requiring them to communicate between each other to solve the puzzles.

At the end of the 48 hour jam, I produced the first version. While not complete, it still gave an example of the general concept with a couple puzzle examples. Two players were supported through a local co-op mode, where chracters were toggled by hitting the tab key.

For this post, I’ll give a general overview of the tools and design ideas that took place at the Global Game Jam.

### Framework

It’s a good rule of thumb in game jams not to build your own framework. Your focus is on producing a game, not a toolset. Phaser.io is a real snazzy HTML5 game engine/framework. It comes with a tilemap loader, collision detection, WebGL support, and a plethora of other goodies to make life easier.

Another guideline with jams is to know your toolset so that you’re not wasting time figuring out how to use the tools. I only had a little experience with Phaser.io prior to the jam, so I didn’t follow this one completely. However being very experienced with JavaScript and the concepts that Phaser.io is built on, I was able to get started very quickly and iterate through ideas easily.

One problem I ran into early on was selecting the wrong physics engine for collision detection. This set me back a little, but helped me learn the differences between the P2 and Arcade systems. In Phaser.io, you can actually have more than one system active, so they’re not exclusive to each other.

# Game Jam #7

Reeeally late in posting this, but I’m determined to post about my game jam back in July where the theme was time manipulation. The dynamic was a little different, I had an “idea person” to help move the creative process along and blocks. I was paired up with Jacq, sound engineer and creative mind. After a few iterations of rehashing the fundamentals of our game, we finally came up with a platformer that fit  the theme. From this experience I had some takeaways to apply to my next jam.

Idea People are AWESOME
Having a person to handle the brainstorming while you’re coding has its benefits. It’s easier to cut and run when hitting a wall, as the other person has already been thinking into alternatives, opposed to wasting time on something that just isn’t working because you don’t have any better ideas.

Skillsets can become dusty
This was a frustrating lesson to learn. After not touching Flixel for a month and a half, working with basics like movement and sprite placement was more difficult than it should have been.

There’s an easier way to prototype
My toolset has been pretty low level. I use ActionScript, and while I utilize the Flixel framework with libraries, it still requires a lot of coding. At the end of the jam I surmized I would have developed my prototype faster with a prototyping framework such as Construct 2 or Stencyl.  Both allow the rapid prototyping of platformers, such as this one without coding.

For those interested, the source and demo can be found here:
Source
Demo

# Canabaliced

I’ve started a game project with my wife, who is a 2d artist. Among the titles we’ve thrown around, Canabaliced (Canabal – Iced) seemed most appropriate. The premise of the game (so far) is you’re a popsicle struggling to survive the heat. And how does he survive? Just the way we do, by eating icy treats, including other popsicles!

The game’s theme was inspired from a challenge by Game Prototype Challenge.  We didn’t end up submitting anything, but we still got an idea to run with.  There’s a lot of ideas being thrown around, shot down, prodded, and dissected, but it’s gaining speed and direction. I see this game concept having a lot of potential, especially with the plethora of frozen treats that exist. But first things first, we need to settle on perspectives, game mechanics, and artsy things.

### Inspirations

For perspective and game mechanics, I’m thinking of designing the levels similar to Teenage Mutant Ninja Turtles II and Double Dragon II: The Revenge. We’ll start off with the level mechanics of Turtles, and later add the more advanced level design elements from Double Dragon, like climbing ladders, and the slight change of terrain perspective/mobility where the characters can only move horizontally.

Weaponry will be another fun thing to play with, including melee, and… ehrm… projectile types.  It will be all out popsicle pandamonium. One idea is to have the player and enemy spit or vomit popsicle juice, with different colors of juice having their own effect; poison, “fire”, slow, etc. There’s room for rocket(pop) launchers, “cherry bombs”, and chocolate mint sprinkle somethings. I need to fit an ice cream sandwich somewhere in there too.

Maybe at some point, there will be a online two player mode just like Turtles, and Dragon.

### Restocking Ammunition

One twist I am intending on using is to have the character’s main weapon use his health as the ammunition.  Any additional weapons will have a small supply of ammo,  meaning the player will need to be cautious using their weapons. The player will be able to restock their main weapon (popsicle spit) in two ways: by obtaining ammo deposits throughout the levels or by consuming NPCs (the good and the evil). I’m thinking of adding some type of morality meter for the second option, which would apply some type of consequence if the player decides to take the easy route and destroy innocent NPCs.

### Conclusion

This basically encapsulates the initial concepts and ideas. I have some developments I will be sharing in some future posts. I think the biggest challenge with this game will be not to make it too serious, or filter the concept. After the idea settled, and reason began returning, I had several parental sensors going off in my head. The same ones I have to ignore when watching Adventure Time (which much of the humor is or will be inspired by). It’s not meant to be serious, it’s meant to be fun. Even so, I still want to give this enough depth to make it more then a game that you play for a few minutes and never touch again.

I’ll be posting more as we progress, including some tutorials and AS widgets. Stay tuned!

# Game Jam #5 Takeways

Here is a takeaways review for last month’s game jam. This builds off of the last entry in this series, from Game Jam #4.

This last game jam was a lot of fun, and I enjoyed it quite a bit.  There’s always a lot of good ideas out there, and I’m impressed at how imaginative and innovative people can be. Thanks to the Sacramento Game Jam meetup and 5th Planet Games for making this possible!

I entered this game jam with a couple objectives in mind. First, to use what I know, and second, to complete a game within the allotted time. Now let me tell you, both of these are challenges! When you enter a jam, you don’t know what other skill sets you have available, and with this being a social event, it’s difficult to consider working by your lonesome. But that’s exactly what happened, at least at first. I could have worked with Unity, currently a very soft skill, or in Java with a framework I’ve never used before. There was even an existing team using ActionScript (my skill of choice), but there were already quite a few members. All were -very- tempting, as I was really seeking out a collaborative effort, but in the end I started off by myself. Luckily, a designer found his way to me, and I became a team of two.

The end result was a nice prototype of a top down action game we titled “Alien Blitzer”. We had a HUD, as well as terrain and player/enemy graphics. The Flixel/Power Tools helped create a functional prototype relatively fast. It was really nice how things just slid in place towards the end. We were successful in the sense that we had a functioning prototype that included the core mechanics and game play. More can be read about the prototype itself in a previous post.

### Lessons to apply to the next Game Jam

The outcome was no accident.  It was a result of experiencing two previous jams/hackathon where things didn’t go exactly as planned, some research, and most importantly, the application of these things. Just like the previous jams, there are a few key things that I have taken away from this jam through trial and error, and will continue using or improve on in preparation for the next game jam.

1.) Have an idea what you want to do

Have an idea what role you want to play, and what skills you will be offering. Going in without any plan can make it difficult to form a group, and can set you up for failure. This doesn’t mean everything must be set in stone, just have a rough plan. It’s tempting to be ultra flexible, and acquire new skills on the spot, but it’s more important to produce a prototype, so try your best to make use of what compatible skills are available. In addition, if you’re up to being a leader, be ready to be step up at the very start.

3.) Create a prototyping kit

Take your framework a step forward, put together a kit that’s fast and flexible, so setup takes less time and doing  comes sooner in the prototyping phase. To emphasis, these jams are meant for prototyping. The less time you spend implementing (coding)  something the better. This means you have more time to work on polishing mechanics, content, etc. A kit that at least has the basic environment setup, player controls, and a splashscreen would be great. It should be setup in a way where it’s easy to remove unneeded features just by removing a few lines of code, you don’t want to go too crazy.

I’ve started a Flixel/Power Tools/Dame kit on github.

4.) Bring a big pad of paper, and some writing utensils

Planning is really important, and it’s easy to become lost in the flurry of  activity. Ideas, goals, and thoughts can become meddled when they’re just floating in your head. Use something physical to keep everyone bound to one reality and understanding. This would include sketches, lists, or written words.  Something to avoid misinterpretations or deviations from what really needs to happen. Putting things down on paper helps out a lot, and I know for at least myself, it helps eliminate fuzzy logic that sounds good at first, but falls apart when it comes time for implementation (doh!).