using Nemerle.Utility; using System.Console; class World { person_1 : Person; person_2 : Person; person_3 : Person; [Accessor] random_generator : System.Random = System.Random (); public GetPersonAt (x : int, y : int) : Person { // OK, this looks a bit stupid, but we didn't go into containers yet if (person_1 != null && person_1.X == x && person_1.Y == y) person_1 else if (person_2 != null && person_2.X == x && person_2.Y == y) person_2 else if (person_3 != null && person_3.X == x && person_3.Y == y) person_3 else null } public this () { person_1 = LukeSkywalker (this); person_2 = DarthVader (this); person_3 = null; // noone else is here } public Display () : void { mutable result = "\n\n\n"; for (mutable y = 0; y < 10; ++y) { mutable line = ""; for (mutable x = 0; x < 20; ++x) { def person = GetPersonAt (x, y); if (person == null) line += ". " else line += person.Name + " " } result += line + "\n"; } result += "Press enter..."; WriteLine (result); ReadLine (); } public PerformTurn () : void { when (person_1 != null) person_1.PerformMove (); when (person_2 != null) person_2.PerformMove (); when (person_3 != null) person_3.PerformMove (); } } abstract class Person { [Accessor] protected mutable x : int; [Accessor] protected mutable y : int; protected world : World; public abstract PerformMove () : void; public abstract Name : string { get; } protected RandomWalk () : void { def dir = world.RandomGenerator.Next (4); if (dir == 0 && x < 19) x++ else if (dir == 1 && x > 0) x-- else if (dir == 2 && y < 9) y++ else if (dir == 4 && y > 0) y-- else PerformMove (); // try again } protected Chase (target : Person) : void { def dx = target.X - X; def dy = target.Y - Y; if (dx == 0 || (dy != 0 && world.RandomGenerator.Next (2) == 0)) if (dy == 0) { // do nothing } else if (dy > 0) y++ else y-- else if (dx > 0) x++ else x-- } public this (w : World) { world = w; x = world.RandomGenerator.Next (20); y = world.RandomGenerator.Next (10); } } class DarthVader : Person { public override Name : string { get { "V" } } public override PerformMove () : void { // check if we can see Luke mutable luke = null; for (mutable dx = -3; dx <= 3; ++dx) for (mutable dy = -3; dy <= 3; ++dy) { def person = world.GetPersonAt (X + dx, Y + dy); when (person != null && person.Name == "L") luke = person; } if (luke == null) { RandomWalk (); } else if (luke.X == X && luke.Y == Y) { WriteLine ("Gotch ya! Game over!"); System.Environment.Exit (0); } else { Chase (luke) } } public this (w : World) { base (w); } } class LukeSkywalker : Person { public override Name : string { get { "L" } } public override PerformMove () : void { RandomWalk (); } public this (w : World) { base (w); } } def world = World (); while (true) { world.PerformTurn (); world.Display (); }