10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

declaring it as abstract in the Component class makes sense. We can now draw the<br />

whole snake.<br />

Building the Composite Snake<br />

Example 6-17 shows the updated constructor of the Main class from Example 6-14<br />

that constructs the whole snake. Lines 10- 25 add the body segments to the snake in<br />

black and gray alternating colors. Finally, the tail <strong>com</strong>ponent is added in lines 26<br />

through 28. The update( ) method is called once (line 30) to fit and display all <strong>com</strong>ponents<br />

on the stage as they’re initially placed offscreen (line 22). The <strong>com</strong>pleted<br />

snake should look like Figure 6-6.<br />

Example 6-17. Updated constructor in Main.as<br />

1 public function Main( )<br />

2 {<br />

3 // create snake<br />

4 snake = new Head( );<br />

5 snake.x = snake.y = 200;<br />

6<br />

7 // add snake to stage<br />

8 addChild(snake);<br />

9<br />

10 // add multiple body segments<br />

11 var parentNode:Composite = snake;<br />

12 var color:uint;<br />

13 for (var i:uint = 0; i < 10; i++)<br />

14 {<br />

15 if (i % 2) {<br />

16 color = 0x000000; // black<br />

17 } else {<br />

18 color = 0xC0C0C0; // grey<br />

19 }<br />

20 var segment:Composite = new BodySegment(color);<br />

21 parentNode.add(segment);<br />

22 segment.x = segment.y = -50; // place it off screen<br />

23 addChild(segment);<br />

24 parentNode = segment;<br />

25 }<br />

26 var tail:Component = new Tail( );<br />

27 addChild(tail);<br />

28 parentNode.add(tail); // add rattle<br />

29<br />

30 snake.update( ); // to fit the segments together<br />

31<br />

32 // register with the stage to receive key press events<br />

33 stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPress);<br />

34 }<br />

232 | Chapter 6: Composite Pattern

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!