Skip to content

Instantly share code, notes, and snippets.

@cgsdev0
Created May 19, 2026 20:47
Show Gist options
  • Select an option

  • Save cgsdev0/82919e340311ef99794070643632213c to your computer and use it in GitHub Desktop.

Select an option

Save cgsdev0/82919e340311ef99794070643632213c to your computer and use it in GitHub Desktop.
conway's game of life
#!/usr/bin/env bash
tput civis
declare -a arr0
declare -a arr1
idx=0
declare -n cur=arr0
declare -n next=arr1
# DEAD='⬜'
# ALIVE='⬛'
DEAD=' '
ALIVE=''
mapfile -t arr0
height="${#cur[@]}"
width="${#cur[0]}"
for ((i=0; i<height; i++)); do
before=${cur[i]}
after=${before//#/$ALIVE}
cur[i]=${after//\./$DEAD}
done
next=("${cur[@]}")
function get {
local r=$1
local c=$2
c=$((c%width))
local row="${cur[r%height]}"
echo "${row:$c:1}"
}
render() {
printf "\e[%s;%sH" 1 1
printf "%s\n" "${next[@]}"
}
step() {
local r c i j
local self neighbor
local line
for ((r=0; r<height; ++r)); do
line=""
for ((c=0; c<width; ++c)); do
sum=0
for i in -1 0 1; do
for j in -1 0 1; do
[ $j -eq 0 ] && [ $i -eq 0 ] && continue
neighbor=${ get $((r + i)) $((c + j)); }
if [[ $neighbor == "$ALIVE" ]]; then
((sum++))
fi
done
done
self=${ get $r $c; }
if [[ $self == "$ALIVE" ]]; then
# we are live
if [[ sum -lt 2 ]]; then
line=$line$DEAD
elif [[ sum -gt 3 ]]; then
line=$line$DEAD
else
line="$line$ALIVE"
fi
elif [[ sum -eq 3 ]]; then
line="$line$ALIVE"
else
line="$line$DEAD"
fi
done
next[r]=$line
done
declare -gn next=arr${idx}
((idx=(idx+1)%2))
declare -gn cur=arr${idx}
}
clear
while :; do
render
step
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment