Last active
May 8, 2024 06:58
-
-
Save kareiva/4ab02fbe03d37ef20636856078af6525 to your computer and use it in GitHub Desktop.
Primitive implementation of Conway's Game of Life in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Problematic life by [email protected] | |
# Studying of bash performance | |
# v0.2.0 | |
term_width=$(($(tput cols) )) | |
term_height=$(($(tput lines) * 2 - 2)) | |
full_square='█' | |
upper_square='▀' | |
lower_square='▄' | |
empty_square='░' | |
game_seed=10 | |
generation='0.01' | |
log_file=debug.log | |
debug_call() { | |
ts=$(date "+%s %N") | |
echo "$ts $@" >> $log_file 2> /dev/null | |
eval $@ | |
} | |
declare -A matrix | |
declare -A matrix_next | |
for ((i=0; i < term_height; i++)) do | |
for ((j=0; j < term_width; j++)) do | |
if [ $(($RANDOM%$game_seed)) -gt 0 ]; | |
then matrix[$i,$j]=0 | |
else matrix[$i,$j]=1 | |
fi | |
done | |
done | |
# main loop | |
clear | |
while true; do | |
for ((i=0; i < term_height; i+=2)) do | |
line=$(($i/2)) | |
row='' | |
for ((j=0; j < term_width; j++)) do | |
if [ ${matrix[$i,$j]} -eq 1 ] && [ ${matrix[$(($i+1)),$j]} -eq 1 ] ; | |
then row+="${full_square}" | |
elif [ ${matrix[$i,$j]} -eq 1 ] && [ ${matrix[$(($i+1)),$j]} -eq 0 ] ; | |
then row+="${upper_square}" | |
elif [ ${matrix[$i,$j]} -eq 0 ] && [ ${matrix[$(($i+1)),$j]} -eq 1 ] ; | |
then row+="${lower_square}" | |
else row+="${empty_square}" | |
fi | |
done | |
echo -en "\033[${line};0f$row" | |
done | |
# calculate conway's loop into $matrix_next | |
for ((i=0; i < term_height; i++)) do | |
for ((j=0; j < term_width; j++)) do | |
sum_neighbours=$((" | |
${matrix[$(($i-1)),$(($j-1))]:-0} + ${matrix[$i,$(($j-1))]:-0} + | |
${matrix[$(($i+1)),$((j-1))]:-0} + ${matrix[$(($i-1)),$j]:-0} + | |
${matrix[$(($i+1)),$j]:-0} + ${matrix[$(($i-1)),$(($j+1))]:-0} + | |
${matrix[$i,$(($j+1))]:-0} + ${matrix[$(($i+1)),$(($j+1))]:-0} ")) | |
if [ ${matrix[$i,$j]} -eq 1 ]; | |
then | |
if [ $sum_neighbours -lt 2 ] || [ $sum_neighbours -gt 3 ]; | |
then matrix_next[$i,$j]=0 | |
else matrix_next[$i,$j]=1 | |
fi | |
elif [ ${matrix[$i,$j]} -eq 0 ]; | |
then | |
if [ $sum_neighbours -eq 3 ]; | |
then matrix_next[$i,$j]=1 | |
else matrix_next[$i,$j]=0 | |
fi | |
fi | |
done | |
done | |
# copy next matrix into main | |
for ((i=0; i < term_height; i++)) do | |
for ((j=0; j < term_width; j++)) do | |
matrix[$i,$j]=${matrix_next[$i,$j]} | |
done | |
done | |
sleep $generation | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment