bash-exercises/guess_number.sh

81 lines
1.6 KiB
Bash
Raw Normal View History

2025-01-13 09:27:30 +01:00
#!/bin/bash
RANDOM_NUM=0
ACTION_TO_TAKE=""
ATTEMPTS_NUM=7
POOL_NUM=100
usage ()
{
echo "Usage: ./guess_number.sh -p 50 -a 30"
echo ""
echo "PARAMETERS"
echo " -h (Show this help prompt)"
echo " -a $ (set the amount of available attempts)"
echo " -p $ (set the amount of numbers that will be generated)"
exit
}
while getopts a:p:h flag; do
case "${flag}" in
a) ATTEMPTS_NUM=${OPTARG};;
p) POOL_NUM=${OPTARG};;
h) usage;;
esac
done
status() {
clear
cat <<'END_CAT'
______________
< Buena suerte >
--------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
END_CAT
echo "Intenta adivinar el número entre 0 y $POOL_NUM!"
echo "Intentos restantes: $ATTEMPTS_NUM"
}
checkWin() {
if [[ "$1" == "$RANDOM_NUM" ]]; then
echo "Enhorabuena! El número era $RANDOM_NUM!"
exit
fi
if [[ "$1" != "$RANDOM_NUM" ]]; then
if [[ $1 -gt $RANDOM_NUM ]]; then
echo "El número es demasiado alto!"
ATTEMPTS_NUM=$((ATTEMPTS_NUM - 1))
return 0
fi
if [[ $1 -lt $RANDOM_NUM ]]; then
echo "El número es demasiado bajo!"
ATTEMPTS_NUM=$((ATTEMPTS_NUM - 1))
return 0
fi
fi
}
checkLose() {
if [[ $ATTEMPTS_NUM == 0 ]]; then
echo "Pierdes! El número era $RANDOM_NUM :/"
exit
fi
}
main() {
RANDOM_NUM=$(seq 0 $POOL_NUM | tr " " "\n" | shuf -n1)
while true; do
status
checkLose
read -p "Número: " num_attempt
checkWin $num_attempt
read -p "Pulse enter para continuar: "
done
}
main