Design a Game by Using Stateflow - MATLAB & Simulink (original) (raw)

Main Content

This example shows how to implement the game of Tetris by using a Stateflow® chart. This model is a redesigned version of the classic Stateflow demo sf_tetris. The new design incorporates these programming paradigms:

Separate Subcomponents by Using Parallel Decomposition

The chart TetrisLogic implements the logic behind the game. The chart consists of three parallel states, which execute in this order:

Simplify Chart Design by Using Hierarchy and Subcharts

By using state hierarchy and subcharts, you can graphically abstract the game logic, present a high-level overview of the flow of the game, and hide the inner complexity of each stage of the game. For example, each substate of the parallel state MainArea represents a separate stage in the flow of the game.

Capture Keyboard Input Through Change Detection

The Moving subchart moves the tetronimo based on the input from the player. By default, the substate MoveSlowly is active. The tetronimo moves slowly down the playing arena while the parallel substates in MoveSlowly monitor the input from the keyboard. If the player presses the space bar, the substate MoveFast becomes active. The tetronimo drops quickly to the bottom of the arena.

To gather input from the keyboard, the subchart uses the change detection operator hasChanged. Every time that the player presses a key, sf_tetris_gui increments an input to the chart, which makes the corresponding hasChanged operator return a value of true. Because MoveSlowly has a parallel decomposition, the chart can process multiple keystrokes each time step.

Key Mappings

To interact with the game UI, use these keys:

See Also

hasChanged

Topics