22
loading...
This website collects cookies to deliver better user experience
ch
which is initialized to 0 in the beginning so as to enter the loop for the first time. A while loop starts with the do statement and ends at the done statement.while [ condition ];
do
# statements
done
for i in {1..5};
do
#statements
done
then
to start the block and fi
to end the if block.if [ condition ];
then
#statements
elif
#statements
else
#statements
fi
ch
. If the input is 1, the game will start and it will ask the user for the number n
, which is the number used throughout the loop until the game is over. c
, this will store 0 for correct input(number x) and 1 for incorrect input. It is initialized with 0, again to enter the while loop once before the generation of numbers. shuf
which can create some permutation of the elements in a list/array or a sequence of numbers in an input stream. We are gonna use shuf
to generate a random sequence of 10 numbers from 0 to 9 using the command shuf -i 0-9 -n 10
. @
variable. If you are new to BASH and want a bit guide on BASH please do check out my series on BASH scripting, I have this all covered. So using @
we can print the entire array in BASH. r
as the shuffled list and a
as the indices list. And print this array with the same method.read -t 5 -p "Enter the index of your number : " x
x
variable and access it later for verification. c
as 1 indicating an improper input and thus it'll show "GAME OVER". But if you were fast enough then we'll check that the index of the shuffled array has your chosen number or not, we used this ${r[$(($x))-1]} -eq $n
to check for the correct number. Why -1? If you remember indexing in the array by default starts with 0, as we have started the second list from 1 hence every element will become offset by 1 hence to avoid that we'll subtract one to refer to that index. p
by one and if it was incorrect, the flag will be set to one as previously said and we'll break the loop. After coming out of the loop, we'll check if the status flag c
was 1 if yes, then print the GAME OVER and display the points earned. And that is it. Let's take a look at some gameplay :)#!/bin/bash
echo -e "\n NumberJack \n"
ch=0
while [ $ch -ne 3 ];
do
echo "
PLAY : Hit 1 and enter.
HELP : Hit 2 and enter.
EXIT : Hit 3 and enter.
"
read -p "Enter your choice : " ch
if [ $ch -eq 1 ];then
x=0
c=0
p=0
read -p "Enter any number between 0 and 9 : " n
while [ $c -eq 0 ];
do
x=11
r=($(shuf -i 0-9 -n 10))
echo "${r[@]} "
for i in {1..10};
do
a[$i]=$i
done
echo "${a[@]} "
read -t 5 -p "Enter the index of your number : " x
if [[ $? -gt 128 ]]; then
c=1
break
fi
if [ ${r[$(($x))-1]} -eq $n ];then
echo "Great"
((p=p+1))
else
c=1
break
fi
done
elif [ $ch -eq 2 ];then
echo "HELP: INSTRUCTIONS TO PLAY THE GAME. "
else
break
fi
if [ $c -eq 1 ];then
echo -e "\nGAME OVER\n"
echo "You scored $p points"
fi
done