From 8aa18c643ba72a28a6ffee67b23fc35bad2647a9 Mon Sep 17 00:00:00 2001 From: raul Date: Wed, 15 Jan 2025 19:16:54 +0100 Subject: [PATCH] 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 --- hangman/hangman.sh | 114 +++++++++++++++++++++++++++++++++++++++++++++ hangman/words.txt | 9 ++++ 2 files changed, 123 insertions(+) create mode 100755 hangman/hangman.sh create mode 100644 hangman/words.txt diff --git a/hangman/hangman.sh b/hangman/hangman.sh new file mode 100755 index 0000000..f7349a1 --- /dev/null +++ b/hangman/hangman.sh @@ -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 diff --git a/hangman/words.txt b/hangman/words.txt new file mode 100644 index 0000000..00e80c8 --- /dev/null +++ b/hangman/words.txt @@ -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