| By Dave Taylor | Article Rating: |
|
| April 6, 2005 12:00 AM EDT | Reads: |
9,578 |
If the print gods are with us, this time, after seven previous columns, we'll finally have a shell script that you can type in and experiment with. Imagine!
The last column addressed the challenges of generating a reasonably random number to enable us to write a rudimentary hi-low guessing game. After experimentation, we settled on using the date command with some fancy footwork to generate a number between 1..x as shown here:
toguess="$(expr `date +%S` % 20 + 1)"
In this case, the result is a quasi-random number between 1 and 20. Good enough for our game, which involves the computer picking a number and then you guessing that number. If you guess too high, it'll prompt "lower," and if you guess too low, it indicates "higher." Not quite as complex as the shell script implementation of Halo 2, but let's start with something manageable.
Basic Looping Structures
The core looping structure of the hi-low game is a while loop, which takes the form:while condition do statements done
The condition is a test statement, though use the "[" shortcut to make it a bit cleaner. For this game, I'm going to let the player have a maximum of 10 guesses, which looks like this:
while [ $guesses -lt 10 ] do statements done
The first requirement of the statements within this loop is a statement that keeps track of how many guesses have been entered (which is the same as how many times the script has cycled through the loop). This is done with the modern shell $(( )) math notation:
guesses=$(( $guesses + 1 ))
If you're running a crufty old shell, it might toss up on that statement (even though it's the Posix way of doing things). If so, just replace it with the old fashioned statement
guesses= "$(expr $guesses + 1)"
The other statement blocks required are user input and a conditional test sequence.
Reading User Input
You already know that echo is the standard method of having shell scripts produce output, but might not know that read is the equivalent for input. Further, since it's nice to have the prompt for input on the same line as the cursor when you're asking for the user to type something in, it's useful to add the "-n" flag to echo. The prompt and input look like this:echo -n "Guess? " read answer
Notice that this is the only time when you'll reference a shell variable without the "$" prefix: if you tried read $answer you'd get an error.
Testing User Input
There are a number of different ways to test the guess against the secret value, but I just use a simple if-then-else sequence for clarity:
if [ $answer -eq $toguess ]
then
echo "Got it! Guesses = $guesses"
exit 0
elif [ $answer -lt $toguess ]
then
echo "higher"
else
echo "lower"
fi
Again, this should be straightforward: if they've guessed the correct value, output a success message, show how many guesses it took, and exit the script. Otherwise, if the answer is too low, suggest "higher," and if it's too high, suggest "lower."
Putting It All Together
Those are all the pieces; let's put it all together in a single listing:
#!/bin/sh
toguess="$(expr `date +%S` % 20 + 1)"
guesses=1
while [ $guesses -lt 10 ]
do
echo -n "Guess? "
read answer
if [ $answer -eq $toguess ]
then
echo "Got it! Guesses = $guesses"
exit 0
elif [ $answer -lt $toguess ]
then
echo "higher"
else
echo "lower"
fi
guesses=$(( $guesses + 1 ))
done
echo "Too many guesses. Number was $toguess"
exit 0
And, since this is a family magazine, let's have a quick game:
$ sh hilow.sh Guess? 10 higher Guess? 15 higher Guess? 17 higher Guess? 19 lower Guess? 18 Got it! Guesses = 5
There we go! Try modifying this script yourself to learn more about scripting. One simple change: make the game harder by having the range of guesses be 1-100 (or more!) or make it really frustrating by changing the number every five guesses, but still only allow a fixed number of guesses.
Published April 6, 2005 Reads 9,578
Copyright © 2005 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Dave Taylor
Dave Taylor, a contributing editor to Linux.SYS-CON.com, has been involved with the Linux and Unix community since 1980 and has written a number of best-selling Unix books. Currently, he writes, teaches, and works as a management consultant to tech startups, along with his new venture, Ask Dave Taylor!, www.askdavetaylor.com and his personal blog is www.blog.Linux.SYS-CON.com. To contact Dave, please go to /www.intuitive.com/contact.shtml.
- Kindle 2 vs Nook
- Is Cloud Computing Like Teenage Sex?
- GovIT Expo Highlights Cloud Computing
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- Cloud Computing Can Revitalize Your Career as Software Developer
- Ubuntu-based Open Source Linux Mint Tests KDE Version
- Yahoo! SVP Shelton Shugar to Discuss Innovation at Cloud Computing Expo
- Virtualization Journal "Readers' Choice Awards" Voting Is Now Open
- Einstein, Sharks and Clouds: IT Security in the Cloud
- Adobe Flex Developer Earns $100K in New York City
- Amazon Web Services Database in the Cloud
- Virtualization Expo Call for Papers Deadline December 15
- Kindle 2 vs Nook
- Cloud CEOs, CTOs & SVPs to Speak at 4th International Cloud Computing Expo
- Is Cloud Computing Like Teenage Sex?
- 1st Annual GovIT Expo: Letter from the Technical Chair
- Ulitzer News: Search vs New Media
- The Difference Between Web Hosting and Cloud Computing
- Cloud Computing Expo: Exclusive Q&A with Yahoo! SVP Cloud Computing
- Confessions of a Ulitzer Addict
- GovIT Expo Highlights Cloud Computing
- Twitter, Linked In, Ning and Ulitzer: Easy Personal Branding Strategy
- My Thoughts on Ulitzer
- Tactical Cloud Computing Panel at 1st Annual GovIT Expo
- The i-Technology Right Stuff
- Linux.SYS-CON.com Exclusive: Linus Discloses *Real* Fathers of Linux
- After Ubuntu, Windows Looks Increasingly Bad, Increasingly Archaic, Increasingly Unfriendly
- Linus' Top Ten SCO Barbs
- A Closer Look at Damn Small Linux
- Netscape Co-Founder's 12 Reasons for Growth of Open Source
- Introducing "Cooperative Linux" - Linux for Windows, No Less
- *POINT - COUNTERPOINT SPECIAL* What's Wrong with the Open Source Community?
- Where Are RIA Technologies Headed in 2008?
- Linux.SYS-CON.com Exclusive: What Would UserLinux Look Like?
- i-Technology Viewpoint: The New Paradigm of IT Buying
- Is Linux Desktop-Ready Yet...or Not?
































