Simple Hangman Game

I was working though simple Perl with some guys that were interested in learning.  So I came up with the idea of making a simple hangman game as an example to work off of.  This is a working game that could use lots more refinement, but was a great teaching tool.  I will add comments to this code later, they were intentionally left out so that they couldn’t cheat.  Here is the code:


#!/usr/bin/perl
#######################################################################
## Written by: Josh Reeley (7/21/2011) reeley AT reeleysoft DOT com
## hangman.pl
#######################################################################
my $errors = 0;
my @words = ("google", "yahoo", "cites", "super", "orange", "pillow", "monitor");
my @guessedAnswer = ();
my @guessedWrong = ();
my $guessLetter;
my $correctCount = 0;
sub askGuess() {
 print "What letter do you want to guess?: ";
 $guessLetter = <STDIN>;
 chomp($guessLetter);
 print "\n";
}
my $number = rand @words;
my $num = substr($number, 0, 1); 
my $answerWord = $words[$num];
my $answerCount = length($answerWord);
my @answer = split(undef,$answerWord);
&answerSpaces($answerCount);
print "@guessedAnswer\n";
&printGallows($errors);
&askGuess();
&checkAnswer($guessLetter);
while ($error <= $answerCount) {
 if ($answerCount eq $correctCount) {
 print "Congratulations, you won!\n";
 exit;
 } else {
 &askGuess();
 &checkAnswer($guessLetter);
 }
}
sub checkAnswer() {
 my $guessLetter = shift;
 my $i = 0;
 my $succeed = 0;
 foreach (@answer) {
 if ($guessLetter eq $_) { 
 $guessedAnswer[$i] = $guessLetter;
 $correctCount++;
 $succeed = 1;
 }
 $i++;
 }
 if ($succeed == 0) {
 push(@guessedWrong,$guessLetter);
 $errors++;
 }
 system(clear);
 print "@guessedAnswer\n";
 &printGallows($errors);
 print "@guessedWrong\n";
}
sub answerSpaces() {
 my $answerCount = shift;
 my $i = 0;
 while ($answerCount > $i) {
 $guessedAnswer[$i] = "_";
 $i++;
 }

}
sub printGallows() {
 my $errors = shift;
 print " -----\n";
 print " | |\n";
 if ($errors < 1) {print " |\n";} else {print " | O\n";}
 if ($errors == 2) {print " | |\n";}
 if ($errors == 3) {print " | /|\n";}
 if ($errors < 4) {print " |\n";} else {print " | /|\\\n";}
 if ($errors < 5) {print " |\n";} else {print " | |\n";}
 if ($errors == 6) {print " | /\n";}
 if ($errors < 7) {print " |\n";} else {print " | / \\\n";}
 print " |\n";
 print " -----\n";
 if ($errors >= 7) {
 print "YOU LOSE!\n";
 print $answerWord ."\n";
 exit;
 }
}
Be Sociable, Share!

Leave a Reply