Skip to content

Instantly share code, notes, and snippets.

@ttowncompiled
Last active October 10, 2018 14:07
Show Gist options
  • Save ttowncompiled/5b35915e2ec9b96debc3e1cb3699a6a6 to your computer and use it in GitHub Desktop.
Save ttowncompiled/5b35915e2ec9b96debc3e1cb3699a6a6 to your computer and use it in GitHub Desktop.
A basic example of the Strategy pattern implemented in Rose.
use std::util::Random
pub abs trait MeleeAttackBehavior begin
pub abs def meleeAttack(self: &Self) -> Int
end
pub abs trait RangedAttackBehavior begin
pub abs def rangedAttack(self: &Self) -> Int
end
pub trait Melee3d6 impl MeleeAttackBehavior begin
pub def meleeAttack(self: &Melee3d6) -> Int do
let rnd := new Random()
rnd.nextInt(6)+rnd.nextInt(6)+rnd.nextInt(6)+3
end
end
pub trait Melee2d4 impl MeleeAttackBehavior begin
pub def meleeAttack(self: &Melee2d4) -> Int do
let rnd := new Random()
rnd.nextInt(4)+rnd.nextInt(4)+2
end
end
pub trait Ranged2d4 impl RangedAttackBehavior begin
pub def rangedAttack(self: &Ranged2d4) -> Int do
let rnd := new Random()
rnd.nextInt(4)+rnd.nextInt(4)+2
end
end
pub trait NoRangedAttack impl RangedAttackBehavior begin
pub def rangedAttack(self: &NoRangedAttack) => 0
end
pub abs class Character begin
health: Int
has melee: impl MeleeAttackBehavior
has ranged: impl RangedAttackBehavior
pub Character(self: &mut Character, health: Int, melee: impl MeleeAttackBehavior, ranged: impl RangedAttackBehavior) do
self.health = health
self.melee = melee
self.ranged = ranged
end
pub def wound(self: &mut Character, dmg: &Int) -> Bool do
self.health = (self.health > dmg) ? self.health-dmg : 0
self.health == 0
end
end
pub class Knight ext Character begin
pub Knight(self: &mut Knight) => self.super(18, new Melee3d6(), new NoRangedAttack())
end
pub class Rogue ext Character begin
pub Rogue(self: &mut Rogue) => self.super(12, new Melee3d6(), new Ranged2d4())
end
pub class GiantRat ext Character begin
pub GiantRat(self: &mut GiantRat) => self.super(10, new Melee2d4(), new NoRangedAttack())
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment