File: life.sl

package info (click to toggle)
slang2 2.3.3-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 11,488 kB
  • sloc: ansic: 101,756; sh: 3,435; makefile: 1,046; pascal: 440
file content (122 lines) | stat: -rw-r--r-- 2,200 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
% This example provides an implementation of Conway's famous game of life.
% It uses the SMG module from the modules directory.  Make sure you
% build it first.

require ("slsmg");
require ("rand");

private define urand (m, n)
{
   variable a = rand_uniform (m*n);
   reshape (a, [m, n]);
   return a;
}

% The algorithm for the game begins here.
private define make_left (n)
{
   variable a;

   a = Int_Type [n];
   a[0] = n-1;
   a[[1:]] = [0:n-2];

   return a;
}

private define make_right(n)
{
   variable a;

   a = Int_Type [n];
   a[[0:n-2]] = [1:n-1];
   a[-1] = 0;

   return a;
}

private define life_init (nr, nc)
{
   variable a;
   variable up, down, left, right;
   variable i;
   variable num_neighbors;

   a = typecast (5.0 * urand (nr, nc), Char_Type);
   a[where (a != 1)] = 0;

   up = make_left (nr);
   down = make_right (nr);
   left = make_left (nc);
   right = make_right (nc);

   return (a,up,down,left,right);
}

private define life_new_generation (a, up, down, left, right)
{
   variable b;
   variable middle = [:];
   variable i;

   % Make sure array contains only 0 and 1
   a[where(a)] = 1;

   b = (a[up,left] + a[up, middle] + a[up, right]
	+ a[middle,left] + a[middle, right]
	+ a[down, left] + a[down, middle] + a[down, right]);
   b = typecast (b, Char_Type);

   i = where ((b < 2) or (b > 3) or ((b == 2) and (a == 0)));
   b[i] = 0;
   return b;
}

define life_print (a, old_a)
{
   variable dims, i, j;
   (dims,,) = array_info (a);

   a = @a;
   a[where (a)] = 1;
   a[where (a and (old_a == 0))] = 2;

   slsmg_set_color (0);
   slsmg_cls ();

   _for (0, dims[0]-1, 1)
     {
	i = ();
	foreach (where (a[i,*]))
	  {
	     j = ();
	     slsmg_gotorc(i,j);
	     slsmg_set_color (a[i,j]);
	     slsmg_write_string ("O");
	  }
     }
   slsmg_set_color (0);
   slsmg_refresh ();
   sleep (1);
}

define life (nr, nc)
{
   variable a, left, right, up, down, new_a;

   (new_a, up, down, left, right) = life_init (nr, nc);

   a = new_a;
   do
     {
	life_print (new_a, a);
	a = new_a;
	new_a = life_new_generation (a, up, down, left, right);
     }
   while (length (where (new_a)));
}

slsmg_init_smg ();

life (SLsmg_Screen_Rows, SLsmg_Screen_Cols);