Strangely Consistent

Musings about programming, Perl 6, and programming Perl 6

June 10 2011: a moon lander

The good news: you've made it all the way to the moon. Congratulations!

The bad news: due to a terrible misjudgment, your moon lander doesn't have as much fuel available as would be desirable. It will take all your concentration to make a soft touch-down. Use the fuel you have, by all means, but not too soon! (Also, don't use it too late.)

Here we go.

my $altitude = 70;
my $velocity = 0;
my $fuel     = 7;

my $LANDER = "<|";
my $GROUND = "|";

loop {
    my $int_alt = $altitude.Int;
    my $view = " " x (70 - $int_alt) ~ $LANDER ~ " " x $int_alt ~ $GROUND;

    say $view;
    say "Altitude: $altitude -- Velocity: $velocity -- Fuel: $fuel";

    given prompt "command> " {
        when "thrust" {
            if $fuel > 0 {
                $fuel--;
                $velocity += 3;
            }
            else {
                say "You can't, you're out of fuel!";
            }
        }
        when "wait" {
            # Waiting means doing nothing
        }
        when "quit" {
            say "Good-bye. It was nice trying to land with you.";
            last;
        }
        default {
            say "Available commands:";
            say "";
            say "thrust -- fire the thruster";
            say "wait   -- don't fire the thruster";
            say "quit   -- exit the simulation";
            say "help   -- get this list of commands";

            redo;
        }
    }

    $velocity -= 1.5;
    $altitude += $velocity;

    if $altitude <= 0 {
        last;
    }
}

if $velocity >= -3 {
    say " " x 70, $LANDER, $GROUND;
    say "You land softly on the moon.";
}
else {
    say " " x 70, "*#", $GROUND;
    say "You crash fatally into the moon's surface.";
    say "Condolences will be sent to your family.";
}

say "Thanks for playing.";

Slightly longer than we've seen so far, but that's just because it's quite a nice game. There's nothing especially new in there.

Well, there are a few things that deserve a mention:

Have fun playing! I know I did. The moon is harder than it looks. :-)