in reply to Number Guess
I remember doing this game when I was first learning in BASIC. And then the corrolary - you pick the number, the computer guesses it. I learned binary searches that day, without realising it. ;-)
Comments:
useprint "Sorry, you ran out of guesses. My number was "; print $value; print ". \n";
Some people will use perl's interpolation to do this as:print "Sorry, you ran out of guesses. My number was ", $value, ". +\n";
The former may be faster, but in reality the deciding factor should be what you find to be more readable.print "Sorry, you ran out of guesses. My number was $value.\n";
#Guessing Game #You only get 10 tries! #Gives the option of starting over. #This version should count your turns for you, down from ten. use strict; use warnings; #This is how many guesses you get. my $max_guesses = 10; sub game { #This is the number they have to guess: a random integer. my $value = int(rand(200)); print "Pick a number between 0 and 200.\n"; for (my $tries = $max_guesses; $tries; --$tries) { print "You have ", $tries, " guesses left.\n"; my $guess = <STDIN>; if($guess>$value) { print "You need to guess a lower number.\n"; print "Guesses left: ", $tries, "\n"; } elsif($guess<$value) { print "You need to guess a higher number.\n"; print "Guesses left: ", $tries, "\n"; } else { print "You guessed my number in ", $max_guesses - $tries, " guesses. Thanks for playing. \n"; return; } } print "Sorry, you ran out of guesses. My number was ", $value, ". +\n"; } my $again = 'y'; while ($again eq 'y') { game(); print "Play Again? (y/n) \n"; $again = <STDIN>; chomp ($again); } print "Goodbye!\n";
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Number Guess
by cryptoquip (Novice) on Jul 15, 2005 at 19:33 UTC | |
by Tanktalus (Canon) on Jul 15, 2005 at 20:41 UTC | |
by cryptoquip (Novice) on Jul 15, 2005 at 21:55 UTC | |
Re^2: Number Guess
by cryptoquip (Novice) on Aug 05, 2005 at 18:51 UTC |