I was going through some old papers and I found this short PERL hangman
script. If you want to learn PERL, this is a good script to study. To
test it, you can put it in your home directory. Make it executable
$ chmod 740 ./hangman.pl
When you run it, you have to specify a dictionary file. In other words, a file
that contains words which the hangman program can randomly select. i.e.
$ ./hangman.pl /usr/games/lib/hangman-words
brian
#!/usr/bin/perl -w
use strict;
$|++;
use constant MAX_MISSES => 6;
my $words_file = shift or die "Please specify words file on command line.\n";
GAMES:
while (1) {
open(WORDS, "<$words_file") or die "Can't open $words_file: $!"; my
$word;
rand($.) < 1 && ($word = $_) while <WORDS>; close WORDS or die "Can't
close $words_file: $!"; chomp $word;
my $misses_left = MAX_MISSES;
my %letters = map {$_ => 1} split //, $word;;
my %guesses = ();
GUESSES:
while ($misses_left) {
print "\n\n\nYou have guessed: ", join(' ', sort keys %guesses), "\n";
print "You have $misses_left misses left.\n\n"; print join(' ', map
{exists $guesses{$_} ? $_ : '_'} split //, $word), "\n"; my $guess;
GET_GUESS:
{
print "\nGuess a letter: ";
chop($guess = lc <STDIN>);
if ($guess !~ /^[a-z]$/) {
print "Please enter a single letter guess.\n";
redo GET_GUESS;
}
if (exists $guesses{$guess}) {
print qq(You\'ve already guessed "$guess".\n);
redo GET_GUESS;
}
}
$guesses{$guess}++;
if (exists $letters{$guess}) {
delete $letters{$guess};
keys %letters or last GUESSES;
} else {
--$misses_left;
}
}
if ($misses_left) {
print "\nYou guessed it: $word!";
} else {
print qq(\nOops... you\'re hanged. The word was "$word."); }
print "\n\n\nPlay again? (Y/N): ";
chop (my $again = <STDIN>);
last GAMES unless $again =~ /^y/i;
}
__END__
-- Brian Lavender http://www.brie.com/brian/
This archive was generated by hypermail 2b29 : Fri Feb 25 2000 - 14:29:06 PST