2012-11-15 53 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语句,即使是单个语句的语句放在大括号中。这将有助于遏制任何错误,如果你必须稍后添加一些错误(因为看起来你将不得不在这里)。