Arranging function in Bejeweled

Started by
1 comment, last by c4c0d3m0n 16 years, 10 months ago
I've rewritten the function that rearranges my Bejeweled field twice already, and it still doesn't work! The first version used to crash my game immediately, the second version actually does rearrange, but it causes some very random bugs (it screws with the selector position and state, and it makes the game hang up when certain matches of 3 jewels occur) My question: Why doesn't this function work properly? The function:
// Moves jewels in tetris style and returns amount of successions
int iRearrange()
{
    if( DEBUG ) {
        debugsz = "Rearranging jewels";
    }
    
    int result = 0;
    
    for( int i = FIELD_SIZE; i > 0; i-- ) {
        for( int j = 0; j < FIELD_SIZE; j++ ) {
            cell& current = field[j];
            cell& above = field[i-1][j];

            if( !current.used ) {
                if( above.used ) {
                    current.used = true;
                    current.jewel = above.jewel;
                    above.used = false;
                    result++;
                }
            }
        }
    }
    
    for( int i = 0; i < FIELD_SIZE; i++ ) {
        cell& c = field[0];
        
        if( !c.used ) {
            c.used = true;
            c.jewel = rand() %7;
            result++;
        }
    }
    
    return result;
}

It's usage:
        while( iCheckMatches() > 0 ) { // Check for matches
            bejstate = REMOVING;
            iscore+= iRemoveMatches(); // Remove matches
            updateScreen( bejstate );
            Sleep( 500 );
            
            while( iRearrange() > 0 ) { // Rearrange until everything is arranged :)
                bejstate = ARRANGING;
                updateScreen( bejstate );
                Sleep( 500 );
            }
        }
Advertisement
The problem I see is:

for( int i = FIELD_SIZE; i > 0; i-- )

You're accessing outside the bounds of the field array. It should be:

for( int i = FIELD_SIZE - 1; i > 0; i-- )

This would overwrite some variables declared after the field array.

This isn't an off by one error, but an off by FIELD_SIZE error. This would be sizeof(cell) * FIELD_SIZE bytes from the end of the array.

This is a common error, and usually the first thing that I would suspect, given the conditions you are seeing.

Check out Super Play, the SNES inspired Game Engine: http://www.superplay.info

Damnit, I knew it was going to be a simple mistake like that that was bugging! Thanks heaps, my game works now :D *yay* I can post the full source code on demand

This topic is closed to new replies.

Advertisement