#!/usr/local/bin/perl -w use strict; srand(time); my $words_equal = 999; # Compute the "score" of two words - how many characters # they have in common. # # Returns $words_equal if the given words are equal, otherwise # returns the number of common characters # sub score { my ($word1, $word2) = @_; my %bag; my $score = 0; return $words_equal if ($word1 eq $word2); foreach (split '', $word1) { $bag{$_}++; } foreach (split '', $word2) { if ($bag{$_}) { $bag{$_}--; $score++; } } return $score; } # Returns a random element from a given array # sub random_arr_elem { my @arr = @{$_[0]}; return $arr[rand() * ($#arr + 1)]; } # Given the name of a dictionary file, picks a random word from it # sub pick_random_word_from_file { my $filename = $_[0]; open(FH, $filename) or die "Can't open $filename: $!\n"; my @words = <FH>; my $the_word = random_arr_elem(\@words); chomp $the_word; return $the_word; } # "Refines" an array of words # Given an array of words, a guess, and the score of that guess, # removes all array elements that don't get the same score with # the guess # sub refine_words_array { my @arr = @{$_[0]}; my $guess = $_[1]; my $score = $_[2]; my @res_arr; foreach (@arr) { push(@res_arr, $_) if ($score == score($guess, $_)); } return \@res_arr; } # Play a human guess game - the human tries to guess a word # # Asks for a dictionary file. Picks a random word from this # file, and lets the human guess # sub human_guess_game { print "Specify dictionary file: "; my $dict_file = <>; chomp $dict_file; my $word = pick_random_word_from_file($dict_file); print "\n** $word **\n"; while (1) { print "\nEnter a guess: "; my $guess = <>; chomp $guess; if (score($word, $guess) == $words_equal) { print "\nCongrats, you guessed it !\n\n"; last; } else { print score($word, $guess); } } } # Play a computer guess game - the computer tries to guess a work # # Asks for a dictionary file and starts guessing words. The user # must supply the score for each guess # sub computer_guess_game { print "If I guess correctly, please enter $words_equal as the scor +e\n"; print "Specify dictionary file: "; my $dict_file = <>; chomp $dict_file; # Get a list of words from the dictionary file # open(FH, $dict_file) or die "Can't open $dict_file: $!\n"; my @words = <FH>; chomp(@words); my $guess = random_arr_elem(\@words); while (1) { print "My guess is: $guess\n"; print "Score: "; my $score = <>; chomp $score; if ($score == $words_equal) { print "\nYay, I won !!\n"; last; } my $ref = refine_words_array(\@words, $guess, $score); @words = @$ref; if (scalar(@words) == 0) { print "\nNo suitable word in the given dictionary !!\n"; last; } print "Legal words left: " . scalar(@words) . "\n"; $guess = random_arr_elem(\@words); } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: The Jotto word game
by queue (Beadle) on Jan 09, 2003 at 19:53 UTC | |
|
Re: The Jotto word game
by spurperl (Priest) on Jan 14, 2003 at 09:55 UTC |