Skip to content

Instantly share code, notes, and snippets.

@ytaki0801
Last active February 16, 2023 19:22
Show Gist options
  • Save ytaki0801/3dfb78733eded1816b49bc53ed878ed8 to your computer and use it in GitHub Desktop.
Save ytaki0801/3dfb78733eded1816b49bc53ed878ed8 to your computer and use it in GitHub Desktop.
Conway's Game of Life in POSIX Shell
#!/bin/sh
xs=80 ys=24
ORIGIN=$(clear) LF='
'
if [ ! ${RANDOM} ]; then
set -- $(head -c $((xs * ys)) /dev/random | od -An -vtu1)
fi
j=0; while [ $j != $ys ]; do
i=0; while [ $i != $xs ]; do
if [ ${RANDOM} ]; then
r=${RANDOM}
else
r=$1
shift
fi
export cx${i}y${j}=$((r%2))
i=$((i+1))
done
j=$((j+1))
done
clear
while true; do
buf=$ORIGIN
j=0; while [ $j != $ys ]; do
i=0; while [ $i != $xs ]; do
case $((cx${i}y${j})) in
1) buf="$buf*" ;;
*) buf="$buf " ;;
esac
i=$((i+1))
done
buf="$buf$LF"
j=$((j+1))
done
echo "${buf%$LF}"
j=0; while [ $j != $ys ]; do
i=0; while [ $i != $xs ]; do
t=0
for l in -1 0 1; do
for k in -1 0 1; do
tx=$(((i+k+xs)%xs)) ty=$(((j+l+ys)%ys))
t=$((t+$((cx${tx}y${ty}))))
done
done; t=$((t-cx${i}y${j}))
case $((cx${i}y${j})) in
1) case $t in 2|3) export cnx${i}y${j}=1 ;;
*) export cnx${i}y${j}=0 ;;
esac ;;
*) case $t in 3) export cnx${i}y${j}=1 ;;
*) export cnx${i}y${j}=0 ;;
esac ;;
esac
i=$((i+1))
done
j=$((j+1))
done
j=0; while [ $j != $ys ]; do
i=0; while [ $i != $xs ]; do
export cx${i}y${j}=$((cnx${i}y${j}))
i=$((i+1))
done
j=$((j+1))
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment