in reply to newbie learning perl
I've reworked your code somewhat. The most important change is to add strictures (use strict; use warnings; - see The strictures, according to Seuss), but I've also added the start of collision detection (which may have an off by 1 bug in it), allowed the number of display rows to be set and refactored the code somewhat (in part to show off some Perl stuff like join and arrays).
This code is not tested because I can't quickly find a working ANSI Terminal emulation for Windows 8.
#!/usr/bin/perl use strict; use warnings; use Term::ANSIScreen qw/:color :cursor :screen/; use Term::ReadKey; my $rows = 50; ReadMode('noecho'); cls; setscroll (1, $rows); locate 1, 1; my @screenRows; # Create the initial screen push @screenRows, newRow() for 1 .. $rows; print join "\n", @screenRows, ''; my $wait = 1; my $skierx = 40; while (1) { if (defined(my $key = ReadKey(-1))) { if ($key eq "j") { --$skierx; } elsif ($key eq "k") { ++$skierx; } elsif ($key eq "x") { exit; } } # Generate and show a new line shift @screenRows; push @screenRows, newRow(); print $screenRows[-1]; # Collision detection if (' ' ne substr $screenRows[$rows / 2], $skierx - 1, 1) { locate $rows, 1; print "Crash!\n"; exit; } # Show skier's updated position locate $rows / 2, $skierx; print "V"; # wait select(undef, undef, undef, $wait); #pauses here $wait -= 0.003; } sub newRow { my $col = int(rand(80)); return ' ' x $col . 'T' . (' ' x (78 - $col)); }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: newbie learning perl
by Anonymous Monk on Feb 19, 2015 at 18:04 UTC | |
by GrandFather (Saint) on Feb 19, 2015 at 20:21 UTC | |
by mkesling (Initiate) on Feb 20, 2015 at 19:03 UTC | |
by GrandFather (Saint) on Feb 20, 2015 at 22:44 UTC | |
by RonW (Parson) on Feb 20, 2015 at 20:58 UTC | |
by mkesling (Initiate) on Feb 20, 2015 at 20:30 UTC |