#!/usr/bin/perl -w # -*- cperl -*- =head1 NAME perlLife.pl - Conway's Game of Life =head1 SYNOPSIS Run on console. Copyright (C) YAMAMIYA Takasi =head1 REFERENCE http://perlmonks.thepen.com/83813.html http://archive.develooper.com/perl-ai@perl.org/msg00646.html =cut use strict; while ("forever") { my $map = LifeMap->new(20, 20); $map->random(); foreach (1 .. 50) { $map->step(); $map->show(); select (undef, undef, undef, 0.2); } } package LifeMap; use constant CLEAR => "\33c"; sub new { my $pkg = shift; my $width = shift; my $height = shift; bless { _width => $width, _height => $height, _map => [], }; } sub random { my $self = shift; foreach my $y (0 .. $self->{_height} - 1) { foreach my $x (0 .. $self->{_width} - 1) { $self->{_map}->[$x][$y] = rand(1) < 0.5 ? 0 : 1; } } } sub show { my $self = shift; print CLEAR; foreach my $y (0 .. $self->{_height} - 1) { foreach my $x (0 .. $self->{_width} - 1) { print $self->{_map}->[$x][$y] ? "O " : " "; } print "\n"; } } sub step { my $self = shift; my $newMap = []; foreach my $y (0 .. $self->{_height} - 1) { foreach my $x (0 .. $self->{_width} - 1) { $newMap->[$x][$y] = $self->_nextWhen($self->{_map}->[$x][$y], $self->_numAt($x, $y)); } } $self->{_map} = $newMap; } sub _numAt { my $self = shift; my $x = shift; my $y = shift; my $sum = 0; foreach my $n ( [$x - 1, $y - 1], [$x - 1, $y ], [$x - 1, $y + 1], [$x , $y - 1], [$x , $y + 1], [$x + 1, $y - 1], [$x + 1, $y ], [$x + 1, $y + 1], ) { my ($_x, $_y) = @$n; if (0 <= $_x and $_y < $self->{_width} and 0 <= $_x and $_y < $self->{_height} and $self->{_map}->[$_x][$_y]) { $sum++; } } return $sum; } sub _nextWhen { my $self = shift; my $cell = shift; my $num = shift; if ($cell) { return (0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0)[$num]; } else { return (0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0)[$num]; } }