如何有效地切换状态?每当我按下重播按钮时,两种状态都会交替显示(win & play)。我相信这是一个无限循环,但是Eclipse不会打印任何错误。
当我尝试这时,结果是null.Thus,结束了游戏。这是答案吗?但我不明白他的Update()。到底要写什么?这会覆盖状态类的更新吗?
这里是我的代码: stateID(2)是Wins.java
PlayGround.java
public static boolean bouncy = true;
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException{
//if the user is successful, show winner state
if(!bouncy){
sbg.enterState(2);
}
//moves the image randomly in the screen
new Timer(10,new ActionListener(){
public void actionPerformed(ActionEvent e)
{
posX = (r.nextInt(TestProject4.appGC.getWidth()-75));
posY = (r.nextInt(TestProject4.appGC.getHeight()-75));
}
}).start();
}
public void mousePressed(int button,int x,int y){
//if the user pressed the mouse button And
//if the user's coordinates is inside the hit area(rect)
if((button == 0) && (rect.contains(x, y))){
Toolkit.getDefaultToolkit().beep();
bouncy = false;
}
}Wins.java
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
//replay game
if(backToGame == true){
sbg.enterState(state);
}
}
public void mousePressed(int button,int x,int y){
//if the user clicks the replay button
if(button == 0){
if((x>160 && x<260)&&(y>280 && y<320)){
if(Mouse.isButtonDown(0)){
backToGame = true;
state = 1;
}
}
//exit button
if((x>=360 && x<460)&&(y>280 && y<320)){
if(Mouse.isButtonDown(0)){
System.exit(0);
}
}
}
}发布于 2014-08-11 12:42:41
我认为您一次又一次地在这两种状态之间切换,因为当您切换回来时,两个GameState对象仍然处于相同的“状态”(变量仍然有相同的值)。
尝试:
if(!bouncy){
bouncy = true; // next time we are in this game state it will not trigger immediately
sbg.enterState(2);
}
if(backToGame == true){
backToGame = false; // same here
sbg.enterState(state);
}先前的答复:
请检查您的if语句:
if((x>160 && x<180)||(y>280 && y<320)){您正在检查鼠标是否位于x坐标、OR、y坐标之间。
我认为您需要检查鼠标是否位于某些x AND和y坐标之间:
if((x>160 && x<180)&&(y>280 && y<320)){发布于 2014-08-11 22:58:55
您的代码有两个方法mousePressed(),一个在PlayGround.java中,另一个在Wins.java中。应用程序显然使用了Playground.java代码。
在PlayGround.java中添加按钮检测代码可以解决这个问题。
其他明智的方法在Wins中显式调用mousePressed()方法也可能有效。
添加注释会有所帮助。它可以显示你对一个项目的思路,帮助其他人试着看看你在做什么。在充实一种复杂的方法时,我一开始评论过度,通过反复的调试和代码评审来剔除明显的注释。当其他人正在查看您的代码时,我也会提供帮助。记住,没有愚蠢的评论,只有愚蠢的人。
https://stackoverflow.com/questions/25226694
复制相似问题