AI problem with an elegant solution
Hi everyone, Vlad here!
I’m excited! It’s really nothing special but I had one of those eureka moments!
Here goes:
The problem
The current game has a number of mechanical hazards. To test the animations Marco designed I simply added a counter that would put the hazard on a waiting state and then run the animation. While the animation was running the hazard was on an attack state that checks if any actors are in the area it affects.
Easy enough but this had these problems:
1. In theory every hazard of the same type has the same loop. Game design wise suspension of disbelief fails.
2. In practice and since the game updates only part of the map what happens is that each hazard has its own loop but the level designer has no control over it.
3. To give a wider control to the level designer the game would need to update every hazard per frame… see the problem here?
The solution
What if most of the hazards had a central AI point? The first time we discussed something like this was when Marco and Pedro were working on Hajime. The objective was to have the AI army making better decisions considering the overall scenario instead of having each unit deciding the next move individually.
In this case we want that the most basic hazard behaviors to be the same regardless of being updated or not while maintaining the suspension of disbelief. The generic solution (we are considering having configurable groups and individual hazards still) is to have chained hazards based on their tile position.
I’m currently writing the class that will serve as the hazard commander. It is amazingly simple. The following code is almost pseudo-code and a very simple version of what I’m writing because there are several hazards and each has a different frame count.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
public function update():void {
// For each hazard
frame++;
if (frame == hazardTexture.collectionLength()) {
chain = chain == maxChains ? 0 : chain + 1;
}
}
public function getFrameOf(id:int):int {
if (id == chain) return frame
else return 0;
} |
The commander is updated each frame. The code is pretty simple, it just increments the frame (not just one counter but one for each hazard type) and if the animation has ended it restarts and increments a chain counter.
Each hazard has a place in the chain. If it is on a part of the map that is updated, it will ask the commander what frame it should have passing its chain id. Even if it has not been updated recently it will update perfectly in sync with the rest of the game.
For this to be pretty and make sense and allow several automatic behaviors we have to understand what chain id means.
|
1 |
private var id:int = (tileX + tileY % maxChains) |
Ok, looks simple, what does this mean? The graphic below is a capture of the spreadsheet where I tested the formula. The top left number is maxChains and in each cell is the chain id of each tile.
So if we have several hazards of the same type in a row, they will act in order, both horizontally and vertically. If there are a lot tightly grouped the player will see a diagonal movement giving a sense of some automatism behind the hazards which is a nice add-on since it fits the game.
But that’s not all, we can use the exact same code commander and give the hazards a different way of using their id. For instance we can have a method that will give an attacking frame to odd and then even ids making more active zones of the the map.
Ok… that’s simple, what’s the Eureka all about?
To be honest this problem was haunting me for a couple of days. I knew I wanted a central decision point (not really a big AI thing but still…) for most non-manually configured hazard for performance and consistency reasons. Everything I thought of was too complicated. Then I thought about this simple chain and the only problem I really had was to have a formula that would allow a consistent behavior, like horizontal, vertical and diagonal chains. That little id formula was the eureka moment because it is so simple, so elegant and solves one major problem.
Like Einstein said:
Make things as simple as possible, but not simpler
Posted: February 10th, 2012
at 12:04am by Vlad
Tagged with Danger Zone, FlashGameBlogs, Snippets, Software Engineering
Categories: Dev Journal: Danger Zone,The code of VGS
Comments: 1 comment
Performance vs Error Checking
Hi everyone, Vlad here!
Seems like on a thing versus some other thing rampage with Application Design vs Game Design shortly followed by this post. I guess that’s a good thing, it means there are challenges and doubts and that we need to research.
This post is also inspired by some books I’ve been reading lately and that I highly recommend: The Productive Programmer that was influenced by The Pragmatic Programmer.
Problem #1
We are writing code and there’s not such thing as writing code without bugs. Sometimes our oldest, most used code, that code that we trust each of our games with gets into a specific spot where a hidden bug appears and we spend hours and hours figuring out what’s happening.
Solution #1 is Problem #2
There are several solutions to this. Writing code that includes testing is in my opinion the best. The problem with this, game development wise and specifically in scripted languages such as AS3, is that this makes the code much slower. The solution was checking for inconsistencies and not performing operations instead of throwing errors and exceptions.
I ended up creating conditions for use. For instance our blit package uses three different types: the core, the object and the texture. The core keeps the state of the whole system, the object keeps the state of what and where to render and the texture keeps the state of BitmapData. If the object did not have a texture it would simply not render. Sounds pretty cool, right?
To be honest… wrong…
Problem #2.1
First problem was the times where the position had NaN value instead of a Number. This rarely happened but every time it did it was a huge headache to identify why and then track the source of the bug down. While this seems unrelated, the fact was the it looked like the texture did not exist. So I had to check if the texture was created, if it was passed, if it was there at all and the worst part was that if the texture was there as it should, where the hell was the problem?
Problem #2.2
Performance wise checking if there is a texture is absolutely dumb! 99% of the times there is a texture present. More, the object class has a visible variable. If the object does not have a texture why is it visible in the first place?
So while apparently I solved a problem by checking if the texture was present and not performing any blit operation if it wasn’t, the truth is that both performance wise (not that serious by the way, it’s just a if statement) and the unwanted problems it induced in the code backfired from time to time.
I spread this type of behavior through the code. While one if statement does not have a large impact in performance, a lot of checking piles up and I had a lot!
Solution #2
A short story and a riddle both taken from those books that explain my thoughts on the ‘final’ (we’ll see about that!) solution for these problems.
The first one was when one of the authors was hired as a consultant for a development project where the coders sent broken code to the version control system. What he did was to create a routine where the version control server would compile the code that was pushed. Every time the compilation didn’t work the server would send an email with the error. With the amount of mail with errors constantly piling up on mailboxes, one of the coders asked if there was a way of not getting that much email. The consultant replied: “Sure, don’t push code with errors!”
The riddle is… what code takes not time to be executed? The one that is not compiled.
So the solution is to write code that allows zero error tolerance while not compiling it. The way to achieve this is with conditional compilation which can be used in several way but these are the ones I believe the most useful is to use code blocks, like this:
|
1 2 3 4 5 6 7 8 9 10 11 |
private function someFunction():void {
CONFIG::debug {
// Development code
}
CONFIG::release {
// Final code
}
// Both dev and final code
} |
Inside the same function, different code is compiled depending on the current configuration. We can have several checks with exceptions and errors being thrown and then have a ‘don’t check at all’ version in the release configuration.
This is a two stage solution really. On one hand every time I do something stupid, I get errors so my code has to be perfectly implemented at least when it comes to our framework. On the other hand the same code that make me code as best as I can is also the code that does not run in the final version.
Posted: February 5th, 2012
at 12:55am by Vlad
Tagged with Bold Pixel Engine, Books, Danger Zone, FlashGameBlogs, Snippets, Software Engineering
Categories: Dev Journal: Danger Zone,The code of VGS
Comments: 4 comments
Enhancing by refactoring
Two years ago I read a lot about OOP. Every time I picked a new concept in some forum or chat I’d do my best to understand and apply it. I was eager to improve my coding knowledge and skills but everything we code as a purpose and an audience and if we forget the purpose or the audience we are introducing more problems with the knowledge we have than solving problems.
That happened with Bold Pixel. At some point in time Bold Pixel became a monster to please developers instead of a tool to be more productive in my purpose to my audience: create games for players! People play games, not code!
I stopped over-engineering sometime ago and started reading about how to become a better programmer not by writing better code, but by writing the exact code to solve the exact problem. This brought a new problem: what to do with Bold Pixel and how to maintain and evolve it? First thing was to start a new package and only bring in classes that I needed but wire the classes up to be as slim and straight to the point as possible. I do that all the time to build up my code base right now, but that’s not all. Here’s the whole process I’m using right now.
Start simple
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class BlitObject {
// Position
public var x:Number = 0;
public var y:Number = 0;
// Rendering
public var visible:Boolean = true;
public function BlitObject():void {
// Constructor
}
internal function render():void {
// Render stuff here
}
} |
The class above can be a stub for a simple blit object. From a OOP perspective it breaks encapsulation completely since x, y and visible variables should be private but seriously, do I really need those to be private or protected and have getters and setters? No I don’t so no need to over-engineer it. The only thing I want to have contained is the render method that should only be called by the blit engine that lives in the same package.
The blit object only responsibility is to copyPixels or draw on a given world position translating camera position on the fly.
Writing a simple class like this is fast, performs fast, case closed.
Evaluate new needs
Now I need a tile map class. This class is also a blit object so following the “is a” versus “has a” rule tile map should inherit blit object. Considering the blit engine has a camera, the tile map won’t move. This brings two new problem.
1. If the tile map doesn’t move, why do I have x and y publicly accessible?
2. I want my camera to follow blit objects so blit objects must have x and y variables (or properties). How can I make tile map be recognized as a blit object, have x and y and have none of those altered?
Sounds messy…
I could write a Blittable interface that would define a render function and getter and setter methods for x and y. The problem is that if there’s something I want to keep in the package scope is the render function and interfaces define public interfaces.
The solution is to convert blit object in an abstract class and have its original functionality moved to a new graphic class.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
class BlitObject {
// Rendering
public var visible:Boolean = true;
internal function render():void {
throw new Error("Abstract function called. Override render()!");
}
public function get x():Number {
return NaN;
}
public function set x(v:Number):void {
throw new Error("Abstract function called or property x not available.");
}
public function get y():Number {
return NaN;
}
public function set y(v:Number):void {
throw new Error("Abstract function called or property y not available.");
}
}
class Graphic extends BlitObject {
// Position
private var _x:Number = 0;
private var _y:Number = 0;
override internal function render():void {
// Render stuff here
}
// Position
override public function get x():Number { return _x }
override public function set x(v:Number):void { _x = v }
override public function get y():Number { return _y }
override public function set y(v:Number):void { _y = v }
}
class TileMap extends BlitObject {
override internal function render():void {
// Render the tile map
}
} |
Problem solved. The class responsibilities are much better defined.
1. A blit object renders and has x and y coordinates. Since it is an abstract class everything we try to do with it directly will result in an error.
2. A graphic is a world movable blit object that renders by copyPixel or draw.
3. A tile map is a world static blit object that renders very large objects by copyPixel or draw based on a predefined xml specification.
Conclusion
What’s the conclusion here? Well for starters by this time I’d have a couple of interfaces and probably a helpers. I’m not saying it is wrong to have interfaces and helpers, actually it is preferable, but it would be coding for the sake of coding instead of coding for the sake of making a game. It took me 10 minutes to do this and while I was at it the BlitObject class also extends a ListObject class that really speed up the iteration, addition and removal of objects from the blit engine.
Still… I did repeat my self and the code has suffered another refactoring since then. I’ll leave that for another post but I wonder if you know what’s repeated… ![]()
Posted: January 28th, 2012
at 2:00am by Vlad
Tagged with Bold Pixel Engine, Danger Zone, Encapsulation, Inheritance, Snippets, Software Engineering
Categories: Dev Journal: Danger Zone,The code of VGS
Comments: No comments
Application Design vs Game Design Round 1
Hi everyone, Vlad here.
Let me start by saying that the title is a bit misleading. For starters it is not an actual bout but more a decision making process. It also gives the impression I’ll write more about this or that I have some kind of plan about this subject. I don’t, it just happens that I think I’ll travel this road again.
Game Design
The game design for this game states that:
1. The player’s objective is to reach the top of the “structure” (named just to make sense) where the action rolls;
2. The “structure” has several “floors” (again just for easier comprehension);
3. The player can fall to the previous “floor”;
4. It is guaranteed that the player will see at least three “floors”;
Application Design
One thing that I know for sure is that we will be blitting all graphics and that the player token has three different blit objects and two of those rotate thus negating copyPixels and putting the dreadful draw method to work.
Another thing I know is that each “floor” is a tilemap, also blitted and that each tile is 64×64.
And now the assumptions begin. How big is each “floor”? I have no idea but let’s say that a rather large “floor” has 50×50 tiles. If the player will see at least three floors and on later stages all “floors” are rather large we are talking about 7,500 tiles to be rendered with a astonishing number of 30,720,000 pixels to be copied… each frame.
The “floor” where the player is will only render the tiles on screen (88 max) but the other two lower “floors” can potentially be fully rendered given the camera specs. Even if all three “floors” only rendered tiles on screen (which won’t happen by design) there would still be 7,500 objects to manage and that’s tiles only since we need to add to this all the remaining entities: player, enemies, decorations, effects, etc, but to make it worse the bottom two levels will be zoomed and probably in full view which means not only that all their blit objects will be visible but also that at least 5,000 of those objects will use draw instead of copyPixels… Did the headache kicked in already or is it just pure performance insanity?
Implementation
One of the great things about copyPixels is that it only renders the intersection between the target bitmapData rectangle and the source rectangle positioned at the destination point. What this means is that if we have 1,000 objects to render but only one actually has an intersecting rectangle, most of the processing time is running the array, vector or list and – more important and processor heavy – calling the functions that will in the end render.
The draw method also does this with a matrix… more on this later.
The solution was to write a BlitTileMap class that builds the tilemap in one big texture before it is used. While it uses much more RAM this class allows to address pretty much every problem stated earlier.
First and foremost the number of objects managed and therefor the performance lost with running their container (in our case, a linked list) and calling functions. From a potential 7,500+ we now have 3. The other issue that this addresses is the number of pixels it will render or try to render, from potentially 30,000,000+ to the worst case scenario of 1,050,000. And last but not least, considering the lower “floors” will be zoomed out, instead of using draw to render 5,000+ objects it will render… 2!
But the draw method also has a funny and helpful consequence. The smaller the scale, the faster draw executes which in terms of performance is relevant considering the zoom out will be achieved through scale. Less objects taking less time to render will be (I hope) quite a performance boost.
Did I just write all this? Wow!… Later!
Posted: January 25th, 2012
at 12:15am by Vlad
Tagged with Danger Zone, Data Structures, FlashGameBlogs, Topdown
Categories: Dev Journal: Danger Zone,The code of VGS,The design of VGS
Comments: 2 comments
Bold Pixel’s Namespaces and Interfaces
After much thought and discussion by myself or at the FGL chat I made some decisions about how to make Bold Pixel more modular in order to simplify my own work. Since we are still on top of contracts, I couldn’t give enough attention to this but my brain was dealing with it in the background.
Inheritance Spaghetti
The problem presented was somewhat simple. My early coding of the blit engine got tangled in the dreadful inheritance headaches. My solution to it was to create one class per major responsibility. It worked fine until the time I decided to expand one of the classes to do something it wasn’t designed to do. So on one hand I solved the inheritance problems but on the other I lost modularity. At this time I had a OOP doubt that I expressed in the FGL forums and the discussion that started there really helped me to move in a different direction, one that I had never considered.
More over I said that I would not support requests that didn’t deal with deal with real problems we had in our own development. And while I stick to that, I couldn’t help but to think: what if Bold Pixel could help someone but it missed one little tiny feature? While this was puzzling me, there was real problem, one with impact in our development that was taunting me…
The case of Blit vs Physics
So Bold Pixel has a blit engine and it will wrap a physics engine (more about the physics engine this later this month) so the question that was on top of the table was: considering there is a blit entity and a physics entity, which one should access the other? Whatever the answer was, modularity was lost in the sense I imagine it. I don’t want blit to know physics and I don’t want physics to know blit!
After a nice chat with Antriel at FGL (thanks mate!) I got to know the Strategy Pattern and all my problems were solved. In simple terms, I will be defining interfaces for all interchangeable objects but the implementations of the interfaces can exist anywhere. In the case presented, a blit entity will have its spatial properties (rotation, x, y and scale) defined by a spatial interface. By default it will be a simple class and it’s needed since the properties of the spatial interface are needed to render bitmapdata. A physics entity will be a implementation of the spatial interface, so if I want to use physics on a blit entity, I simply write: myBlitEntity.position = myPhysicsEntity;
Visibility and Access Issues
This brought another problem. Bold Pixel has always kept its inner “stuff” hidden. The objective was this was to keep the auto-completion short and the use easy preventing mistakes. In order to implement interfaces I would have to make a lot of code public.
The answer to this would be abstract classes, but ActionScript3 does not support it. That will be addressed with simple naming and convention over configuration. Any class in any namespace in Bold Pixel that starts with Abstract will only have the simplest shortest implementation needed for something to work. For instance, if I want a blit entity that draws pixels I will have to extend a AbstractBlitEntity class (I guess that will be the name) but that brings another problem…
So ActionScript does not support abstract classes… convention will say that Abstract defines an abstract class.
Namespaces (to wrap this up!)
To have a better code organization I will need more packages and to have more packages I will need to provide access to classes in different packages. This will be done with namespaces. The only thing that annoys me is that Flash Develop in the current version (3.2.2) does not support code-completion with custom namespaces, but what matters is that using custom namespaces solves two problems. First I can have a bunch of private functionality like I like, but second, any coder can with a simple namespace use extend Bold Pixel to his own needs in a full modular way.
While I reckon that this is all just in my head and that a lot of work will have to be done and even considering that probably this will make Bold Pixel a little bit more complicated to the average coder, I feel it sorts a lot of questions, so: Namespaces and Interfaces FTW!
Posted: September 1st, 2010
at 1:46am by Vlad
Tagged with Bold Pixel Engine, Design Patterns, FlashGameBlogs, Software Engineering
Categories: The code of VGS
Comments: 1 comment

