HOME - TEACHING

Code For Game of Life in Perl

#!/usr/bin/perl -s
use strict;
use Time::HiRes qw(usleep);

#author : maxime borry

#variables globales
my $nb_iterations = 100;
my $size = 38;
my $densite_initiale  = 0.33;
my $a = 1;
my @M = &generer();
my $ctr;


#############################
#execution du programme

while ( $ctr ++ < $nb_iterations) {
    system "clear";
    print "itération = $ctr\n";
    &afficher(@M);
    #screencap($ctr);
    @M = &regles_du_jeu(@M);
&usleep(200000);
}
system"convert -delay 25 -loop 0 img/cut*.jpg anim.gif";


###############################
#fonctions en dessous
         

sub screencap {
    my $ctr = shift(@_);
    while (length($ctr)<3){
        $ctr = "0".$ctr;
    }
    my $output = "img/cap$ctr.jpg";
    system "import -window root $output";
    system "convert $output -crop 480X500+0+30 img/cut$ctr.jpg";
}


sub generer {
    my @M;
    foreach my $line (0 .. $size-1){
        foreach my $col (0 .. $size-1){
            if (rand(1) < $densite_initiale) {
                $M[$line][$col] = 1;
            }
            else {
                $M[$line][$col] = 0;
            }
        }
    }
    return @M;
}

sub afficher {
    my @M = @_;
    foreach my $line (0 .. $size-1){
        foreach my $col (0 .. $size-1){
            if ($M[$line][$col] == 0) {
                print " " ;
            }
            else {
                print "#" ;
            }
        }
    print "\n";
    }

}

sub regles_du_jeu {
    my @M = @_;
    my @N;
    foreach my $line (0 .. $size-1){
        foreach my $col (0 .. $size-1){
            my $voisins = 0;
            $voisins = ($M[$line][$col-1] + $M[$line-1][$col-1] + $M[$line-1][$col] + $M[$line-1][$col+1] + $M[$line][$col+1] + $M[$line+1][$col+1] + $M[$line+1][$col] + $M[$line+1][$col-1]) ; 
            
            if ($voisins == 2) {
                $N[$line][$col] = $M[$line][$col];
            }
            elsif ($voisins == 3) {
                $N[$line][$col] =1;
            }
            else {
                $N[$line][$col] = 0;
            }
            
        
        }
    }
    return @N;
}