Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Change the speed of snake in bash shell code

I have been tasked to create a "snake" game in shell scripting. I am having trouble adding keys 1,2,3 to control the moving speed of the snake, 1-slowest, 3-fastest.

How can I change the DELAY variably by pressing 1 for the delay to be .3, 2 for the delay to be .2 and 3 for the delay to be .1

The DELAY variable is originally set to .5 . If I change the DELAY, the speed of the snake changes.

Below is the code I have so far but it keeps breaking": I only put 1) as the key input because I dont want to put 2) and 3) until I can get 1) working.

    # Pick a random direction to start moving in
DIRECTIONS=( u d l r )
randomchar "${DIRECTIONS[@]}"

sleep 1
move
while :
   stty echo
do
   read -s -n 1 key
   case "$key" in
   w)   DIRECTION="u";;
   s)   DIRECTION="d";;
   a)   DIRECTION="l";;
   d)   DIRECTION="r";;
   1)   DELAY=".2";;
   2)   DELAY=".1";;
   3)   DELAY=".05";;

   x)   tput cup $COLS 0
        echo "Quitting..."
        tput cvvis
        stty echo
        tput reset
        printf "Bye Bye!\n"
        trap exit ALRM
        sleep $DELAY
        exit 0
        ;;
   esac
done

And above in a function I created called speed() my code looks like:

speed() {
    case "$SPEED" in
      1) DELAY=$(( $DELAY - 0.2 ));;
      2) DELAY=$(( $DELAY - 0.3 ));;
      3) DELAY=$(( $DELAY - 0.35 ));;
   esac

Comments