-
Notifications
You must be signed in to change notification settings - Fork 0
/
84-hangman
80 lines (68 loc) · 2.83 KB
/
84-hangman
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/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.
wordlib="/usr/lib/games/long-words.txt"
empty="\." # we need something for the sed [set] when $guessed=""
games=0
# Start by testing for our word library datafile
if [ ! -r “$wordlib” ] ; then
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
fi
# The big while loop. This is where everything happens
while [ "$guess" != "quit" ] ; do
match="$(randomquote $wordlib)" # pick a new word from the library
if [ $games -gt 0 ] ; then
echo ""
echo "*** New Game! ***"
fi
games="$(( $games + 1 ))"
guessed="" ; guess="" ; bad=${1:-6}
partial="$(echo $match | sed "s/[^$empty${guessed}]/-/g")"
# The guess > analyze > show results > loop happens in this block
while [ "$guess" != "$match" -a "$guess" != "quit" ] ; do
echo ""
if [ ! -z "$guessed" ] ; then # remember, ! –z means “is not empty”
/bin/echo -n "Guessed: $guessed, "
fi
echo "Steps from gallows: $bad, word so far: $partial"
/bin/echo -n "Guess a letter: "
read guess
echo ""
if [ "$guess" = "$match" ] ; then # Got it!
echo "You got it!"
elif [ "$guess" = "quit" ] ; then # 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 [ $(echo $guess | wc -c | sed 's/[^[:digit:]]//g') -ne 2 ] ; then
echo "Uh oh: You can only guess a single letter at a time"
elif [ ! -z "$(echo $guess | sed 's/[[:lower:]]//g')" ] ; then
echo "Uh oh: Please only use lowercase letters for your guesses"
elif [ -z "$(echo $guess | sed "s/[$empty$guessed]//g")" ] ; then
echo "Uh oh: You have already tried $guess"
# Now we can actually see if the letter appears in the word
elif [ "$(echo $match | sed "s/$guess/-/g")" != "$match" ] ; then
guessed="$guessed$guess"
partial="$(echo $match | sed "s/[^$empty${guessed}]/-/g")"
if [ "$partial" = "$match" ] ; then
echo "** You've been pardoned!! Well done! The word was \"$match\"."
guess="$match"
else
echo "* Great! The letter \"$guess\" appears in the word!"
fi
elif [ $bad -eq 1 ] ; then
echo "** Uh oh: you've run out of steps. You're on the platform... <SNAP!>"
echo "** The word you were trying to guess was \"$match\""
guess="$match"
else
echo "* Nope, \"$guess\" does not appear in the word."
guessed="$guessed$guess"
bad=$(( $bad - 1 ))
fi
done
done
exit 0