How to effectively switch states?Whenever I press the replay button, the two states shows alternatively (win & play). I believe that was an infinite loop but Eclipse does not print any errors.
When I tried this, it results to null.Thus, ending the game. Could this be the answer? But I don't understand his Update(). What to put exactly there?will that overwrite the update of the state class?
Here is my code: stateID(2) is the 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);
}
}
}
}
I think you switch between both states again and again because both GameState objects are still in the same "state" (variables have still the same values) when you switch back.
Try:
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);
}
Previous answer:
Please check your if statement:
if((x>160 && x<180)||(y>280 && y<320)){
You are checking whether the mouse is between some x coordinates OR
some y coordinates.
I think you want to check whether the mouse is between some x AND
some y coordinates:
if((x>160 && x<180)&&(y>280 && y<320)){