Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Roles

Name: Anonymous 2013-09-06 10:16

Roles implement a bit more flexibility in the class-object programming model.
It allows to create "behavoir sets", that cannot be instantiated, but can be applied to other classes or objects.

role SharpShooter {
   method Shoot { say 'Shoot(Precision => 99)' };
   method See   { say 'See(HowFar => 50)' };
}
role Shooter {
   method Shoot { say 'Shoot(Precision => 60)' };
   method See   { say 'See(HowFar => 20)' };
}
role Thief {
   method Steal  { say 'Pickpocket( Smoothness => 50 )' };
   method Escape { say 'Run ( Speed => 50 )' };
}
role Mortal {
   has $.Age;
   method HappyBirthday {
      say 'Unit is One year older';
      $.Age += 1; 
   };
}
role Inmortal {
   has $.Age;
   method HappyBirthday { say 'Unit do not age at all' };
}
class NinjaElf does SharpShooter does Thief does Inmortal {
   method Taunt { say 'I will gladly give my inmortal life for my mission' };
}
class Archer does SharpShooter does Mortal {
   method Taunt { say 'Right between the eyes!' };
}
class ElfArcher is Archer does Inmortal {
   method Taunt { say 'I have been practicing my aiming for a thousand years.'}
}
my NinjaElf  $Unit1 .= new;
my Archer    $Unit2 .= new;
my ElfArcher $Unit3 .= new;
my @Units = $Unit1, $Unit2, $Unit3;
for (@Units) -> $Unit {
   print '*The unit says: ';
   $Unit.Taunt;
   say 'Watch your head'    if $Unit.^does(SharpShooter);
   say 'Watch your pockets' if $Unit.^does(Thief);
}

Output...

*The unit says: I will gladly give my inmortal life for my mission
Watch your head
Watch your pockets
*The unit says: Right between the eyes!
Watch your head
*The unit says: I have been practicing my aiming for a thousand years.
Watch your head

With roles, you can model complex behavoirs and its combinations, without having to stick to a rigid class heriarchy. Being that you can assign roles at runtime also, this allows to to create powerful dynamic objects that can change their behavoir on the fly.

$Unit2 does Thief; # Now our archer has Thief skills

Name: Anonymous 2013-09-06 10:29

>NinjaElf 
>Inmortal
Badly designed RPG by a script kiddie

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List