Wednesday, 2 March 2022

bashword : A Wordle-like game in BASH

bashword

 

#!/bin/bash
clear
shopt -s lastpipe
RED="\e[1;31m"
GREEN="\e[1;37;42m"
BROWN="\e[33m"
CYAN="\e[36m"
GRAY="\e[37m"
YELLOW="\e[1;43;30m"
COLOUR=( $GRAY $GREEN $YELLOW )
EOC="\e[0m"
z=$RANDOM
COUNT=0
guessNum=1
CONGRATS=("Extraordinary !" "Superb !" "Well Done" "Not bad" "Just OK... " "Just in time !")
 
# build a WORD array
grep "^.....$"  /usr/share/dict/words|grep -v "[é'[:upper:]]"|
while read word ;do
   WORDS[$COUNT]+=$word
   ((COUNT++))
done  

# select a random 5 letter word
word=${WORDS[$(($RANDOM % ${#WORDS[@]}))]}
echo -e $CYAN"Guess the 5 letter word"
echo -e "The letter clues are colour coded :"$EOC
echo -e "           "$GREEN     "  Correct position   "$EOC
echo -e "           "$YELLOW   "  Incorrect position "$EOC
if [ "$1" == "DEBUG" ] ; then echo "The word is:" $word ;fi

while [ $guessNum -lt  7 ]   
do
  found=0
 while [ $found -eq 0 ] ; do
  echo -e $CYAN"Enter guess no." $guessNum $EOC
  read guess
  while [ ${#guess} -lt 5 ] ;do
    echo "Enter a 5 letter word"
    read guess
  done  
  #check guess is real word
  n=${#WORDS[@]}
  ((n--))
  while [ $n -ge 0 ] ;do
    if [ ${WORDS[$n]} == $guess ] ; then
     found=1
     break
    fi
    ((n--))
  done
  if [ $found -eq 0 ];then
    echo -e $RED"Word not found in list, Try again"$EOC
  fi
 done
 
 # check for correct letter in correct space
 unset testWord
 match=(0 0 0 0 0 )
 for letter in {0..4} ;do
     testWord[$letter]+=${word:$letter:1}  
     if [ ${guess:$letter:1} == ${testWord[$letter]} ]; then
      set $((match[$letter] = 1))
      testWord[$letter]="_"
     fi
 done

# check for correct letters anywhere...  
 for gw in {0..4} ;do
    for tw in {0..4} ;do
     if [ ${testWord[$tw]} == ${guess:$gw:1} ]; then
      if [ ${match[$gw]} -eq 0 ] ;then
         set $((match[$gw] = 2))
         testWord[$tw]="_"
      fi
     fi
  done
 done  

# display matches
 echo " "
 for letter in {0..4} ;do
     echo -en ${COLOUR[${match[$letter]}]}" "${guess:$letter:1} $EOC
 done  
 echo
 echo

 if [ "$guess" ==  "$word" ] ; then
   echo ${CONGRATS[$guessNum-1]}
   echo
   break
 fi
  ((guessNum++))
done

if [ $guessNum -eq 7 ]; then
 echo -e "You ran out of guesses\nThe word was "$word
fi