vendredi 29 novembre 2019

Random movement algorithm in C

I'm basically trying to write down a very basic algorithm that lets a char "move" into a preset map of chars.

What I need to do, is to get the char moving to a next position which must be empty (checked with == ' ' over the map matrix values); if there are both horizontal or vertical need to chose one randomly.

What I've done so far is VERY messy: I first check if there's an empty tile next to the char, if there is one, check if vertically both next tiles are free, if free chose one randomly, then do the same for X axis. If neither vertical\horizontal axis has both free next tiles, find one free and set it as the direction taken.

Now, I don't know if the logic is actually correct but I couldn't come to a better AND working solution. Open to any suggestion.

if(map[charPos.y-2][charPos.x-1] == ' ' || map[charPos.y][charPos.x-1] == ' '
|| map[charPos.y-1][charPos.x-2] == ' ' || map[charPos.y-1][charPos.x] == ' '){

if ((map[charPos.y-2][charPos.x-1] == ' ' && map[charPos.y][charPos.x-1] == ' ')
    || (map[charPos.y-1][charPos.x-2] == ' ' && map[charPos.y-1][charPos.x] == ' ')){
    if ( map[charPos.y-2][charPos.x-1] == ' ' && map[charPos.y][charPos.x-1] == ' '){
        chosenDir = rand() % (DIR_DW - DIR_UP + 1) + DIR_UP;
    } else if (map[charPos.y-1][charPos.x-2] == ' ' && map[charPos.y-1][charPos.x] == ' '){
        chosenDir = rand() % (DIR_RT - DIR_LT + 1) + DIR_LT;
    }
} else if(map[charPos.y-2][charPos.x-1] == ' '){
                chosenDir=DIR_UP;
} else if(map[charPos.y][charPos.x-1] == ' '){
                chosenDir=DIR_DW;
} else if(map[charPos.y-1][charPos.x-2] == ' '){
                chosenDir=DIR_LT;
} else if(map[charPos.y-1][charPos.x] == ' '){
                chosenDir=DIR_RT;
}
}

switch (chosenDir){
    case DIR_UP: {
        charPos.y-=1;
    }
    case DIR_DW: {
        charPos.y+=1;
    }
    case DIR_LT: {
        charPos.x-=1;
    }
    case DIR_RT: {
        charPos.x+=1;
    }
}



Aucun commentaire:

Enregistrer un commentaire