Fake enums

26 10 2010

The more I write ActionScript code the more I want to write C++ code. Partially because I like C++ and partially because I dislike ActionScript I guess. In many ways, and probably a whole topic in and of itself, the enjoyment and usage of a programming language is highly subjective. But it isn’t the topic of this post.

ActionScript 3.0 doesn’t support the notion of built-in enumerated values. Otherwise known as enums by those with a panache for shortening words. The thing about enums is that, well, they are really really useful to have around when we want to limit the input range of a given function or container. Enums give us an even further advantage though in the sense that they not only provide a controlling mechanism but also an associative relationship between a symbol and its representation in the system. A simple example in C++.

enum StateType
{
  IN_GAME = 0,
  IN_MENU = 1,
  IN_TRANSITION_OUT = 2,
  IN_TRANSITION_IN = 3,
};

In this case we can define another variable in the main game class which holds a current state [not the best solution but a simple and viable one nonetheless].

StateType mCurrentState = StateType::IN_MENU;

mCurrentState can now only hold those values specified by the StateType enum. And not only that but each particular value has a meaningful name. Very useful and, unfortunetly, non-existant in ActionScript 3.0. So I finally gave up and decided to hack something together. It’s a bit ungainly as a solution but it’s a neccessary evil for now.

The other tactic one can employ in this situation, by the way, is to simply create a few static constants and pass them around as unsigned/signed integers. Good but not quite what I want although it is a part of my solution. This Type class is designed to define a few buttons on the main menu and make sure we can’t accidently choose a funny button.

public class ButtonType
{
  public static const BUTTON_01:uint = 0;
  public static const BUTTON_02:uint = 1;
  public static const BUTTON_03:uint = 2;
  public static const BUTTON_04:uint = 3;

  public static function CheckValid(_value:uint):void
  {
    switch (_value)
    {
      case SHARK_ISLAND:
      case SEVEN_CITIES:
      case UNKNOWN_BOOK:
      case INSTRUCTIONS: break;
      default: { throw Error("Unrecognized button type"); }
    }
  }  
  public function get value():uint { return mValue; }
  public function set value(_value:uint):void
  {
    CheckValid(_value);
    mValue = _value;
  }
	
  public function ButtonType(_type:uint)
  { 
    this.value = _type;
  }

  /*PRIVATE DATA*/
  private var mValue:uint = 0;
}

Why go through all the trouble of writing a different class instead of just encoding the static constants into the main menu class? My reasons are as follow:

  1. Because it means the MainMenu will have one less responsiblity to take care of [validity check].
  2. Code is now localized. So all code changes to button types [adding/removing types] and their validity checking would only occur in one place.
  3. Other classes which only use the button types don’t need to have knowledge of the entire MainMenu class [ie. import it]

Any better ideas out there?

“And every time she sneezes I believe it’s love and, oh lord, I’m not ready for this sort of thing…”





Some ado for things to do

23 10 2010

In a complete change of pace from the last few posts I’d like to go back to some C++ mainly because, well, I missed writing C++ code. [I haven’t finished the RunningCore but I’ll post up the complete code later and I’m sure no one would mind].

I’ve recently had a couple of conversations with people who have just started programming and I’ve seen code posted by other people who are going through the process and all of it reminded me of my first forays into the C++ language and the way we were taught it at school. The following are just some things I picked up on the way, they are my opinion of course and anyone can and probably will disagree with some of them if not all of them. Please feel free to comment [editing this I just realized it’s a pun, you’ll understand later] since I’m always up to learning new things and/or unlearning bad habits which is usually alot harder. So, without further ado, let’s start.

using namespace std;

This line is present in almost every tutorial or book I’ve seen and used by every teacher I met, all for the sake of brevity of code. Well guess what, the scoping operator is in the language to be used. C++ supports namespaces for a reason and it’s best to get students used to the fact that code is separated logically into ‘spaces. Exposing everything in a namespace like that will trample on other people’s code and cause annoying name clashes. If a function has too many ‘::’ in it for your liking the better alternative is to use a using directive local to that function.

int main(int argc, char* argv[])
{
  using std::cout;
  using std::endl;

  cout<<"Hello World!"<<endl;
}

Keeping with the namespace theme, put your code [yes I’m talking to you!] in your own namespace. The global namespace is full of things as it is, don’t add more to the party. Be proud of your code, own it. The global namespace will thank you and so would anyone coming after you that uses your code but also wants to have another function called Create() which does something completely different.

And another thing, comments are NOT your friend!
No, seriously, if someone tells you to document everything with comments then shoot them. Documenting algorithms should be in the documentation not in between the code lines. Comments are not meant for documentation purposes. They are also not used for this purpose:

void function()
{
  int i=0;
  int a=12;
  i+=a;
  //i-=a*2; <------ This is NOT a good practice
}

If you comment a line, delete it, otherwise it’s flotsam, rubbish in the code stream. If you want to branch out from a particular codebase or just revert to some old code then use your VCS [Version Control System]. What, you aren’t using one! Stop writing code, just stop and go get one. Doesn’t matter if it’s Git, Mercurial, SVN or whatever. Your code is too precious to be left hanging without a VCS. And no, for the love of the gods [you know, Zeus, or Odin, or who ever you happen to believe in] DropBox IS NOT A VCS. If you ask around the office what kind of VCS they’re using and they tell you DropBox, RUN!

Hm… Where was I?
Documents, yeah. Coding standards are good, they’re good to have around and they’re good to document. I submitted a 6 page review in college for the coding standards our team was suppose to follow. I got a really good mark for it. I should have failed. Coding standards are only good if people follow them and people will only follow them if they can
A. Read them in a glance and,
B. Actually retain the rules in their head.

6 pages of documentation just for that allows for neither. Having globalized standards is important to any project but if they sit on more than 1 A4 page of 1.5 line-space, 12pt Ariel font then it’s a waste of time. Think hard about what’s important to you; items like, perhaps, Directory structure, Tabs vs. Spaces and indentation rules. A character count for global/local/static variables is useless [I had it in my particular document example and I wish I didn’t].

And just a few more for the road before I leave.
Braces, unlike commets, are your friends. They love you and they love us. They show everyone where everything lives and which lines belong to which if.

if (condition) { doSoemthing(); }
if (anotherCondition)
{
  doSomething2();
  doSomething3();
}

switch (lastCondition)
{
  case 0: { doSomething(); break; }
  case 1: { doSomething2(); break; }
  case 2:
  {
    doSomething3();
    dontDoAnything();
    break;
  }
  deafult: { handleDefault(); }
};

Clean and clear code can save lives you know, mostly yours if the maintainer has access to your address.
Get into good coding practices from the start. Don’t be fooled by tutorials or teachers telling you that it doesn’t matter. It does. And it’ll make life easier in the long run [just not the short one].

And one last, tiny little thing. If you have to include windows.h do it in a .cpp file, in a different directory on some else’s computer through a DLL. Worst header ever written…

“I think I’m a banana tree, Oh dear, I’m going slightly mad”





Last push

17 10 2010

Sorry about the delay but deadlines before blogs I guess; wow it’s been four days, where does the time fly?
Where was I?

Ah yes, velocity and acceleration. Well, the calling code for the RunningCore would probably look something like this:

if (InputDevice.IsPressed("Left"))
{ 
  mRunningCore.Accelerate(RunningCore.LEFT); 
}
.../*somewhere in an update function*/...
mRunningCore.Update(_deltaTime);

And from here users can query the CurrentVelocity and go on their merry ways; sort of. I’ve established what happens when users press “Left”, the problem is I’m still one question/answer short of proper communication. What happens when users stop pressing left?
At the moment, nothing, velocity will never change, users cannot slow down [they won’t reach lightspeed anymore but I bet even YOU will get tired after seven hours of straight running at maximum speed].

I’ve reach, you guessed it, another decision.
Should I add another function?

public function Decelerate(_friction:Number):void;

Or should the RunningCore class implicitly slow velocity when users aren’t pressing the movement buttons?

The answer in this case, as in many with programming, is – it depends.

I actually don’t have a hard and fast and right answer for this; I’ve tried implementing both ways and in various forms, each one with its own benefits and drawbacks. But code has to be written and choices have to be made, in this case I’ll use an implicit slowdown. The real problem here is that these physics are faked and faking things is harder because it involves hacking solutions which in turn mean hacked and tacked-on add-ons [it rhymes and is the truth, two for two].

But how do we signal the RunningCore its users have stopped wanting to accelerate?
My solution relies on the fact that when users call accelerate the RunningCore changes mCurrentAcceleration;

mCurrentAcceleration = mMaximumAcceleration * mDirection;

Using this I can augument the Update function in this manner:

public function Update(_deltaTime:number):void
{
  if (!IsVelocityAtMaximum())
  {
    mCurrentVelocity += mCurrentAcceleration * _deltaTime;
  }
  mCurrentAcceleration=0;
}

The logic behind reseting the mCurrentAcceleration is simple. I basically say, assume that users have not requested Accelerate() until proven otherwise. This solves the communication problem, but not the slowing down problem. RunningCore needs to slow its velocity by a certain amount when users aren’t requesting to accelerate.

public function Update(_friction:number, _deltaTime:number):void
{
  // mCurrentAcceleration will only be 0 if users have not called RunningCore::Accelerate
  if (mCurrentAcceleration == 0) { mCurrentAcceleration =_friction; }  
  if (!IsVelocityAtMaximum())
  {
    mCurrentVelocity += mCurrentAcceleration * _deltaTime;
  }
  mCurrentAcceleration=0;
}

The code still needs to be organized a bit here as well, because my previous decision concerning handling maximum speed is actually producing results which are wrong. So let’s refactor.

public function Update(_friction:number, _deltaTime:number):void
{
  if (!IsVelocityAtMaximum()) { CapVelocityToMaximum(); }
  
  // mCurrentAcceleration will only be 0 if users have not called RunningCore::Accelerate
  if (mCurrentAcceleration == 0) { mCurrentAcceleration =_friction; }
  
  mCurrentVelocity += mCurrentAcceleration * _deltaTime;
  mCurrentAcceleration=0;
}

Run it, test it, and you’ll see that this code doesn’t actually do what we need. The problem stems from not defining my new requirements. The question should now be what do I want from friction? And the answer… I want to use friction as an acceleration which works against the current direction of RunningCore’s velocity. Let’s revise the code.

public function Update(_friction:number, _deltaTime:number):void
{
  // assert(mVelocity>=0)
  if (!IsVelocityAtMaximum()) { CapVelocityToMaximum(); }
  
  // mCurrentAcceleration will only be 0 if users have not called RunningCore::Accelerate
  if (mCurrentAcceleration == 0)
  { 
    mCurrentAcceleration =_friction * -Tools.GetSign(mCurrentVelocity); 
  }
  
  mCurrentVelocity += mCurrentAcceleration * _deltaTime;
  mCurrentAcceleration=0;
}

Much better. But notice the new asserting check to make sure that _friction is positive [or at least zero] because the internal logic of Update() relies on that fact. Phew, nearly done. There’s just one more thing to complete this function, can you [if you aren’t me that is] spot it? Try running it, I wonder what would happen?

There’s probably one more post to do concerning RunningCore. But the truth of the matter is these posts aren’t really about physics [fake or real] or code at all, they’re about my workflow and how I approach programming [at the moment]. I wonder what it would look like in 10 years?

“Life is a lemon and I’d like my money back”





Left, right, left, right

13 10 2010

Last time we’ve seen our little player character he, well, he couldn’t really do anything because I didn’t finish the class. Although you could ask him some serious questions about his running. Let’s fix that.

What do I need next?
A question which drives all of creation. In this case what is needed is a way to communicate between the user of the RunningCore and the RunningCore itself. Since I’ve already established that users issue a command to accelerate [ie. they tell the RunningCore to apply acceleration], this would be the name of my new function. But accelerating alone doesn’t help, I also need to know which direction to accelerate to.

public function Accelerate(_direction:int):void

The first thing I need to make sure is that users [me later on when I forget how to use my own code] don’t break the logic behind this function and supply a “funny” value.

public function Accelerate(_direction:int):void
{
  //assert(_direction==LEFT || _direction==RIGHT);
  mFacing=_direction;
}

The assert is not a macro in ActionScript as far as I know, just replace it with the appropriate fault-handling routines of the project. Alright, the player can change direction but still no acceleration, let’s fix that too.

public function Accelerate(_direction:int):void
{
  //assert(_direction==LEFT || _direction==RIGHT);
  mFacing=_direction;
  mCurrentAcceleration = mMaximumAcceleration * mDirection;
}

Notice how it’s not really proper physics… Well, this is a small 2D platformer in ActionScript. Control and fun take precendence over physical accuracy [usually].

Alright, I’ve got a way to communicate to the RunningCore that I want to accelerate. Now what?
the next thing is a way to update the RunningCore’s velocity. A good function for that, lo and behold;

public function Update(_deltaTime:number):void
{
}

Taking the simplest route possible following our “fake” physics;

public function Update(_deltaTime:number):void
{
  mCurrentVelocity += mCurrentAcceleration * _deltaTime;
}

Of course using this players can’t actually stop and in fact will continue to accelerate until they hit lightspeed [and if you want to know what that feels like, watch Red Dwarf]. First order of business, let’s cap velocity to its maximum. For that, two more functions, this time private since they’re used for internal logic.

private function IsVelocityAtMaximum():boolean
{
  return (Math.abs(mCurrentVelocity) >= mMaximumVelocity);
}
private function CapVelocityToMaximum():void
{
  mCurrentVelocity = mMaximumVelocity * Tools.GetSign(mCurrentVelocity);
}

Why all the exta functions?
A. I like them and it’s my blog 😛
B. And probably more important, because this is an evolving code. And separate functions are easier to debug/trace/change as needed. Also, it’s a lot easier to copy/paste code away from functions then try to refactor loose code into functions!

But wait, why is it taking the absolute value of mCurrentVelocity? and what’s this Tools.GetSign()??

The IsVelocityAtMaximum() function needs to take the absolute value of mCurrentVelocity since the value of velocity may be positive [if running right] or negative [if running left] but the mMaximumVelocity is a positive value [since I’ve decided to use the same value for both positive and negative velocities].

As for the second question, the Tools.GetSign() is a function which returns either +1 or -1 depending on the value of its argument. I wasn’t sure whether ActionScript had this built in.

public function GetSign(_value:number):int
{
  return (_value>=0) ? +1 : -1;
}

I love this operator 😀 And mCurrentVelocity needs to be capped in relation to its sign [direction]. Meaning that if the user is moving left [-1] mCurrentVelocity needs to be capped to -mMaximumVelocity and vice-versa.

Now for another decision, isn’t programming fun! Do I want to disable acceleration if the current velocity is passed the maximum, or do I want to cap it to the maximum when needed? Let’s disable it for now though.

public function Update(_deltaTime:number):void
{
  if (!IsVelocityAtMaximum())
  {
    mCurrentVelocity += mCurrentAcceleration * _deltaTime;
  }
}

Well, 3am is my cue to accelerate into bed [going to leave the dishes dirty tonight :P]. Tomorrow will see the conclusion of this little running saga [horrible horrible pun, please don’t shoot me].

“Lord knows I’ve paid some dues gettin’ through; Tangled up in blue.”





I never liked running…

12 10 2010

It’s three in the morning, again, well I can’t really complain about that; these are my working hours after all. But having to debug movement code for the last hour and a half has left me in a sour mood. Of course the fact that I’ve managed to solve it makes me happy. So if nothing else I think we can establish that being a programmer of any kind is one hell of a ride… Bipolar tendencies aside, let’s talk shop.

As mentioned before, I’ve been dabbling into the art of ActionScript 3.0 in order to write a 2D platformer. The language itself has probably been explained by people more familiar with it so I won’t try, I don’t dislike it, in fact its been a pleasent surprise working with it. There are a few niggles here and there, nothing I can’t live with. The one which annoys me the most is the “const” keyword. To me const refers to either bitwise const or logical const, either way when I’m saying: this object is a constant, what I mean is it should not change state [or bits in the memory, however you want to look at it]. There’s something quite wrong when code like this compiles and executes:

const position:Point = new Point(10,10);
position.x=11;
trace(position);

I understand that the const qualifier refers to the actual reference to the underlying object but to me that’s fairly useless. And another thing, would it have killed Adobe to give me control over where/when a const object gets initialized to its final value. Why can’t I use an object’s constructor to determine the value of its constants??

But I started this post by talking about movement code so let’s get back to that. This particular code is part of a class called RunningCore, which is a part of the Player class [and I’m sure you can guess what it does]. I like the concept of having different Core classes which can be quickly added/removed from classes to supply functionality. In contrast, the first iteration of the Player class contained all the running logic inside it and that meant I couldn’t reuse the code for any other object in the game; so I put on my refactoring hat and made some refactoring coffee and got to… well I probably fell asleep, but right after I woke up I went to refactor the code.

Roll your sleeves and let’s go.
What’s the first thing I need from the RunningCore? Why, I need to know whether I’m running right or left; cool, let’s just enum a direction, ah bloody hell, no enumerators in ActionScript… Never mind, constant static integers should work just as well.

public class RunningCore
{
  public static const LEFT  :int = -1;
  public static const RIGHT :int = +1;
  
  public function get IsFacingRight():boolean { return mFacing==RIGHT; }
  public function get IsFacingLeft() :boolean { return mFacing==LEFT;  }

  private var mFacing:int = RIGHT; //arbitrary direction to start at
}

Why, +1, -1? That’s to do with my coordinate system [positive and negative X-Axis] and the fact I already know that the direction would control the Velocity [which is a vector quality] but I don’t want it to resize it. Next I needed to decide how much to fake the physics. In this case I wanted to have an acceleration force which works on the velocity, rather than manipulate the velocity directly. The acceleration itself is constant, unlike real life, but I’m not going for a full physics system here.

Ok, now what?
Well, I know what the overall system should look like, velocity and acceleration. And because I can’t run faster than light players shouldn’t either so let’s cap their velocity/acceleration to some maximum.

public class RunningCore
{
  public static const LEFT  :int = -1;
  public static const RIGHT :int = +1;
  
  public function IsFacingRight() :boolean { return mFacing==RIGHT; }
  public function IsFacingLeft()  :boolean { return mFacing==LEFT;  }
  public function IsRunningLeft() :Boolean { return mCurrentAcceleration<0; }
  public function IsRunningRight():Boolean { return mCurrentAcceleration>0; }
  public function IsMoving()      :Boolean { return mCurrentVelocity != 0; }
  /*Add get/set methods for for velocity and acceleration variables*/

  private var mFacing              :int    = RIGHT;
  private var mCurrentVelocity     :Number = 0;
  private var mMaximumVelocity     :Number = 0;
  private var mCurrentAcceleration :Number = 0;
  private var mMaximumAcceleration :Number = 0;
}

I’ve omitted the get/set methods for brevity’s [and formating] sake. Notice how I’ve also made some query functions [which could also be get functions I guess, if you’re into that sort of thing] which cement the requirements I have from this class.

Are you moving? 
Where are you moving? 
How fast are you moving?

This post is getting long and I still need to reimplement the jump mechanics, so I’ll just break it off now. The next post will be tomorrow [rather than a week from now] and will finish the RunningCore class.

“The chances of anything coming from Mars are a million to one he said”





Tech vs. Game

5 10 2010

I’ve reached a point in my code where I must make a decision.

I’ve been reading alot lately about game engines and shaders and data oriented design rather than object oriented design and all that jazz. And one particular presentation kind of struck a chord. It had nothing to do with game design mind you, but it basically boiled down to design around data not around world description. You can read about it here. It’s an interesting read and he definitely makes some excellent points about the whole data orientation design concept. But that wasn’t my point. The point was, it got me thinking and my train of thought went something like this:

* Design the engine around data.
* Design the game around worlds.
* The discrepancy between the need for a “cutting-edge” game technology and a fun and engaging experience.
* What is more important to me as a developer?

And as a single developer with only two hands and one keyboard I was struck by the fact I’ve never actually thought about it that way. So I mused some more.

A “good” game is more than the sum of its technology. A game must provide an engaging interactive experience, an environment where players learn. This is not to be confused with the term educated. A game does not need to overtly teach players about something. An engaging world is one which players would want learn about and learn of. Challenges teach us as we overcome them and the sense of achievement we feel from both “winning” and learning is sublime.

But this relationship can also be reversed. Without the technology in place to display, update and make the game interactive on computers/consoles there is no game. Games are “driven” by technology, they need it. As a programmer it has been far too easy for me to fall into believing that the code is more important than the world and its rules. But the truth is, it isn’t. Code and the engine technology are companions to the experience of the game [much like sound and graphics] but they are not its masters. The game is not defined by the code which runs it. It is the game itself which should determine what the code should do, what the data should be and what things look like and sound like.

That said games are still bound by the platforms [hardware] which run them and these in turn determine the data and code structure. The only conclusion I can reach from here is that in order to design a game one must be painfully aware of the target platform intricacies as well as the complexities of making beliveable worlds.

This still doesn’t answer my original question however. And I will do so now.
What is more important to me as a developer?

I care about technology and I love programming; I tried to write interfaces and generalize and use all the best software engineering practices I’ve learnt over the years and you know what, a couple of months down the line and I’m still nowhere near a game. I am close to starting a game engine but no game. I don’t want to write a game engine, the Unreal people have done it better than I, the Unity team have done it better and I’m sure out there there are many many game engines. I want to develop and release games… Technology will emerge but the game is the important drive.

So I’m shifting focus.

“Planet Earth is blue and there’s nothing I can do”