#!/bin/bash

function DrawMan
{
    if [ $pos -eq 6 ]; then
        m1="$dm1"
        m2="$dm2"
        m3="$dm3"
        m4="$dm4"
    else
        m1="$lm1"
        m2="$lm2"
        m3="$lm3"
        m4="$lm4"
    fi

    echo "                     $m1"

    for j in 0 1 2 3 4 5 6; do
        if [ $j -eq $pos ]; then
            echo -n "-->"
        else
            echo -n "   "
        fi
    done

    echo "$m2"
    echo "                     $m3"
    echo "                     $m4"
}

lm1='  ---  '
lm2='\(^_^)/'
lm3=' |___| '
lm4=' /   \ '

dm1='  ---  '
dm2='*(x_x) '
dm3='/|___|\'
dm4=' /   \ '

num1=11
num2=989
num3=11
num4=32

echo "*** Math Test \(^_^)/ ***"
echo ""

ok=0
pos=0
cor=0

while [ $ok -eq 0 ]; do
    echo -n "Start(S) or Quit(Q) ? "
    read ans

    if [ "$ans" = 'q' ] || [ "$ans" = 'Q' ]; then
        echo ""
        echo "Bye !"
        exit
    fi

    if [ "$ans" = 's' ] || [ "$ans" = 'S' ]; then
        ok=1
        echo ""
    fi
done

t1=`date +%s`

for i in 1 2 3 4 5; do
    r0=$[$RANDOM % 4]

    if [ $r0 -eq 0 ]; then
        r1=$[($RANDOM % (num2 - num1 + 1)) + num1]
        r2=$[($RANDOM % (num2 - num1 + 1)) + num1]
        ra=$[$r1 + $r2]
        rs='+'
    fi

    if [ $r0 -eq 1 ]; then
        r1=$[($RANDOM % (num2 - num1 + 1)) + num1]
        r2=$[($RANDOM % (num2 - num1 + 1)) + num1]
        ra=$[$r1 - $r2]
        rs='-'
    fi

    if [ $r0 -eq 2 ]; then
        r1=$[($RANDOM % (num4 - num3 + 1)) + num3]
        r2=$[($RANDOM % (num4 - num3 + 1)) + num3]
        ra=$[$r1 * $r2]
        rs='*'
    fi

    if [ $r0 -eq 3 ]; then
        r1=$[($RANDOM % (num4 - num3 + 1)) + num3]
        r2=$[($RANDOM % (num4 - num3 + 1)) + num3]
        ra=$[r1]
        r1=$[r1 * r2]
        rs='/'
    fi

    ok=0
   
    while [ $ok -eq 0 ]; do
        DrawMan
        echo ""

        if [ $pos -eq 6 ]; then
            echo "You died becuase of too stupid. :)"
            exit
        fi

        echo "Question $i:  $r1 $rs $r2 = ?"
        echo ""
        echo -n "What is the answer (Q to exit) ? "
        read ans

        if [ "$ans" = 'q' ] || [ "$ans" = 'Q' ]; then
            echo ""
            exit
        fi

        if [ $ans -eq $ra ]; then
            echo "Correct !"
            ok=1
            cor=$[$cor + 1]
        else
            echo "Wrong !"
            pos=$[$pos + 1]
        fi

        echo ""
    done
done

t2=`date +%s`
tt=`expr $t2 - $t1`
echo "Well done !!! You finished the math test in $tt seconds."
