Friday, January 29, 2016

A Short Perl6 ASCII Rotator

This script rotates a simple chunk of ASCII art based on user input (90, 180, or 270 degrees). It's not very elegant, and there's a minor and annoying bug in it, but I'm done for the day, so.  Here's a test run:

+OO
OOO
OOO

% 90


OOO
OOO
+OO


% 180


OO+
OOO
OOO


% 270


OOO
OOO
OO+


% 180


+OO
OOO
OOO


%


And here's the code.


my Str @test = ("+OO"
               ,"OOO"
               ,"OOO");


my $r = 0;

loop
{
    run( 'cls' );
    say @test.join( "\n" );
    my $in = prompt "\n% ";

    @test = rotate( 90,  @test )  if $in ~~ /90/;
    @test = rotate( 180, @test ) if $in ~~ /180/;
    @test = rotate( 270, @test ) if $in ~~ /270/;
}          

sub rotate( $degrees, Str @pixobject )
{
   return @pixobject if $degrees % 360 == 0;
  
   my Str @a = @pixobject;
  
   @a = rotate90( @a );
   @a = rotate90( @a ) if $degrees > 90;
   @a = rotate90( @a ) if $degrees > 180;

   return @a;
}  

sub rotate90( Str @pixobject )
{
   my Str @new = ();
   for @pixobject -> $line
   {
      my Str @row = $line.split('');
      my $len = @row.elems;
      for (0..$len) -> $i
      {
         @new[$len-$i] = '' unless @new[$len-$i];
         @new[$len-$i] ~= @row[$i] if @row[$i];
      }
   }
   return @new;
}