package fusionworm;
#
# fusionworm.pm - a worm engine, adapted for termfusion.pm
# (based on worm.pm - a worm engine)
#
# author: Max-Gerd Retzlaff <m.retzlaff@gmx.net>
#                           <mgr@hannover.ccc.de>
#
# date:    Fri Aug  2 15:18:35 CEST 2002
# version: 0.4
#
# GnuPG-Information:
#  Fingerprint: 49CD 21F2 41AC 72C5 D0D1  27DC C2B2 48AE 8123 9F12
#  pub  1024D/81239F12 2002-03-12 Max-Gerd Retzlaff <m.retzlaff@gmx.net>
#  uid                            Max-Gerd Retzlaff <mgr@hannover.ccc.de>
#  sub  4096g/63E36E39 2002-03-12
#
# This application is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version. 
#
# This application is distributed in the hope that it will be useful, 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111 USA.  

use termfusion;
use Exporter;
@ISA = ('Exporter');
@EXPORT = ('init_worm','move_worm','draw_worm', 'creep_worm', 'grow_worm',
	   'set_worm_delay');

my @wormdesc = undef;
my @worm = ();
my $worm_delay = 0.07;

sub set_worm_delay {
    $worm_delay = $_[0];
}

sub init_worm {
    # example worm: init_worm( "\@.OOOOOOooooooo...... " );
    my $string = $_[0];
    
    @wormdesc=();
    foreach my $cell ( 0..length( $string )-1 ) {
	$wormdesc[$cell] = substr( $string, $cell, 1 );
    }
    @worm=();
}

sub move_worm {
    my ( $x, $y ) = @_;
    unshift( @worm, [ $x, $y ] );
    if ( scalar( @worm ) > scalar( @wormdesc ) ) {
	pop( @worm );
    }
}

sub draw_worm {
    for( my $cell = 0; $cell < scalar @worm; $cell++ ) {
	printxy( ${ $worm[$cell] }[0], ${ $worm[$cell] }[1], $wormdesc[$cell] );
    }
}

sub grow_worm{
    my $newcellcount = defined( $_[0] ) ? $_[0] : 4 ;
    my $newcell      = defined( $_[1] ) ? $_[1] : $wormdesc[ $#wormdesc - 1 ];
    my $cell_delim   = defined( $_[2] ) ? $_[2] : $wormdesc[ $#wormdesc - 1 ];
    my $worm_end     = defined( $_[3] ) ? $_[3] : $wormdesc[ $#wormdesc ];

    $wormdesc[ $#wormdesc ] = $cell_delim;
    foreach (1..$newcellcount) {
	push( @wormdesc, $newcell );
    }
    push( @wormdesc, $worm_end );
}

sub creep_worm {
    my ( $x, $y ) = @_;
    move_worm( $x, $y );
    draw_worm();

    select(STDOUT);$|=1;
    select( undef, undef, undef, $worm_delay );
}

return 1;
