summaryrefslogtreecommitdiff
path: root/sys/src/games/life.c
blob: 000134e8c5f6df23c0952ca785f077297a6b3830 (plain)
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/*
 * life - john conways's game of life (and variations),
 * sci. am. 223, october 1970, pp. 120—123, or
 * http://en.wikipedia.org/wiki/Conway's_Game_of_Life
 */
#include <u.h>
#include <libc.h>
#include <bio.h>
#include <draw.h>
#include <event.h>

enum {
	NLIFE	= 256,		/* life array size */
	PX	= 4,		/* cell spacing */
	BX	= PX - 1,	/* box size */
	NADJUST	= NLIFE * NLIFE,
};

/*
 * life[i][j] stores L+2*N, where L is 0 if the cell is dead and 1
 * if alive, and N is the number of the cell's 8-connected neighbours
 * which live.
 * row[i] indicates how many cells are alive in life[i][*].
 * col[j] indicates how many cells are alive in life[*][j].
 * Adjust contains pointers to cells that need to have their neighbour
 * counts adjusted in the second pass of the generation procedure.
 */
char	life[NLIFE][NLIFE];
int	row[NLIFE];
int	col[NLIFE];
char	action[18];		/* index by cell contents to find action */
char	*adjust[NADJUST];

Point	cen;
Image	*box;
int	i0, i1, j0, j1;
int	needresize;

void	birth(int, int);
void	centerlife(void);
void	death(int, int);
int	generate(void);
int	interest(int [NLIFE], int);
void	main(int, char *[]);
int	min(int, int);
void	readlife(char *);
void	redraw(void);
void	setrules(char *);
void	window(void);

static void	reshape(void);

static void
setbox(int i, int j)
{
	Point loc;

	loc = Pt(cen.x + j*PX, cen.y + i*PX);
	draw(screen, Rpt(loc, addpt(loc, Pt(BX, BX))), box, nil, ZP);
}

static void
clrbox(int i, int j)
{
	Point loc;

	loc = Pt(cen.x + j*PX, cen.y + i*PX);
	draw(screen, Rpt(loc, addpt(loc, Pt(BX, BX))), display->white, nil, ZP);
}

void
setrules(char *r)
{
	char *a;

	for (a = action; a != &action[nelem(action)]; *a++ = *r++)
		;
}

static void
g9err(Display *, char *err)
{
	static int entered = 0;

	fprint(2, "%s: %s (%r)\n", argv0, err);
	exits(err);
}

void
usage(void)
{
	fprint(2, "Usage: %s [-3o] [-r rules] file\n", argv0);
	exits("usage");
}

void
idle(void)
{
	int c;

	while (ecanmouse())
		emouse();			/* throw away mouse events */
	while (ecankbd())
		if ((c = ekbd()) == 'q' || c == 0177) /* watch keyboard ones */
			exits(nil);
	if (needresize)
		reshape();
}

void
main(int argc, char *argv[])
{
	int delay = 1000;

	setrules(".d.d..b..d.d.d.d.d");			/* regular rules */
	ARGBEGIN {
	case '3':
		setrules(".d.d.db.b..d.d.d.d");
		break;					/* 34-life */
	case 'o':
		setrules(".d.d.db.b.b..d.d.d");
		break;					/* lineosc? */
	case 'r':					/* rules from cmdline */
		setrules(EARGF(usage()));
		break;
	default:
		usage();
	} ARGEND
	if (argc != 1)
		usage();

	initdraw(g9err, 0, argv0);
	einit(Emouse|Ekeyboard);	/* implies rawon() */

	cen = divpt(subpt(addpt(screen->r.min, screen->r.max),
		Pt(NLIFE * PX, NLIFE * PX)), 2);
	box  = allocimage(display, Rect(0, 0, BX, BX), RGB24, 1, DBlack);
	assert(box != nil);

	redraw();
	readlife(argv[0]);
	do {
		flushimage(display, 1);
		idle();
		sleep(delay);
		idle();
	} while (generate());
	exits(nil);
}

/*
 * We can only have interest in a given row (or column) if there
 * is something alive in it or in the neighbouring rows (or columns.)
 */
int
interest(int rc[NLIFE], int i)
{
	return(rc[i-1] != 0 || rc[i] != 0 || rc[i+1] != 0);
}

/*
 * A life generation proceeds in two passes.  The first pass identifies
 * cells that have births or deaths.  The `alive bit' is updated, as are
 * the screen and the row/col count deltas.  Also, a record is made
 * of the cell's address.  In the second pass, the neighbours of all changed
 * cells get their neighbour counts updated, and the row/col deltas get
 * merged into the row/col count arrays.
 *
 * The border cells (i==0 || i==NLIFE-1 || j==0 || j==NLIFE-1) are not
 * processed, purely for speed reasons.  With a little effort, a wrap-around
 * universe could be implemented.
 *
 * Generate returns 0 if there was no change from the last generation,
 * and 1 if there were changes.
 */
#define	neighbour(di, dj, op) lp[(di)*NLIFE+(dj)] op= 2
#define	neighbours(op)\
	neighbour(-1, -1, op);\
	neighbour(-1,  0, op);\
	neighbour(-1,  1, op);\
	neighbour( 0, -1, op);\
	neighbour( 0,  1, op);\
	neighbour( 1, -1, op);\
	neighbour( 1,  0, op);\
	neighbour( 1,  1, op)

int
generate(void)
{
	char *lp;
	char **p, **addp, **delp;
	int i, j, j0 = NLIFE, j1 = -1;
	int drow[NLIFE], dcol[NLIFE];

	for (j = 1; j != NLIFE - 1; j++) {
		drow[j] = dcol[j] = 0;
		if (interest(col, j)) {
			if (j < j0)
				j0 = j;
			if (j1 < j)
				j1 = j;
		}
	}
	addp = adjust;
	delp = &adjust[NADJUST];
	for (i = 1; i != NLIFE - 1; i++)
		if (interest(row, i)) {
			for (j = j0, lp = &life[i][j0]; j <= j1; j++, lp++)
				switch (action[*lp]) {
				case 'b':
					++*lp;
					++drow[i];
					++dcol[j];
					setbox(i, j);
					*addp++ = lp;
					break;
				case 'd':
					--*lp;
					--drow[i];
					--dcol[j];
					clrbox(i, j);
					*--delp = lp;
					break;
				}
		}
	if (addp == adjust && delp == &adjust[NADJUST])
		return 0;
	if (delp < addp)
		sysfatal("Out of space (delp < addp)");
	p = adjust;
	while (p != addp) {
		lp = *p++;
		neighbours(+);
	}
	p = delp;
	while (p != &adjust[NADJUST]) {
		lp = *p++;
		neighbours(-);
	}
	for (i = 1; i != NLIFE - 1; i++) {
		row[i] += drow[i];
		col[i] += dcol[i];
	}
	if (row[1] || row[NLIFE-2] || col[1] || col[NLIFE-2])
		centerlife();
	return 1;
}

/*
 * Record a birth at (i,j).
 */
void
birth(int i, int j)
{
	char *lp;

	if (i < 1 || NLIFE - 1 <= i || j < 1 || NLIFE - 1 <= j ||
	    life[i][j] & 1)
		return;
	lp = &life[i][j];
	++*lp;
	++row[i];
	++col[j];
	neighbours(+);
	setbox(i, j);
}

/*
 * Record a death at (i,j)
 */
void
death(int i, int j)
{
	char *lp;

	if (i < 1 || NLIFE - 1 <= i || j < 1 || NLIFE - 1 <= j ||
	    !(life[i][j] & 1))
		return;
	lp = &life[i][j];
	--*lp;
	--row[i];
	--col[j];
	neighbours(-);
	clrbox(i, j);
}

void
readlife(char *filename)
{
	int c, i, j;
	char name[256];
	Biobuf *bp;

	if ((bp = Bopen(filename, OREAD)) == nil) {
		snprint(name, sizeof name, "/sys/games/lib/life/%s", filename);
		if ((bp = Bopen(name, OREAD)) == nil)
			sysfatal("can't read %s: %r", name);
	}
	draw(screen, screen->r, display->white, nil, ZP);
	for (i = 0; i != NLIFE; i++) {
		row[i] = col[i] = 0;
		for (j = 0; j != NLIFE; j++)
			life[i][j] = 0;
	}
	c = 0;
	for (i = 1; i != NLIFE - 1 && c >= 0; i++) {
		j = 1;
		while ((c = Bgetc(bp)) >= 0 && c != '\n')
			if (j != NLIFE - 1)
				switch (c) {
				case '.':
					j++;
					break;
				case 'x':
					birth(i, j);
					j++;
					break;
				}
	}
	Bterm(bp);
	centerlife();
}

int
min(int a, int b)
{
	return(a < b ? a : b);
}

void
centerlife(void)
{
	int i, j, di, dj, iinc, jinc, t;

	window();
	di = NLIFE / 2 - (i0 + i1) / 2;
	if (i0 + di < 1)
		di = 1 - i0;
	else if (i1 + di >= NLIFE - 1)
		di = NLIFE - 2 - i1;
	dj = NLIFE / 2 - (j0 + j1) / 2;
	if (j0 + dj < 1)
		dj = 1 - j0;
	else if (j1 + dj >= NLIFE - 1)
		dj = NLIFE - 2 - j1;
	if (di != 0 || dj != 0) {
		if (di > 0) {
			iinc = -1;
			t = i0;
			i0 = i1;
			i1 = t;
		} else
			iinc = 1;
		if (dj > 0) {
			jinc = -1;
			t = j0;
			j0 = j1;
			j1 = t;
		} else
			jinc = 1;
		for (i = i0; i * iinc <= i1 * iinc; i += iinc)
			for (j = j0; j * jinc <= j1 * jinc; j += jinc)
				if (life[i][j] & 1) {
					birth(i + di, j + dj);
					death(i, j);
				}
	}
}

void
redraw(void)
{
	int i, j;

	window();
	draw(screen, screen->r, display->white, nil, ZP);
	for (i = i0; i <= i1; i++)
		for (j = j0; j <= j1; j++)
			if (life[i][j] & 1)
				setbox(i, j);
}

void
window(void)
{
	for (i0 = 1; i0 != NLIFE - 2 && row[i0] == 0; i0++)
		;
	for (i1 = NLIFE - 2; i1 != i0 && row[i1] == 0; --i1)
		;
	for (j0 = 1; j0 != NLIFE - 2 && col[j0] == 0; j0++)
		;
	for (j1 = NLIFE - 2; j1 != j0 && col[j1] == 0; --j1)
		;
}

static void
reshape(void)
{
//	int dy12;

//	if (needresize) {
//		sqwid = Dx(screen->r) / (1 + bdp->cols + 1);
//		dy12  = Dy(screen->r) / (1 + bdp->rows + 1 + 2);
//		if (sqwid > dy12)
//			sqwid = dy12;
//		recompute(bdp, sqwid);
//	}
	sleep(1000);
	needresize = 0;
	cen = divpt(subpt(addpt(screen->r.min, screen->r.max),
		Pt(NLIFE * PX, NLIFE * PX)), 2);
	redraw();
	flushimage(display, 1);
}

/* called from graphics library */
void
eresized(int callgetwin)
{
	needresize = callgetwin + 1;

	/* new window? */
	/* was using Refmesg */
	if (needresize > 1 && getwindow(display, Refnone) < 0)
		sysfatal("can't reattach to window: %r");

	/* destroyed window? */
	if (Dx(screen->r) == 0 || Dy(screen->r) == 0)
		exits("window gone");

	reshape();
}