java - 状态管理-【切换状态,重玩游戏】

标签 java user-input slick2d 2d-games state-management

如何有效切换状态?每当我按下重播按钮时,两种状态就会交替显示(win & play)。我相信这是一个无限循环,但 Eclipse 不会打印任何错误。

当我尝试this时,结果为null。从而结束游戏。 可以this是答案吗?但我不明白他的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);
          }
       }
    }
}

最佳答案

我认为您一次又一次地在两种状态之间切换,因为当您切换回来时,两个 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坐标某些y坐标之间。

我认为您想检查鼠标是否位于某些 x AND 某些 y 坐标之间:

  if((x>160 && x<180)&&(y>280 && y<320)){

关于java - 状态管理-【切换状态,重玩游戏】,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226694/

相关文章:

java - 使用 Apache Spark 将数据从一个数据库传输到另一个数据库的 ETL 过程

java - 如何在 Jasper 中找出 String[] 的大小

java - 使用着色器时纹理不渲染?

Java for 循环 - (i * 16) 对 i 的所有值求值为 0

java - Java孤儿案

java - 如何使用IDE mybatis在插入/选择/更新数据库之前自动修剪参数

c# - 输入字符串的格式不正确

matlab - 丢弃连续调用输入之间的键盘事件 (MATLAB)

c++ - 我有一个变量,结构中的许多变量之一,我想将信息读入其中

java - UnicodeFont 渲染似乎阻止了其他所有内容的渲染?