There are a goodly number of smallish issues in your code and a few outright bugs. Some of the issues clean up if you go back and re-read the scoping reply I wrote above.
I've reworked your current code to clean up variable scope and to correctly handle lines and collision detection. Look carefully at how @xloc is managed.
I've also removed the END block code and instead put the main work in a sub wrapped by appropriate ReadMode calls.
As icing a few blank lines are put at the start of the run to give skiers time to get their eye in and you can tune the number of trees generated per line.
#!/usr/bin/perl
use strict;
use warnings;
use Win32::Console::ANSI;
use Term::ANSIScreen qw/:color :cursor :screen/;
use Term::ReadKey;
my $kLines = 50;
my $kWidth = 80;
my $kMaxTrees = 5;
my $kPractise = 5;
ReadMode('cbreak');
cls;
run();
ReadMode('restore');
sub run {
my @xloc;
locate 1, 1;
my $hLen = ($kWidth - 15) / 2 - 10;
print ' ' x 5, '-' x $hLen, " Ready Set GO! ", '-' x $hLen;
push @xloc, ' ' x $kWidth for 1 .. 4;
push @xloc, newLine($kWidth) for 1 .. $kLines - 2;
locate 2, 1;
print join "\n", @xloc, '';
my $wait = 1;
my $skierx = $kWidth / 2;
my $y = $kLines;
my $score = 0;
while (1 < 2) {
my $key = ReadKey(-1);
if (defined $key) {
# here when key pressed
--$skierx if $key eq ",";
++$skierx if $key eq ".";
return if $key eq "x";
}
push @xloc, newLine($kWidth); # Generate a new line at the end
locate ++$y, 1;
print "$xloc[-1]\n";
#crash???
if ('T' eq substr $xloc[0], $skierx - 1, 1) {
print " CRASH!!! ";
return;
}
# place V
shift @xloc; # Remove the previous line
locate $y - $kLines + 2, $skierx;
print "V";
#score
locate $y - $kLines + 1, 1;
if ($y < $kPractise + $kLines) {
print "PRACTICE";
} else {
print ++$score;
}
# keep speeding up, reducing pause time
select (undef, undef, undef, $wait); #pauses here
$wait = .25 if $score eq 50;
$wait = .2 if $score eq 100;
$wait = .15 if $score eq 150;
$wait = .1 if $score eq 200;
}
}
sub newLine {
my ($width) = @_;
my $line = ' ' x $width;
substr $line, rand $width, 1, 'T' for 1 .. rand $kMaxTrees;
return $line;
}
Please read the Perl docs for anything you can't understand, or ask here if you really can't figure it out. But do work through the code line by line and understand what is going on.
Oh, and really don't put multiple statements on a line!
Perl is the programming world's equivalent of English
|