| Category: | Fun Stuff |
| Author/Contact Info | sulfericacid sulfericacid@qwest.net |
| Description: | Generates a random (or semi-random) number based on user's inputted $max. Object of game is to guess the number before your chances run out (default set at 5). Games completed, won and lost are stored into a database and presented to the user after each game. # Small bug fixed: Thanks Enlil! # Indents fixed: PerlTidy saved the day From this script I learned: naked blocks (which are a total life saver), the easier way to increment database variables and furthered my experience with regex (as scary as that is). |
#!/usr/bin/perl -W
use strict;
use warnings;
use POSIX;
use Fcntl;
use SDBM_File;
my %dbm;
my $test = "game.dbm";
my $win = 0;
my ( $total, $wonpercent, $lostpercent );
tie( %dbm, 'SDBM_File', $test, O_CREAT | O_RDWR, 0644 )
|| die "Died tying database\nReason: $!";
unless ( exists $dbm{win} ) { $dbm{win} = 0 }
unless ( exists $dbm{lost} ) { $dbm{lost} = 0 }
# max = maximum number to randomize
# tries = # of tries not to exceed $allowed
# allowed = max number of tries allowed
my $tries = 0;
my $guess;
my $allowed = 5;
print "What's the highest number you want to try?\n";
chomp( my $max = <STDIN> );
my $answer = int( rand($max) ) + 1;
while ( $tries < $allowed ) {
print " Your guess: ";
chomp( $guess = <STDIN> );
$tries++;
if ( $guess eq $answer ) {
last;
}
elsif ( $guess > $answer ) {
print " $guess is too high!\n";
}
elsif ( $guess < $answer ) {
print " $guess is too low!\n";
}
}
if ( $guess eq $answer ) {
print "\nYou got it right!\n";
print "It only took you $tries tries!\n";
$dbm{won}++;
$dbm{total}++; # for stats
}
else {
print "\n You lose! You're only allowed $allowed guesses :(\n";
print "Answer was: $answer\n";
$dbm{lost}++;
$dbm{total}++; # for stats
}
print "-----------------------------------------\n";
print "Total games played: $dbm{total}\n";
$wonpercent = ( $dbm{won} / $dbm{total} ) * 100;
$lostpercent = ( $dbm{lost} / $dbm{total} ) * 100;
print "Games won: $dbm{won}\n";
print "Games lost: $dbm{lost}\n";
printf( "Percent won: %.0f\n", $wonpercent );
printf( "Percent lost: %.0f\n", $lostpercent );
print "-----------------------------------------\n";
|
|
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Guess A Number
by jasonk (Parson) on Mar 17, 2003 at 15:06 UTC | |
by sulfericacid (Deacon) on Mar 17, 2003 at 17:21 UTC | |
by Anonymous Monk on Mar 17, 2003 at 19:33 UTC | |
by sulfericacid (Deacon) on Mar 18, 2003 at 04:29 UTC | |
by artist (Parson) on Mar 17, 2003 at 18:07 UTC | |
by sulfericacid (Deacon) on Mar 18, 2003 at 04:27 UTC | |
|
Re: Guess A Number
by parv (Parson) on Mar 17, 2003 at 18:00 UTC | |
|
Re: Guess A Number
by MrYoya (Monk) on Mar 17, 2003 at 19:00 UTC | |
by sulfericacid (Deacon) on Mar 18, 2003 at 04:32 UTC | |
|
Re: Guess A Number
by parv (Parson) on Mar 17, 2003 at 22:47 UTC | |
by sulfericacid (Deacon) on Mar 18, 2003 at 04:35 UTC |