| By Dave Taylor | Article Rating: |
|
| April 6, 2005 12:00 AM EDT | Reads: |
10,629 |
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 10,629
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.
- Ubuntu-based Open Source Linux Mint Tests KDE Version
- Linux Virtualization and Tired Open Source Myths
- IGEL Supports Red Hat Enterprise Virtualization 3.0
- CloudLinux Announces Support for Atomia
- Amazon Kindle Fire Gets Its Own 'Personal Cloud Desktop' with AlwaysOnPC App Launch
- SPIRIT DSP Receives 2011 INTERNET TELEPHONY Product of the Year Award
- Hadoop Quickstart: Use Whirr to automate standup of your distributed cluster on Rackspace
- Jury Gets Novell Antitrust Case Against Microsoft
- The Utility Infrastructure Security Market 2012-2022: Cybersecurity & Smart Grids
- FORTUNE Magazine Names Rackspace Among “100 Best Companies to Work For”
- iFollowOffice Turns to Virtual Bridges and Savvis for On-Demand Virtual Desktop Services
- EnterpriseDB Announces Availability of Postgres Plus Cloud Database
- i-Technology in 2012: Five Industry Predictions
- Ubuntu-based Open Source Linux Mint Tests KDE Version
- Amazon to Rent Out Supercomputers
- Amazon Émigré Starts Network Monitoring Firm
- HP’s Putting a Back Door in the Itanium Alamo
- Linux Virtualization and Tired Open Source Myths
- CloudLinux Announces Preferred Partner Program
- MapR Pushes the Hadoop Envelope
- Rightware Announces Gaming Performance Benchmark for OpenGL ES 3.0/Halti
- IGEL Supports Red Hat Enterprise Virtualization 3.0
- CloudLinux Announces Support for Atomia
- 3Dconnexion Announces its Newest 3D Mouse - the SpaceMouse Pro
- 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
- A Closer Look at Damn Small Linux
- Linus' Top Ten SCO Barbs
- SCO CEO Posts Open Letter to the Open Source Community
- Netscape Co-Founder's 12 Reasons for Growth of Open Source
- Where Are RIA Technologies Headed in 2008?
- *POINT - COUNTERPOINT SPECIAL* What's Wrong with the Open Source Community?
- Introducing "Cooperative Linux" - Linux for Windows, No Less
- Linux.SYS-CON.com Exclusive: What Would UserLinux Look Like?
- Why Recovering a Deleted Ext3 File Is Difficult . . .


















