#!/bin/bash # hangman - A simple version of the hangman game. Instead of showing a # gradually embodied hanging man, this simply has a bad guess countdown. # You can optionally indicate the initial distance from the gallows as # the only arg. setvar wordlib = ""/usr/lib/games/long-words.txt"" setvar empty = ""\."" # we need something for the sed [set] when $guessed="" setvar games = '0' # Start by testing for our word library datafile if test ! -r $wordlib { echo "$0: Missing word library $wordlib" >&2 echo "(online: http://www.intuitive.com/wicked/examples/long-words.txt" >&2 echo "save the file as $wordlib and you're ready to play!)" >&2 exit 1 } # The big while loop. This is where everything happens while test $guess != "quit" { setvar match = "$(randomquote $wordlib)" # pick a new word from the library if test $games -gt 0 { echo "" echo "*** New Game! ***" } setvar games = """$(( $games + 1 ))" setvar guessed = """" ; setvar guess = """" ; setvar bad = ${1:-6} setvar partial = "$(echo $match | sed "s/[^$empty${guessed}]/-/g")" # The guess > analyze > show results > loop happens in this block while test $guess != $match -a $guess != "quit" { echo "" if test ! -z $guessed { # remember, ! –z means "is not empty" /bin/echo -n "Guessed: $guessed, " } echo "Steps from gallows: $bad, word so far: $partial" /bin/echo -n "Guess a letter: " read guess echo "" if test $guess = $match { # Got it! echo "You got it!" } elif test $guess = "quit" { # You’re out? Ok. sleep 0 # A 'no op' to avoid an error message on 'quit' # Now we need to validate the guess with various filters } elif test $(echo $guess | wc -c | sed 's/[^[:digit:]]//g') -ne 2 { echo "Uh oh: You can only guess a single letter at a time" } elif test ! -z $(echo $guess | sed 's/[[:lower:]]//g') { echo "Uh oh: Please only use lowercase letters for your guesses" } elif test -z $(echo $guess | sed "s/[$empty$guessed]//g") { echo "Uh oh: You have already tried $guess" # Now we can actually see if the letter appears in the word } elif test $(echo $match | sed "s/$guess/-/g") != $match { setvar guessed = ""$guessed$guess"" setvar partial = "$(echo $match | sed "s/[^$empty${guessed}]/-/g")" if test $partial = $match { echo "** You've been pardoned!! Well done! The word was \"$match\"." setvar guess = "$match" } else { echo "* Great! The letter \"$guess\" appears in the word!" } } elif test $bad -eq 1 { echo "** Uh oh: you've run out of steps. You're on the platform... " echo "** The word you were trying to guess was \"$match\"" setvar guess = "$match" } else { echo "* Nope, \"$guess\" does not appear in the word." setvar guessed = ""$guessed$guess"" setvar bad = $(( $bad - 1 )) } } } exit 0