- Code a game using a state machine.
- Demonstrate the use of the state pattern.
Exercises
Exercise 6A_TwoStates
Make an alien that can be toggled Active or Inactive by user keystrokes. When the user presses ‘A’ the alien becomes active and animated. When the user presses ‘I’ the alien becomes inactive and motionless.
- Use the transition table and state diagram:
| Press 'A' | Press 'I' | |
|---|---|---|
| S0 (Initial state) |
S1 | S0 |
| S1 | S1 | S0 |
- Then create a Finite State Machine (FSM) class using the FSM class from the framework. You'll also need to create two states using the framework's State class.
- When there are just a few classes like this example, you could code them as inner classes. Later, when you are dealing with lots of classes, you may wish to even create a States container class to contain them all. This is encapsulation.
Exercise 6B_ThreeStates
- Draw a state diagram for a three-state alien, which can be Active, Inactive, or Moving depending on user key presses. Use pencil and paper, or UMLet.
- Then code to the diagram.
- When in the Moving state the alien should move randomly around the screen.
Exercise 6C_BlockBreaker
The Block Breaker game is played as follows. A paddle at the bottom of the screen can move left and right using keystrokes. Blocks are positioned in a stationary matrix (2D array) near the top. A ball appears directly below the blocks and falls toward the South edge. The paddle must move to the ball to make it bounce off the paddle up toward the blocks. When a block is hit by the ball, the ball bounces off the block, and the block disappears. The game is won when all the blocks are gone. The game is lost when the ball gets past the paddle and strikes the South edge.
- Code the game using a paddle, an array of blocks, a bouncing ball, and an FSM class.
- Consider using some typical states: Setting Up, Playing, Game Won, Game Lost, and Retry Screen.
- Here's a state diagram and transition table you can use if you'd like:
Exercise 6D_BlockBreakerPlus
Add barriers to your game for the ball to bounce off.
Challenges
Challenge 6E_SpaceAliensFSM
Enhance your Space Aliens code to make a full game of play using the following states: Start Screen, Setting Up, Playing, Game Won, Game Lost, and Retry Screen.
- Add barrier sprites for your ship to hide behind.
- Fireballs cannot penetrate the barriers.
- Also, your ship’s missiles should not penetrate the barriers.
- Have two kinds of aliens in the alien group so that each type shoots a different kind of fireball. This is polymorphism.
If a transition from one state to the next does not require an event or action,
then you may want to use the FSM's state change listener.
For more on the two ways of representing a finite
state machine, see
Formal FSM Definition and
Transition Monoid.
For instructions on using the state change listener, consult the Book.