Add PoC hangman game written in Bash

Please don't use Bash for anything other than shell scripting, it really
really really sucks, I'm only doing this because I'm forced to by my
classes, just use Go
This commit is contained in:
raul 2025-01-15 19:16:54 +01:00
parent 31813090de
commit 8aa18c643b
Signed by: raul
GPG Key ID: C1AA797073F17129
2 changed files with 123 additions and 0 deletions

114
hangman/hangman.sh Executable file
View File

@ -0,0 +1,114 @@
#!/bin/bash
ATTEMPTS_NUM=7
SECRET_STRING=()
VISIBLE_STRING=()
FILEPATH=""
usage ()
{
echo "Usage: ./hangman.sh -f file.txt -a 20"
echo ""
echo "PARAMETERS"
echo " -h (show this help prompt)"
echo " -a $ (set the amount of available attempts)"
echo " -f file.txt (select the file to pull lines from)"
exit
}
while getopts a:f:h flag; do
case "${flag}" in
a) ATTEMPTS_NUM=${OPTARG};;
f) FILEPATH=${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
}
getLine() {
if [[ ! -f $FILEPATH ]]; then
echo "File doesn't exist!"
exit
fi
out=$(shuf -n1 $FILEPATH)
echo $out
}
arrayIze() {
LINE=$1
LINE_LEN="${#LINE}"
for ((i = 0; i < $LINE_LEN; i++)); do
CHAR=${LINE:i:1}
SECRET_STRING+=("$CHAR")
SECRET_STRING+=(" ")
if [[ $CHAR == " " ]]; then
VISIBLE_STRING+=('_')
else
VISIBLE_STRING+=("#")
fi
done
echo ${SECRET_STRING[*]}
echo ${VISIBLE_STRING[*]}
}
main() {
if [[ $FILEPATH == "" ]]; then
usage
fi
line=$(getLine)
echo $line
arrayIze "$line"
# while true; do
# status
# #checkLose
# read -p "Número: " num_attempt
# #checkWin $num_attempt
# read -p "Pulse enter para continuar: "
# done
}
main

9
hangman/words.txt Normal file
View File

@ -0,0 +1,9 @@
fantastic
achieve
this is a spaced sentence
this is another spaced sentence
security
tool
this is an even bigger spaced sentence
cathedral
committee