#!/usr/bin/perl -w
#	plays worm, the old BSD game.
#	should win if the term is an odd number of chars wide or high. An even
#	size terminal _could_ produce a winner.
#
#	Use, share, copy, change under the same terms as worm
#	mick@lowdrag.org (c)2002
use strict;
use Term::ReadKey;

my($width, $height) = GetTerminalSize();
my ($odd_wide, $odd_high) = 0;
if($width % 2)	{ $odd_wide = 1; }
if($height % 2)	{ $odd_high = 1; }

my $x = $width - 5;	#	account for window 
my $y = $height - 4;	#	decorations
if($odd_high)	{ $y++ }	
open(WORM, "| worm");
print WORM 'k' . 'h'x8 . 'j'x(int($y/2));

while(1)	{
	&count;
	&wiggle;
}

sub wiggle	{
	if($odd_high)	{
		print WORM 'j'x($y-1);
	}
	else	{
		my @ary = (1..(int($x/2)-2));
		my $fudge = $ary[rand(@ary)];
		my $i = '0';
		while($i < (int($x/2)))	{
			if($i == $fudge)	{
				unless($odd_wide)	{
					print WORM 'h';
				}
			}
			print WORM 'khjh';
			$i++
		}
		print WORM 'kh';
		print WORM 'j'x$y;
	}
}

sub count	{
	my $i = '0';
	while($i < ($y-1))	{
		if($i % 2)	{
			horizontal('h', ($x));
		}
		elsif($i == 0)	{
			horizontal('l', $x+1);
		}
		else	{
			horizontal('l', ($x));
		}
		$i++;
		&up;
	}
	if($odd_high)	{
		horizontal('h', $x+1);
	}
}

sub horizontal	{
	my ($dir, $len) = @_;
	my $i = '0';
	while($i < $len)	{
		$i++;
		print WORM $dir;
	}
}

sub up	{
	print WORM 'k';
}
