#!/bin/bash

function DrawMap
{
    count=1
    echo ""

    for i in $map; do
        if [ $count -eq $pos ] && [ $die -eq 0 ]; then
            echo -n "X "
        elif [ $count -eq $bomb1 ] && [ $die -eq 1 ]; then
            echo -n "! "
        elif [ $count -eq $bomb2 ] && [ $die -eq 1 ]; then
            echo -n "! "
        elif [ $count -eq 12 ]; then
            echo -n "$ "
        else
            echo -n "$i "
        fi

        if [ $[$count % 4] -eq 0 ]; then
            echo ""
        fi

        count=$[$count + 1]
    done

    echo ""
}

map='? ? ? ? ? ? ? ? ? ? ? ? '
pos=1
bomb1=$[$RANDOM % 5 + 2]
bomb2=$[$RANDOM % 5 + 7]
die=0
ok=0

echo "*** Floor Bomb x_x\" ***"
echo ""
echo "Instruction:"
echo "I = Move forward"
echo "K = Move backward"
echo "J = Move left"
echo "L = Move right"
echo "Q = Quit"
echo ""
DrawMap

while [ $ok -eq 0 ]; do
    echo -n "What do you want to do? "
    read cmd

    if [ "$cmd" = 'i' ] || [ "$cmd" = 'I' ]; then
        pos=$[$pos - 4]
        if [ $pos -lt 1 ]; then
            pos=$[$pos + 4]
        fi
    fi

    if [ "$cmd" = 'k' ] || [ "$cmd" = 'K' ]; then
        pos=$[$pos + 4]
        if [ $pos -gt 12 ]; then
            pos=$[$pos - 4]
        fi
    fi

    if [ "$cmd" = 'j' ] || [ "$cmd" = 'J' ]; then
        pos=$[$pos - 1]
        if [ $[$pos % 4] -eq 0 ]; then
            pos=$[$pos + 1]
        fi
    fi

    if [ "$cmd" = 'l' ] || [ "$cmd" = 'L' ]; then
        pos=$[$pos + 1]
        if [ $[$pos % 4 ] -eq 1 ]; then
            pos=$[$pos - 1]
        fi
    fi

    if [ "$cmd" = 'q' ] || [ "$cmd" = 'Q' ]; then
        echo ""
        echo "Bye !"
        ok=1
    fi

    if [ $pos -eq $bomb1 ] || [ $pos -eq $bomb2 ]; then
        die=1
    fi

    if [ $ok -eq 0 ]; then
        DrawMap

        if [ $die -eq 1 ]; then
            echo "You died. x_x"
            echo ""
            ok=1
        fi

        if [ $pos -eq 12 ]; then
            echo "Congratulation !!! ^_^"
            echo ""
            ok=1
        fi
    fi
done
