2012-11-15 178 views
0

對象應該根據流逝的時間(在追逐或分散之間切換)更改模式(移動算法)。我創建了一個while循環,但對象只在一種模式下(追逐)移動,這很奇怪,因爲我將它設置爲初始分散。雖然循環無法正常工作

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; 
} 
+4

'ghostAlive'永遠不會被初始化。如果是這樣,這個「while」循環將是無限的,因爲它永遠不會更新。 – squiguy

回答

1

你的評論說它從scatterMode開始,但是你在聲明它的時候不會設置任何模式。所以,它實際上默認爲chaseMode。因爲您不初始化布爾值ghostAlive,所以它默認爲false,這意味着您的循環不會發生,這意味着模式不會設置爲scatterMode,這意味着它始終保留在chaseMode中。

要開始解決這個問題,您應該初始化ghostAlive爲true。然後,對於所有ifs,您可以使用ghostAlive = false語句來結束循環。我不完全確定你在整個項目中使用這種方法的目的是什麼,但是這一點知識應該可以幫助你。您必須在循環內以某種方式使ghostAlive爲false才能退出循環。

不知道你爲什麼要使用所有這些靜態方法和字段。對於你發佈的內容來說似乎沒有必要。

此外,最好將if語句,即使是單個語句的語句放在大括號中。這將有助於遏制任何錯誤,如果你必須稍後添加一些錯誤(因爲看起來你將不得不在這裏)。