Here is one version.
The rand() function is not really that random but it is good enough for this game.
This shows how to start the game, validate input to the game and also how to restart a new session of the game.
Certainly some refinements are possible, but this a general framework.
Update: I guess I could have combined two statements:#!/usr/bin/perl -w use strict; my $secret_number; my $total_guesses; sub init_game { $secret_number = int(rand 101); $total_guesses =0; } init_game(); #initial start of game parameters print "General Rules:\n"; print " I have a secret number from 0-100\n"; print " Your job is to guess this number!\n"; print " You will be given hints for each guess\n"; print " Enter quit if you give up!\n"; while ( (print "Enter a guess: "), (my $number = <STDIN>) !~ /^\s*q(uit)?\s*$/i ) { next if $number !~ /\S/; #skip blank lines $number =~ s/^\s*//; #no leading spaces $number =~ s/\s*$//; #no trailing spaces (also chomps) if ($number =~ /[-.]+/) { print "only unsigned integers are allowed!\n"; next; } if ($number =~ /\D/) { print "Invalid!! Only integer numbers >=0 are allowed!\n"; next; } if ($number >100) { print "Hey, you didn't pay attention, max number is 100!\n"; next; } if (game_finished($number)) { print "would you like to play again?:(Y|y|yes)\n"; if ( (my $answer =<STDIN>) =~ /^\s*Y(es)?\s*$/i) { init_game(); print "New Game Starting!!!\n\n"; } else { exit(0); } } } sub game_finished { my $number = shift; $total_guesses++; if ($number == $secret_number) { print "Horray! you got the secret number, $secret_number!\n"; print "But it took you $total_guesses total guesses to do it!!\ +n"; return(1); } if ($number < $secret_number) { print "You guessed too low! Dummy!\n"; return(0); } if ($number > $secret_number) { print "You guessed too high! Duh!\n"; return(0); } } Example Session: General Rules: I have a secret number from 0-100 Your job is to guess this number! You will be given hints for each guess Enter quit if you give up! Enter a guess: 50 You guessed too high! Duh! Enter a guess: 25 You guessed too high! Duh! Enter a guess: 12 You guessed too high! Duh! Enter a guess: 6 You guessed too low! Dummy! Enter a guess: 8 You guessed too high! Duh! Enter a guess: 7 Horray! you got the secret number, 7! But it took you 6 total guesses to do it!! would you like to play again?:(Y|y|yes) y New Game Starting!!! Enter a guess: q
if ($number =~ /[-.]+/) if ($number =~ /\D/) into just one regex: if( $number =~/[-.\D]/) { print "Invalid!! Only unsigned integer numbers >=0 are allowed! +\n"; next; } probably could add if( $number =~/[-.+\D]/) also to disallow the + sig +n. But I don't this minor issue detracts from the main point.
In reply to Re: Modifying loop structure and placement
by Marshall
in thread Modifying loop structure and placement
by irvson
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |