226 | Chapter 6: Composite Pattern
The snake’s head will be controlled by keyboard events. The next step is to develop
the document class that will build the snake, and register keyboard events to control
the snake.
Controlling the Snake
Example 6-14 shows theMainclass that builds the composite snake structure and
registers event handler methods to control the snake. As a first step, only the snake’s
head will be created (lines 18-23). The arrow keys will make the snake head move
forward, backward, rotate left, and right. The snake’s head will be the free end of the
kinematic chain that represents the snake. Just like the puppeteer’s string pulling on
the marionette’s hand, key presses will pull on the snake’s head and rotate it.
Example 6-13. Head.as
package
{
public class Head extends Composite
{
public function Head(color:uint = 0xC0C0C0)
{
graphics.lineStyle(20, color);
graphics.moveTo(0, 0);
graphics.lineTo(20, 0);
}
}
}
Example 6-14. Main.as
1 package
2 {
3 import flash.display.Sprite;
4 import flash.events.*;
5 import flash.geom.*;
6 import flash.ui.Keyboard;
7
8 /**
9 * Main Class
10 * @ purpose: Document class for movie
11 */
12 public class Main extends Sprite
13 {
14 private var snake:Composite;
15
16 public function Main( )
17 {
18 // create snake
19 snake = new Head( );
20 snake.x = snake.y = 200;
21
22 // add snake to stage