Concise way to calculate #define

71 Views Asked by At

I have a set of #define's in a generated header such as this:

#define SFX_SOIL_DESTROY_1 2
#define SFX_SOIL_DESTROY_2 14
#define SFX_SOIL_PLACE_1 32
#define SFX_SOIL_PLACE_2 33
#define SFX_WOOD_DESTROY_1 5

I have a method that must return the correct define for the material type and sound type. Here is a long, inconcise solution:

int getSfx (MaterialType material, SoundType sound)
{
     switch (material)
     {
         case SOIL:
         {
             switch (sound)
             {
                 case DESTROY:
                     return rand()%2 ?  SFX_SOIL_DESTROY_1 : SFX_SOIL_DESTROY_2;
                 case PLACE:
                 // And so on

Is there some sort of macro-hack that could condense this? Any help is greatly appreciated.

2

There are 2 best solutions below

0
On

Storing it as data lookup is much faster and only requires processing once (when its set up). So, assuming material and sound are more or less zero-based sequential (otherwise do a lookup translation):

int soundLut [MAX_MATERIAL][MAX_SOUND][2] = {
    {        // SOIL
        {SFX_SOIL_DESTROY_1, SFX_SOIL_DESTROY_2},  // destroy
        {SFX_SOIL_PLACE_1, SFX_SOIL_PLACE_2},      // Place
        // etc - if only one effect, put 2 values the same
    },
    {        // WOOD
        // and so on
    }        
};

And then:

int getSfx (MaterialType material, SoundType sound)
{
    return soundLut [material][sound][rand()%2];
}
2
On

Maybe you can use a map for this purpose with a very similar solution as @Mike (but maybe a bit safer).

void initialize()
{
    // This is your class member.
    // std::map< std::pair< MaterialType, SoundType >, std::pair< int, int > > sfxs;

    sfxs[ std::make_pair( SOIL, DESTROY ) ] = std::make_pair( SFX_SOIL_DESTROY_1, SFX_SOIL_DESTROY_2 );
    sfxs[ std::make_pair( SOIL, PLACE )   ] = std::make_pair( SFX_SOIL_PLACE_1,   SFX_SOIL_PLACE_2 );
    // ...
}

int getSfx( MaterialType aMaterial, SoundType aSound )
{
    const auto key = std::make_pair( aMaterial, aSound );
    if ( sfxs.find( key ) != sfxs.end() )
    {
        return ( rand() % 2 ) ? ( sfxs[ key ].first ) : ( sfxs[ key ].second );
    }
    return -1;
}