Terrifying code revisited

Remember this ?
I wrote that just for fun, but I thought "Why not try to make something useful out of it ?"

Well, it happend. :slight_smile:

Is it useful enough to replace other OO languages ? Hell no !!

But it makes managing a "herd of cooperating scripts" much easier and using it ends up with cleaner and much more readable code, and that is a good thing :slight_smile:

I wrote a kind of "lib" in bash (<100 LOC) that manages the subprocesses and extends bash with only two commands: 'New' and '@'

'New' creates a new instance of a class
'@' sends a message to an instance

Usage:
New instancename classname
@ target_instance "bashcommand"

It works pretty good and I already wrote some scripts to test.
I've cobbled a simple demo together to show how it is used.

Here are the demo "classfiles" that together form a working app to play dice.
Note, however, that it will only work when using my "lib"

Ofcourse the example below is ridiculous and inefficient, but this code is only to demonstrate the use of these commands.

  1. main
# config
declare -i -r nr_of_dice=3

#init
for (( i=0 ; i < nr_of_dice ; ++i ))
do
	New "die_$i" class/die
done

New cup class/cup
New display class/display

# main
while :
do
	@ cup "throw"
	read -s -n1 choice
	case "${choice^^}" in
	Q) exit ;;
	esac
done
  1. cup
cup=(  )

throw()
{
	local x

	for (( x=0 ; x < nr_of_dice ; ++x ))
	do
		@ "die_$x" 'throw && @ cup "collect $eyes"'
	done
}
collect()
{
	cup+=( "$1" )
	if [ "${#cup[*]}" -ge "$nr_of_dice" ]
	then
		@ display "Show ${cup[*]}"
		cup=( )
	fi
}
  1. die
throw()
{
	eyes="$(( RANDOM % 6 ))"
}
  1. display
eyes=( "0" '1' "2" '3' "4" '5' "6" '7' "8" '9'
".-------." ".-------." ".-------." ".-------." ".-------." ".-------." 6 7 8 9
"|       |" "|     0 |" "|     0 |" "| 0   0 |" "| 0   0 |" "| 0   0 |" 6 7 8 9
"|   0   |" "|       |" "|   0   |" "|       |" "|   0   |" "| 0   0 |" 6 7 8 9
"|       |" "| 0     |" "| 0     |" "| 0   0 |" "| 0   0 |" "| 0   0 |" 6 7 8 9
"'-------'" "'-------'" "'-------'" "'-------'" "'-------'" "'-------'" 6 7 8 9
)
Show()
{
	local row col

	[ -n "$debug" ] || clear

	for row in 1 2 3 4 5
	do
		for col in "$@"
		do
			echo -n "${eyes[${row}${col}]} "
		done
		echo
	done

	echo " [T]hrow or [Q]uit"
}

I hope you can read it and kind of guess how it works
If you are interested in more,let me know. :slight_smile:

EDIT: some changes for readability; EDIT2: corrected a spelling error;

3 Likes