in reply to Hangman

Here is my silly little version. It has no clues and does no hangman ASCII art so it is more like "word guess" :P

Gratuitous screen shot:
>>>hangman<<<

 a  _  a  p  _  a  b  _  l  _  _  _

Incorrect guesses left: 7
       Already guessed: a b l m p r
            Your guess:

You can specify both the number of incorrect guesses allowed and the word file on the command line, or accept the defaults like so:
./hangman.pl
./hangman.pl 10
./hangman.pl 7 /usr/share/dict/dictionary

This version also does not allow words that begin with a capital letter (because I was finding guessing the proper nouns from /usr/share/dict/words too hard!)

#!/usr/bin/perl my (%g, $w, $s); my $s = shift || 9; my $file = shift || '/usr/share/dict/words'; die "Number of guesses must be greater than 0\n" if ($s <= 0); open(F, $file) || die "Can't open that dictionary file\n"; my $count = `wc -l < $file`; chomp($count); $count =~ s/[ \t]*//g; $count = int(rand() * $count) + 1; while ($count > 0 || $w =~ /^[A-Z]/) { $w = <F>; seek(F, 0, 0) if (! $w); $count--; } chomp($w); while ($s >= 0) { my $x = length($w); print "\f"; print ">>>hangman<<<\n\n"; for (0..length($w)-1) { if (exists($g{substr($w, $_, 1)})) { print " " . substr($w, $_, 1) . " "; $x--; } else { print " _ "; } } if (! $x) { print "\n\nCongratulations!!! ;)\n\n"; exit; } my @g = sort keys %g; print "\n\n"; print "Incorrect guesses left: $s\n"; print " Already guessed: @g\n"; GUESS: print " Your guess: "; my $g = <>; $g = lc(substr($g, 0, 1)); goto GUESS unless ($g =~ /[a-z]/); $s-- if ($w !~ /$g/ && ! exists $g{$g}); $g{$g} = 1; } print " The word was: \"$w\"\n\n";

Replies are listed 'Best First'.
Re^2: Hangman
by stigpje (Novice) on Jul 01, 2008 at 13:50 UTC