2

I've made a simple guessing game, which utilizes simple if-statement. Guess a number between 0 and 10. It'll hint you to put a higher/lower number. That's working fine. To make it a little more interesting, I'd like to taunt the user until the right answer is input.

Question: How to get a message item randonly and return this message if the user has not guessed the right number?

Example:
Guess a number: 5
You have no idea, huh? Try higher. 7
Ha! still far from it. Try higher. 8
Did you just fart? I'm sure it was a perfect 10! Try higher. 10
You momma did teach you how to count, right? Try lower. 9

Yes, well done!

Any ideas? :)

dat789
  • 1,923
  • 3
  • 20
  • 26

1 Answers1

4

You can try:

# Store your string in a BASH array:
arr=( "foo" "bar" "baz" "abc" "xyz" )

# get a number between 0 and length of array:
len=${#arr[@]}

# get a random string from array using BASH variable $RANDOM
n=$(($RANDOM % len))
echo ${arr[$n]}
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Is there a way to put the array in a function? – dat789 Oct 23 '13 at 14:09
  • Yes array can be created inside the function also but if values of the array are static then its better to keep it outside to avoid array creation every time function is called. – anubhava Oct 23 '13 at 14:15