#!/usr/bin/perl use strict; use warnings 'all'; # create the Map my $map = new Map; # set Map size and start position by user $map->matrix()->position(); # MainLoop MAIN: while (1) { # clear screen system($^O =~ /win/i ? "cls" : "clear"); # draw the Map $map->draw(); # get user input print " 1/w:forward\t2/s:back\t3/a:left\t4/d:right 5/q:quit IN: "; chomp(my$in = ); $in =~ s/\s*//; # evaluate user input if ($in =~ /^[1w]$/i) { # move forwards $map->move(0, -1); } elsif ($in =~ /^[2s]$/i) { # move backwards $map->move(0, 1); } elsif ($in =~ /^[3a]$/i) { # move leftwards $map->move(-1, 0); } elsif ($in =~ /^[4d]$/i) { # move rightwards $map->move(1, 0); } elsif ($in =~ /^[5q]$/i) { # stop MainLoop last MAIN; } else { print " Wrong input: $in "; ; } } # MainLoop # exit if the MainLoop is stopped exit(0); package Map; use strict; use warnings 'all'; # # create a new object # sub new { my $class = shift; my $obj = { matrix => ["*"], # 1d matrix to save the Map data pos => [1,1], # array with x and y position in the Map(count from 1) width => 1, # width of the matrix(count from 1) height => 1, # height of the matrix(count from 1) }; bless $obj, $class; return $obj; } # new # # create the matrix by given width and height # sub dat { my $self = shift; my($width, $height) = @_; $self->{width} = $width; $self->{height} = $height; $self->{matrix} = [split("","."x($width*$height))]; return $self; } # dat # # set the startposition by given x and y coordinate # sub pos { my $self = shift; my($x, $y) = @_; # we have a 1d matrix, so the index must be: x+width*y $self->{matrix}->[$self->{pos}->[0]-1+$self->{width}*($self->{pos}->[1]-1)] = "."; $self->{pos} = [$x, $y]; $self->{matrix}->[$x -1+$self->{width}*($y -1)] = "*"; return $self; } # pos # # set the matrix by user # sub matrix { my $self = shift; print "Rows: "; chomp(my$r = ); print "Columns: "; chomp(my$c = ); return $self->dat($c, $r); } # matrix # # set the startposition by user # sub position { my $self = shift; print "Startrow: "; chomp(my$r = ); print "Startcolumn: "; chomp(my$c = ); return $self->pos($c, $r); } # position # # change position with amount # sub move { my $self = shift; my($ax, $ay) = @_; # compute new position my $nx = $self->{pos}->[0]+$ax; my $ny = $self->{pos}->[1]+$ay; # if we are out of the Map, go top or respectively bottom $nx = $self->{width} if $nx < 1; $ny = $self->{height} if $ny < 1; $nx = 1 if $nx > $self->{width} ; $ny = 1 if $ny > $self->{height}; # set the new pos return $self->pos($nx, $ny); } # move # # draw the matrix on screen # sub draw { my $self = shift; for my$y (1..$self->{height}) { for my$x (1..$self->{width}) { print $self->{matrix}->[$x-1+$self->{width}*($y-1)] ." "; } print " "; } return $self; } # draw __END__