# # On Wed, May 26, 2004 at 07:47:45AM -0400, Marco Baringer wrote: # >When I was in elementary school I wasted many an hour playing hangman # >with my friends. # # My solution is attached; I wrote the game server first, then a word # guesser following list discussion. # # The game server is fairly simple; it uses a slightly different data # representation from the others I've seen so far, in that it tracks # individual letters and only coincidentally maps them into the word. # # The guesser depends on having the dictionary available, and uses the # letter-frequency technique discussed; since a correct guess costs # nothing, it always picks the most common letter in the possible words. # # Roger # #! /usr/bin/perl -w use strict; my $dict=shift @ARGV; unless ($dict && -e $dict && -r $dict) { die "Can't open dictionary file.\n" } my $guesses=shift @ARGV || 11; my $word; { my $n=0; open DICT,"<$dict"; while () { $n++; if (rand($n)<1) { chomp; my $w=lc($_); if ($w !~ /[^- 'a-z]/) { $word=$w; } } } close DICT; } my %mask; my @letters=split '',$word; map {$mask{$_} = $_} @letters; map {$mask{$_} = '_'} ('a'..'z'); my $remaining=$guesses; my $show='_' x length($word); while (1) { print "$show\n"; chomp (my $guess=<>); $guess=lc(substr($guess,0,1)); if (exists $mask{$guess}) { if ($mask{$guess} eq '_') { $mask{$guess}=$guess; $show=join('',@mask{@letters}); if ($show !~ /_/) { print "LIFE!\n"; last; } if ($show !~ /$guess/) { $remaining--; if ($remaining<=0) { print "DEATH!\n"; last; } } } else { print "You've already tried that letter.\n"; } } else { print "You may only guess letters.\n"; } }