#!/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";

In reply to Guess A Number by sulfericacid

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.