lundi 11 février 2019

2048 Game over funtion

I have made a function called game_over which returns a boolean based on whether a grid representing a 2048 game is in a game over situation. If it is it returns false if it is not it would return true.

The function works perfectly except in one situation where there is a zero in the bottom right or bottom left corner and I can not figure out why this is. I have tried changing the limits to length -1 but this had no effect. It should if there is a zero in the bottom left or right immediately return false as it goes into the first for loop which checks if there is a zero. What is going on here?

bool game_over(const std::vector<int>& v){

int length = std::sqrt(v.size());

for (int i = 0; i < length; i++){
     if (v[i] == 0){
         return false;
     }
}

for( int i= 0; i < length ; i++ ){
    for( int j = 0; j < length; j++){

        int x = v[twod_to_oned(i, j, length)];

        if (i < length   && x == v[twod_to_oned(i+1, j, length )]){
            return false;
        }

        if (j < length  && x == v[twod_to_oned(i, j+1, length)]){
            return false;
        }
    }
}
return true;
}


int twod_to_oned(int row, int col, int rowlen){
    return row*rowlen+col;
}

Aucun commentaire:

Enregistrer un commentaire