Skip to content

Instantly share code, notes, and snippets.

@leagris
Created July 4, 2021 01:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leagris/509350e90cb1dd1790b2b07a30132903 to your computer and use it in GitHub Desktop.
Save leagris/509350e90cb1dd1790b2b07a30132903 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
print_basket() {
# Print remaining keys (content of basket)
for fruit in "${!basket[@]}"; do
printf '%d %s\n' "${basket[$fruit]}" "${fruit,,}"
done
}
declare -a all_fruits=(
'apple' 'banana' 'cherry' 'lemon' 'mango'
'orange' 'peach' 'plum' 'red banana' 'sweat chestnut')
# Number of fruits in the basked
selection_size=3
clear
cat <<EOF
--:{# Guess the fruits in my basket #}:--
? ? ?
\ ? ? ? ? /
\_?_?_?_/
EOF
printf 'I went to the market, and got %d different fruits in my basket out of this selection of %d:\n' \
"$selection_size" "${#all_fruits[@]}"
printf -- '- %s\n' "${all_fruits[@]}"
printf '\n'
declare -A basket
# Randomize a selection of fruits
i=0
# Iterate to fill all slots of our selection basket
while [ "$i" -lt "$selection_size" ]; do
# Gett all available fruit indexes (names) in an array
fruit_indexes=("${!all_fruits[@]}")
# Randomly select a fruit to pick for our basket
fruits_length="${#fruit_indexes[@]}"
j="${fruit_indexes[RANDOM % fruits_length]}"
fruit="${all_fruits[j]}"
# Set the fruit in our basket with a random amount between 1 and 10
basket[${fruit^^}]=$((RANDOM % 9 + 1))
# Remove the fruit from all_fruits so it cannot be selected again
unset 'all_fruits[j]'
i=$((i + 1))
done
# Debug / Cheating
# declare -p basket
max_tries=3
tries_left=$max_tries
guessed=0
while [ $guessed -lt $selection_size ] && [ $tries_left -gt 0 ]; do
printf 'Enter the name of a fruit: '
read -r fruit
# Uppercase fruit for case insensitive match
fruit="${fruit^^}"
if [[ -v basket[$fruit] ]]; then
printf 'Yes, there is %d %s in my basket!\n' \
"${basket[$fruit]}" "${fruit,,}"
guessed=$((guessed + 1))
# Remove fruit from basket
unset "basket[$fruit]"
else
tries_left=$((tries_left - 1))
printf 'No, thre is no %s in my basket!\nTries left: %d\n' \
"${fruit,,}" "$tries_left"
fi
done
# Display the game results
printf '\n'
case $guessed in
"$selection_size")
printf '* * * Congratulations, you guessed all fruilts ! * * *\n'
;;
0)
printf 'Sorry you could not guess any of the fruits!\nBasket contained:\n'
print_basket
;;
*)
printf 'Nice! You guessed %d fruits out of %s!\nUnguessed fruits:\n' \
"$guessed" "$selection_size"
print_basket
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment