Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Switch Statements and Branch Tables

Name: Anonymous 2012-04-10 13:55

So let's say I'm making a game, and each monster in it follows a separate movement pattern. For each step of gameplay, each monster must have its movement routine called. Instead of evaluating a conditional to determine which movement pattern a monster should use, I could solve this problem easily by enumerating the movement patterns, and using this value as an index into a jump table.

My first instinct would be to write this (in C) literally as an array of function pointers. The end result would look something like:
for all monsters
    *(movfunctions + monster.movementpattern)(&monster) // call a movement pattern function


Alternatively, I could write a single movement function with a massive switch statement instead:
case MONSTER_KNIGHT: // MONSTER_KNIGHT being #define'd to a constant
    // chase the player
    break;
case MONSTER_BUG:
    // hug the walls
    break;


Now, I get that the entire purpose of a switch statement is to facilitate the creation of jump tables. Could I then assume that the compiled results of both methods would be similar?

Name: Anonymous 2012-04-19 7:16

I don't see why you would have multiple arrays, is the pattern able to change that much?
if so you could have a int mov_group and many different monsters use the same mov_group, and this symbol identifying a static index that now is of type patterns[], so

pattern_groups[monster.mov_group].patterns[monster.mov_pattern](*monster);

and each monster 'class' would default to a certain pattern group but able to change between movements that belong to it's group, maybe by stances? defensive, offensive, ..
now if you wanted a particular monster to suddenly use a unique movement pattern you could make a rule that element at 0 on index 0 (pattern_group[0].patterns[0]) is reserved to call a function referenced by the callee instead, something like

if(mov_special == TRUE){
this.special = my_func;
pattern_group[0].patterns[0](*this);
}

where 'this' is
struct Monster{
... // typical monster stuff
void (*special[])(monster *);
}

and the default function in [0,0] is
void default_special(monster * m){
m->special();
}


I don't know if this helps, it is getting dangerously close to OOP

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List