Maze Game: Sample Program
0406.pl
#!/usr/bin/perl
use strict;
require Term::Screen;
use Time::HiRes qw (usleep);
#
# To student:
# Note that this program uses literals where variables and
# constants should be used - fix this after copying!
#
# Only try patching this code into your program *after*
# tonic/poison/exit handled fully and correctly
#
my $notover = 1;
my $count = 1;
my $keystroke;
# Locate bad guy (for demo purposes only, using literal values)
my $badguy = "B";
my $badx = 37;
my $bady = 6;
# Init screen
my $scr=new Term::Screen;
$scr->clrscr();
# Open and read map file
open LAUNDRYBASKET, "< mapfile.txt";
my @map = <LAUNDRYBASKET>;
close LAUNDRYBASKEY;
# Draw map on screen, putting copy in mem for reference
my $x = 0;
my $y = 0;
my ($line, @items, $smellycat, @biggerdeeperwidermap);
foreach $line (@map) {
chomp $line; # Eat any EOL from the file
# Map uses ':' to separate chars; all chars including spaces must be separated leading to:
# such as this =: :=:=:=:=:=:=:=:=:=:=:=:=:=:=:=:=: :=:
@items = split(':', $line);
push @biggerdeeperwidermap, [@items];
$x = 0; # Failure to reset x leads to map flowing to right over successive lines
# Coords in paterrn Y,X - DONT FORGET!
foreach $smellycat (@items) {
$scr->at($y, $x)->puts($smellycat);
$x++;
}
$y++;
}
# Start main loop ('game') until end (eq "Q" or "q")
while ($notover) {
if ($scr->key_pressed()) {
$keystroke = $scr->getch();
if (($keystroke eq "q") || ($keystroke eq "Q")) {
$notover = 0;
}
}
$scr->at($bady,$badx)->puts($badguy)->at(20,0); # MAKE CURSOR 'DISAPPEAR' after positioning???
$count++;
usleep (100000);
&moveman();
}
sub moveman () {
# Move the bad guy
# [snicker] much more evillor than skeletor
my $moved = 0;
my $newy = $bady;
my $newx = $badx;
my $dir;
# use $moved as a semaphore
my $random = int(rand(100))+1; # This I is so A it's I all over again <:{}
# To student: how does the bad guy 'decide' how to move?
if ($random % 2) {
if ($biggerdeeperwidermap[$bady-1][$badx] eq " ") { # Move up?
$moved = 1; $dir="UP"; $newy -= 1;
}
elsif ($biggerdeeperwidermap[$bady][$badx+1] eq " ") { # Move right?
$moved = 1; $dir="RIGHT"; $newx += 1;
}
}
else {
if ($biggerdeeperwidermap[$bady+1][$badx] eq " ") { # Move down?
$moved = 1; $dir="DOWN"; $newy += 1;
}
elsif ($biggerdeeperwidermap[$bady][$badx - 1] eq " ") { # Move left?
$moved = 1; $dir="LEFT"; $newx -= 1;
}
}
# Did we find a place to move to?
if ($moved == 1) {
$scr->at($bady, $badx)->puts(" ");
$bady = $newy;
$badx = $newx;
$scr->at($bady, $badx)->puts("B");
}
# This is debug stuff:
$scr->at(40,40)->puts("$badx, $bady, $dir")->clreol();
} # endsub moveman
Last updated: 20120312-13:54