ActionScript 3.0 Design Patterns

(Chris Devlin) #1

316 | Chapter 8: Observer Pattern


When you test the script, you’ll find that when you fire on the Android, only the


Earthling’s hit can be seen as recorded. That’s because both the Alien and Earthling


are hit by the same double-beam, and the Alien’s hit is recorded and broadcast first,


quickly followed by the Earthling’s hit. As a result, you can see only the Earthling’s


beam hit. Figure 8-6 shows the game after the Alien ship has been destroyed, and the


Earthling’s still sustaining hits from the Android beam, but because the Alien stops


receiving messages after it is destroyed, it doesn’t show the additional hits on the


Earthling.


While this example is not a true game, it does illustrate the great possibilities for


sending score information to different subscribers in different formats. Likewise, it


illustrates how the Observer design pattern effortlessly handles rapidly changing data


through a single subject, and then quickly distributing it to different subscribers.


if (torpedo.hitTestObject(earthlingMC) && lFlag==0)
{
lFlag=1;
eKiller++;
scoreSetter.setScore (eKiller,"Earthling Hit");
dataOut ( );
if (eKiller >= 5)
{
scoreSetter.setScore (eKiller,"Earthling Out");
earthling.nomDeGuerre="Earthling Off";
this.earthlingMC.rotation=90;
missile.rotation=90;
killWarrior (earthling);
dataOut ( );
}
}
}


//Output Data
private function dataOut ( )
{
for (var i:int = 0; i < battleUpdate.length; i++)
{
battleUpdate[i].text=warrior[i].nomDeGuerre+
":\n"+warrior[i].passOn( );
}
}
//Kill zone
public function killWarrior (warship:ConcreteObserver)
{
scoreSetter.unsubscribeObserver (warship);
}
}
}


Example 8-19. ChangeHandler.as (continued)

Free download pdf