#!/usr/bin/perl -w

# fall.pl, copyright (c) 2000 by Jason McIntosh <jmac@jmac.org> 
# This is the non-obfuscated version of the the far more compact
# (and contest-enterable) version of fall.pl

use strict;                     # Why bother? :) Oh well

my ($gap_size) = @ARGV;         # Size of gap
$gap_size ||= 10;
my $playfield_size = 40;        # Size of playfield

my $pc = '.';                   # The player's avatar :)
my $difference = ($playfield_size - $gap_size);
my $offset = ($difference / 2);

my $score = 0;
my $lives = 5;

my $pc_dir = 1;                 # direction of pc's slide (1 == right)
my $pc_pos = $offset;           # position of pc

my @left_chances;
foreach (0..$difference) {
    $left_chances[$_] = (100/$difference)*$_;
}
    
while ($lives) {
    # Print a row
    $| = 1;
    my @row = ();
    my @gap = (' ')x$gap_size;
    $gap[$pc_pos - ($offset)] = $pc;
    push @row,'*'x($offset+1);
    push @row, @gap;
    push @row,'*'x($difference-$offset+1);
    push @row,' ',$lives;
    print join('',(@row));
    # Determine shift direction
    # Heh, definitely needs a trinary op here
    if (rand(100) <= $left_chances[$offset]) {
        $offset--;
    } else {
        $offset++;
    }
    $score++;
    # Detect input
    my $rout = my $rin = '';
    vec($rin,fileno(STDIN), 1) = 1;
    my @stuff;
    if (select ($rout=$rin, undef, undef, .1)) {
        until (sysread(STDIN, my $b, 1)) {}
        $pc_dir = -$pc_dir;
    } else {
        print "\n";
    }
    # move pc
    $pc_pos += $pc_dir;
    # detect collision
    if ($pc_pos < $offset) {
        $pc_pos = $offset;
        $lives--;
        $pc_dir = -$pc_dir;
    } elsif ($pc_pos >= ($offset + $gap_size)) {
        $pc_pos = $offset+$gap_size-1;
        $lives--;
        $pc_dir = -$pc_dir;
    }
    
}

print "$score\n";
