Specifying a Sprite with a Statechart

A sprite is a reactive object: it responds dynamically to events, changing its state and modifying its behavior. For all but the simplest example, specify the sprite's behavior before becoming entangled in writing code. The UML statechart is an excellent tool for defining a sprite, and there are even utilities for automatically generating Java code from statecharts.

The rest of this section gives a brief introduction to statecharts and explains how they can be translated to Java. However, this isn't a book about UML, so I refer the interested reader to UML Distilled (Addison-Wesley Professional) by Martin Fowler. For a UML text with a Java slant, check out UML for Java Programmers (Prentice Hall) by Robert C. Martin (http://www.objectmentor.com). Martin's web site offers SMC, a translator that takes textual statechart information and generates Java (or C++) code.

A simple statechart for a subway turnstile is shown in Figure 11-4. (This example comes from a tutorial by Robert C. Martin.)

A subway turnstile statechart

Figure 11-4. A subway turnstile statechart

The states are inside rounded rectangles; the transitions (arrows) indicate how the system responds to events. The syntax for a transition is:

    event [ condition ] / action

An event arrives when the system is in a given state, causing the associated transition to be executed. First, the condition is evaluated if one is present. ...

Get Killer Game Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.