]> Creatis software - CreaPhase.git/blob - octave_packages/miscellaneous-1.1.0/gameoflife.m
Add a useful package (from Source forge) for octave
[CreaPhase.git] / octave_packages / miscellaneous-1.1.0 / gameoflife.m
1 ## Copyright (C) 2010 VZLU Prague, a.s.
2 ##
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
6 ## version.
7 ##
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
11 ## details.
12 ##
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
15
16 ## -*- texinfo -*-
17 ## @deftypefn{Function File} {B =} gameoflife (A, ngen, delay)
18 ## Runs the Conways' game of life from a given initial state for a given
19 ## number of generations and visualizes the process.
20 ## If ngen is infinity, the process is run as long as A changes.
21 ## Delay sets the pause between two frames. If zero, visualization is not done.
22 ## @end deftypefn
23
24 function B = gameoflife (A, ngen, delay = 0.2)
25   B = A != 0;
26   igen = 0;
27   CSI = char ([27, 91]);
28
29   oldpso = page_screen_output (delay != 0);
30   unwind_protect
31
32     if (delay > 0)
33       puts (["\n", CSI, "s"]);
34       printf ("generation 0\n");
35       colorboard (! B);
36       pause (delay);
37     endif
38
39     while (igen < ngen)
40       C = conv2 (B, ones (3), "same") - B;
41       B1 = C == 3 | (B & C == 2);
42       igen++;
43       if (isinf (ngen) && all ((B1 == B)(:)))
44         break;
45       endif
46       B = B1;
47       if (delay > 0)
48         puts (["\n", CSI, "u"]);
49         printf ("generation %d\n", igen);
50         colorboard (! B);
51         pause (delay);
52       endif
53     endwhile
54
55   unwind_protect_cleanup
56     page_screen_output (oldpso);
57   end_unwind_protect
58
59 endfunction