redundant6939
redundant6939

Reputation: 153

Messy for loop/if statement

Im doing a pacman game. The following code is for ghosts movement and it works correctly. But I have to include a another check. The problem is that I always ruin the logic.

Current code:

public void moveGhost(Tiles target) {
    if(specialIntersections()){
        direction = direction; //keeps going in the same direction
    }
    else{
        int oppDir;
        if(direction == UP){
            oppDir = DOWN;
    }
    else if(direction == DOWN){
        oppDir = UP;
    }
    else if(direction == LEFT){
        oppDir = RIGHT;
    }
    else{
        oppDir=LEFT;
    }

    double minDist = 10000.0;
    Tiles potentialNext;

    for(int i=0; i<4; i++){
        if(i!=oppDir){
            potentialNext = maze.nextTile(getCurrentPos(), i);
            if(!(potentialNext.wall()) && check(potentialNext)){
                if(calculateDistance(target, potentialNext) < minDist){
                   minDist = calculateDistance(target, potentialNext);
                   futureDirection = i;
                }
            }
        }
    }
}


changeDirection();
timer++;
increment();

x += xinc;
y += yinc;
tunnel();

}

Another check I need to include:

  //if the door is a wall (closed) the object cannot go through it
  if(DoorIsWall()){
if(!(potentialNext.wall()) && !(potentialNext.door())  && check(potentialNext)){ 

Upvotes: 0

Views: 109

Answers (1)

jahroy
jahroy

Reputation: 22692

I generally write a new method when my conditions start to get unruly:

if (isTileValid(potentialNext)) {
    // do stuff
}


private boolean isTileValid(TileObject someTile) {
    if (someTile.wall()) {
        return false;
    }
    if (someTile.door()) {
        return false;
    }
    if (! check(someTile)) {
        return false;
    }
    return true;
}

Upvotes: 2

Related Questions