main
life
1#!/bin/sh
2# conways game of life
3# usage:
4# life [generations]
5
6# dependencies:
7# shell
8# awk
9# 'rs' command from bs
10
11set -eu
12
13rows=10
14cols=10
15gens=${1:-20}
16delay=${DELAY:-0.15}
17state=$(mktemp)
18
19cleanup() {
20 rm -f "$state" "$state.next"
21}
22trap cleanup EXIT INT TERM
23
24awk -v n="$((rows * cols))" '
25BEGIN {
26 srand()
27 for (i = 1; i <= n; i++)
28 print rand() < 0.35 ? 1 : 0
29}
30' > "$state"
31
32gen=0
33while [ "$gen" -lt "$gens" ]; do
34 printf '\033[H\033[J'
35 awk '{ print $1 ? "@" : "." }' "$state" | rs "$rows" "$cols"
36 printf '\ngen %s\n' "$gen"
37
38 awk -v rows="$rows" -v cols="$cols" '
39 {
40 cell[NR] = $1
41 }
42 END {
43 for (r = 1; r <= rows; r++) {
44 for (c = 1; c <= cols; c++) {
45 idx = (r - 1) * cols + c
46 n = 0
47 for (dr = -1; dr <= 1; dr++) {
48 for (dc = -1; dc <= 1; dc++) {
49 if (dr == 0 && dc == 0)
50 continue
51 rr = r + dr
52 cc = c + dc
53 if (rr < 1 || rr > rows || cc < 1 || cc > cols)
54 continue
55 n += cell[(rr - 1) * cols + cc] ? 1 : 0
56 }
57 }
58 alive = cell[idx] ? 1 : 0
59 if (alive)
60 nxt[idx] = (n == 2 || n == 3) ? 1 : 0
61 else
62 nxt[idx] = (n == 3) ? 1 : 0
63 }
64 }
65 for (i = 1; i <= rows * cols; i++)
66 print nxt[i]
67 }
68 ' "$state" > "$state.next"
69
70 mv "$state.next" "$state"
71 gen=$((gen + 1))
72 sleep "$delay"
73done