[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] hangman



James Fox wrote:
> 
> anyone got the scripts for a version of hangman?
> 
> (trying to brighten up my day with cgi)
> 

Here is Jonathan Feinberg's command-line hangman.  He posted it to clpm
a while back.  Sorry, it's not CGI; you'll have to do that part yourself.
:)

I also note that Lincoln Stein's CGI tutorial for O'Reilly includes
a discussion of a networked multiplayer version of hangman.

Ronald

---


#!/usr/local/bin/perl

# Jonathan Feinberg   jdf@pobox.com

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): ";
        chomp (my $again = <STDIN>);
        last GAMES unless $again =~ /^y/i;
    }

===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org