sparksofl
6/24/2017 - 9:34 PM

hangman.sh

#!/bin/bash
# copyrigth (c) 2016 Solodovnik Mary

bold=$(tput bold)
normal=$(tput sgr0)
blue=$(tput setaf 6)
green=$(tput setaf 2)
red=$(tput setaf 1)
nc=$(tput sgr0)

function indexof() {
  sym=$1
  word=$2
  len=$((${#2}-1))
  index=-1
  for i in $(seq 0 $len)
  do
    if [ "$sym" == "${word:$i:1}" ]; then
      index=$i
      break;
    fi
  done
  echo $index
}

function reset_consts() {
  errors_counter=0
  errors_made=''
  max_errors=6
}

function replace_all_occurences() {
  index=`indexof "$guess" "$temp"`
  if [[ "$temp" =~ "$guess" ]] && [[ "$index" != -1 ]]; then
    mask="${mask:0:index}$guess${mask:((index+1))}"
    temp="${temp:0:index}_${temp:((index+1))}"
    if [ "$secret" == "$mask" ]; then
      echo "${green}${bold}$mask${normal}${nc}"
      echo "${bold}Hurray, you won!${normal}"
      break
    else
      replace_all_occurences
      echo $mask
      echo "It's there!"
    fi
  fi
}

function hangman {
  echo "Enter the word to guess 🔒 :"
  read -s secret
  len="${#secret}"; limit=$(($len-2))

  # s___t

  mask=`printf '_%.0s' $(seq 1 $len)`
  mask="${mask:0:0}${secret:0:1}${mask:1}"
  mask="${mask:0:((len-1))}${secret:((len-1)):((len-1))}${mask:len}"

  # _ecre_

  temp=$secret
  temp="${temp:0:0}_${temp:1}"
  temp="${temp:0:((len-1))}_${temp:len}"
  reset_consts

  while true; do
    clear
    echo "${bold}${blue}${mask}${nc}${normal}, errors: $errors_counter/$max_errors [${red}$errors_made${nc} ]"
    printf 'Enter a letter: '
    read guess
    index=`indexof "$guess" "$temp"`
    if [ "$guess" == 'show' ]; then
      echo "You proposed: $secret"
      break
    elif [ ${#guess} != 1 ]; then
      echo "It's not a letter!"
    elif [[ "$index" != -1 ]]; then
      replace_all_occurences
    elif [ "$secret" != *$guess* ]; then
      echo "Wrong!"
      ((errors_counter++))
      errors_made+=" $guess"
      if [ "$errors_counter" -eq "$max_errors" ]; then
        echo "You've lost"
        break
      fi
    fi
  done
}

echo "The hangman game. If you gave up, enter
'show' to see the word."
hangman

while true; do
  echo "Try again? [Y/N]: "
  read answer
  if [ "$answer" == 'Y' ]
  then
    hangman
  else
    break
  fi
done