#!/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. setglobal wordlib = '"/usr/lib/games/long-words.txt'" setglobal empty = '"\.'" # we need something for the sed [set] when $guessed="" setglobal 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" { setglobal match = $[randomquote $wordlib] # pick a new word from the library if test $games -gt 0 { echo "" echo "*** New Game! ***" } setglobal games = "$shExpr(' $games + 1 ')" setglobal guessed = ''"" ; setglobal guess = ''"" ; setglobal bad = $(1:-6) setglobal 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 { setglobal guessed = ""$guessed$guess"" setglobal partial = $[echo $match | sed "s/[^$empty$(guessed)]/-/g] if test $partial = $match { echo "** You've been pardoned!! Well done! The word was \"$match\"." setglobal 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\"" setglobal guess = $match } else { echo "* Nope, \"$guess\" does not appear in the word." setglobal guessed = ""$guessed$guess"" setglobal bad = $shExpr(' $bad - 1 ') } } } exit 0