One More Blog

Tuesday, June 03, 2008

A Simple Perl Game

A few into after starting with Perl, I have managed to write a small and simple perl game. It does not do big things but can be used as a timepass. The idea is about guessing a random number correctly. Every time you run the program, it will create a random number between 1 to 100. As you enter your guess, it will tell you whether your guess is more or less than the number. The program finishes when you guess the correct number. The point is to minimize the number of wrong attempts.

Below is the source code for the game written in Perl. You will need a Perl interpreter to execute this. After you have Perl, type perl game.pl to execute the program after you save it in a file game.pl






#!/usr/bin/perl -w

## random_guess.pl - A small game to guess a random number between 1 to 100
## Copyright 2008 Sourav Banerjee

## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see .


use strict;

my $secret_num = int(1 + rand 100);

print "Enter your guess between 1 to 100, press enter
or type quit or exit to quit the program:\n";

while (1) {
chomp(my $guess = );
if ( $guess =~ /quit|exit|^\s*$/i ) {
print "Exiting the program.\n";
last;
} elsif ( ! ($guess =~ /^\d+$/) ) {
print "Invalid input, please enter a number\n";
redo;
} elsif ( $guess eq $secret_num ) {
print "Your guess is correct.\n";
last;
} else {
if ( $guess < $secret_num ) {
print "Too low, try again\n";
redo;
} else {
print "Too high, try again\n";
redo;
}
}
}

Labels: ,

0 Comments:

Post a Comment

<< Home