ActionScript 3.0 Design Patterns

(Chris Devlin) #1

232 | Chapter 6: Composite Pattern


declaring it asabstractin theComponentclass makes sense. We can now draw the


whole snake.


Building the Composite Snake


Example 6-17 shows the updated constructor of theMainclass from Example 6-14


that constructs the whole snake. Lines 10- 25 add the body segments to the snake in


black and gray alternating colors. Finally, the tail component is added in lines 26


through 28. Theupdate( )method is called once (line 30) to fit and display all com-


ponents on the stage as they’re initially placed offscreen (line 22). The completed


snake should look like Figure 6-6.


Example 6-17. Updated constructor in Main.as


1 public function Main( )
2 {
3 // create snake
4 snake = new Head( );
5 snake.x = snake.y = 200;
6
7 // add snake to stage
8 addChild(snake);
9
10 // add multiple body segments
11 var parentNode:Composite = snake;
12 var color:uint;
13 for (var i:uint = 0; i < 10; i++)
14 {
15 if (i % 2) {
16 color = 0x000000; // black
17 } else {
18 color = 0xC0C0C0; // grey
19 }
20 var segment:Composite = new BodySegment(color);
21 parentNode.add(segment);
22 segment.x = segment.y = -50; // place it off screen
23 addChild(segment);
24 parentNode = segment;
25 }
26 var tail:Component = new Tail( );
27 addChild(tail);
28 parentNode.add(tail); // add rattle
29
30 snake.update( ); // to fit the segments together
31
32 // register with the stage to receive key press events
33 stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);
34 }
Free download pdf