League Invaders Pt. 6
Game States
Our game is going to have 3 primary states:
1. a menu state that shows our title screen
2. a game state that shows the game while in play
3. a end state that shows the game over screen
1. Delete all references of your GameObject object in your GamePanel class.
2. In your GamePanel class, create three final integer variables and set them equal to different numbers.
final int MENU_STATE = 0;
final int GAME_STATE = 1;
final int END_STATE = 2;
3. Create a fourth int variable (not final) called currentState. This will keep track of the state that the game is currently in. Set it equal to MENU_STATE.
4. Create a void method for updating each state called updateMenuState, updateGameState, and updateEndState.
5. Create a void method for drawing each stated called drawMenuState, drawGameState, and drawEndState. Make each of these methods take in a Graphics object as a parameter the same as the paintComponent method
6. In the actionPerformed method, create a series of if/else statements to check what state the currentState variable is in. Call the appropriate method inside the if/else block.
EXAMPLE:
if(currentState == MENU_STATE){
updateMenuState();
}else if(currentState == GAME_STATE){
updateGameState();
}else if(currentState == END_STATE){
updateEndState();
}
7. Do the same thing in the paintComponent method except call the appropriate draw method. Make sure you pass in the Graphics object (g) from the paintComponent method.
8. Go to the drawMenuState method and draw a blue rectangle that covers the entire width and height of the window.
g.setColor(Color.BLUE);
g.fillRect(0, 0, LeagueInvaders.WIDTH, LeagueInvaders.HEIGHT);
9. Draw a black screen in the drawGameState method and draw a red screen in the drawEndState method
10. In the keyPressed method, check if the ENTER key is pressed. If it is pressed, change the state to the next state. If the current state is the end state, then go back to the menu state.
if(currentState > END_STATE){
currentState = MENU_STATE;
}
11. Run your program. Every time the ENTER key is pressed, you should see the screen change colors.