user1822333
user1822333

Reputation: 1

While loop doesn't work properly

Object is supposed to change mode (movement algorithm) depending on the time elapsed (switch between chase or scatter). I created a while loop but the object moves only in one mode (chase) and that is strange since I set it to be scatter initially.

private static int seconds=0;
private static boolean ghostalive;

protected static final int chaseMode = 0;
protected static final int scatterMode = 1;
protected static final int frightenedMode = 2;

static int mode; //initially ghost start in scatterMode

public Ghost(int x, int y, Maze maze){
    super(x, y, maze);
    futureDirection = 0;
    timer = 0;
    mode = getMode();
}     

public static int getMode(){
    mode=setMode();
    return mode;
}

//LEVEL 1
//scatter for 7s 
//chase for 20s 
//scatter for 7s 
//chase for 20s 
//scatter for 5s 
//chase for 20s
//scatter for 5s 
//chase indefinite

public static int setMode(){

while(ghostalive){

    mode = scatterMode;
    if(seconds>7)
        mode = chaseMode;//chaseMode=true;
    if(seconds>27)
        mode = scatterMode;
    if(seconds>34)
        mode = chaseMode;
    if(seconds>54) 
        mode = scatterMode;
    if(seconds>59) 
        mode = chaseMode;
    if(seconds>79)
        mode = scatterMode;
    if(seconds>84)
        mode = chaseMode;

    seconds++;      
   }    
       return mode;
}

Upvotes: 0

Views: 224

Answers (1)

AHungerArtist
AHungerArtist

Reputation: 9599

Your comment says it starts in scatterMode, but you don't set the mode to anything when it's declared. So, it actually defaults to chaseMode. Because you don't initialize the boolean ghostAlive, it defaults to false, meaning your loop never happens, which means the mode doesn't get set to scatterMode, which means it always stays in chaseMode.

To begin to fix this, you should initialize ghostAlive to true. Then, for all the ifs, you can put a ghostAlive = false statement to end the loop. I'm not exactly sure what your objective is with this method in context of your whole project, but that bit of knowledge should help you out either way. You have to make ghostAlive false inside the loop somehow to get out of the loop.

Not sure why you're using all these static methods and fields, though. Seem unnecessary for what you've posted.

Additionally, it's good practice to put if statements, even single statement ones, in curly brackets. This will help curb any errors if you have to later add some (as it appears you will have to here).

Upvotes: 1

Related Questions