Hangman
am 10.07.2006 01:12:23 von weberwCan someone help with my code? When the user enters "c" in the text
box it fills in c_ _, which is great. But when they enter the next
letter, like "a". It erases the c_ _ and produces _ a _. I need to
keep it to be ca_. Also how do you get the number of wrong guesses in
a string? Example, j,l,u,v etc.so the user knows the letters they have
entered?
#!C://Perl/bin/perl
use CGI ':standard';
use CGI::Carp 'fatalsToBrowser';
use constant MAX_MISSES => 8;
&display();
my $word;
$word = "cat";
my $misses_left = MAX_MISSES;
my %letters = map {$_ => 1} split //, $word;;
my %guesses = ();
if (param()) {
my $guess = param('guess');
&processguess($guess);
sub processguess{
if (exists $guesses{$guess}) {
print qq(You\'ve already guessed "$guess".\n);
}
$guesses{$guess}++;
if (exists $letters{$guess}) {
delete $letters{$guess};
keys %letters or last GUESSES;
} else {
--$misses_left;
print "another";
}
if ($misses_left > 0)
{
print "Your guess is: ", join(' ', sort keys %guesses), "\n";
print "You have $misses_left misses left.\n\n";
print join(' ', map {exists $guesses{$_} ? $_ : '_'} split //,
$word), "\n";
my $guess;
}
}
}
}
sub display {
my $the_cookie = cookie (
-name=>'gameid',
-value=>$id,
-expires=>'+1h');
print header(-cookie=>$the_cookie),
start_html(
-title=>"Hangman!",
-onLoad=>"document.forms[0].guess.select()"),
h1("Hangman!"),
"Tries Remaining: ",
"The word: ",
br,
"Letters guessed so far: ",
br,
start_form,
"Next Guess: ",
textfield (
-name=>"guess",
-size=>5,
-maxlength=>1,
-default=>''),
br,
br,
br,
submit (-name=>"submit", -label=>"Guess"),
submit (-name=>"new_game", -label=>"New Game"),
end_form,
end_html;
}
end_html;