Mike Austin's Blog

Wednesday, October 19, 2005

Another simple example in Dylan

Here is another example using Dylan, slightly incomplete for brevity.
// Let's define a base class for our objects
define class <actor> (<object>)
// Each slot is initialized in each object instance
slot position = make (<vector>, size: 2);
slot velocity = make (<vector>, size: 2);
slot radius = 1.0;
slot mode = #"normal";
end;

// And here we have a few subclasses of <actor>
define class <ship> (<actor>) end;
define class <rock> (<actor>) end;

// A ship collided with a rock, let's do something
define method actor-collided (ship :: <ship>, rock :: <rock>)
format-out ("Ship collided with a rock!\n");
end;

// No matter what state, advance the actor's position
define method actor-tick (actor :: <actor>, mode :: <symbol>)
actor.position := actor.position + actor.velocity;
end;

// If the ship is in "boost" mode, make it accelerate
define method actor-tick (ship :: <ship>, mode == #"boost")
next-method(); // calls any other applicable methods
ship.velocity := ship.velocity * 1.1;
end;

// Now lets make a ship and a rocks container
let ship = make (<ship>);
let rocks = vector (make (<rock>), make (<rock>));

while (1)
// Advance the ship and each rock, and check for collisions
actor-tick (ship, ship.mode);
for (rock in rocks)
actor-tick (rock, rock.mode);
if (distance-to (ship, rock) < ship.radius + rock.radius)
actor-collided (ship, rock);
end;
end;
end;

0 Comments:

Post a Comment

<< Home