Here is a somewhat shorter version to play with -- it differs in the ordering of the previous guesses (but you can change push() to unshift() to get the original behaviour):
#!/usr/bin/perl -w use strict; # Colors: [y]ellow [b]lue [g]reen [r]ed blac[k] [w]hite my @colors = qw/y b g r k w/; my $pattern = join '', map{@colors[rand @colors]} 1..4; my @guesses = (); for my $count (1 .. 11) { print "Mastermind!\n"; print "Colors:[y]ellow [b]lue [g]reen [r]ed blac[k] [w]hite\n"; print @guesses; last if $count > 10; chomp(my $guess = <STDIN>); print "$pattern\n" and redo if $guess eq 'showme'; print "Bad Input\n" and redo unless $guess =~ /^[ybgrkw]{4}$/; my $tmp_pat = $pattern; my $right_color = grep { $tmp_pat =~ s/$_// } split //, $guess; my $right_place =()= "$pattern$guess"=~/(.)(?=...\1)/g; $right_color -= $right_place; push @guesses, "$count|$guess|$right_place,$right_color\n"; if ($right_place == 4){ print "You win!\n"; exit; } } print "You lost! Pattern was: $pattern\n";
Update: chipmunk's shortened version of getting the right_place calculation (in his reply below) caused me wonder about other shortcuts for the same calculation -- here is one:
my $right_place =()= "$pattern$guess"=~/(.)(?=...\1)/g;
However, I think we're both crossing the line into obfuscation now rather than simplification. On the other hand, revisiting the code after a little break unveiled a large bug lurking in the code for counting the right colors that aren't in the right place --- the previous code was:
$right_color += $pattern =~ s/([$guess])/$1/g; $right_color -= $right_place;
But that fails to do the right thing under some conditions. I've patched the code above (and thrown in the above shortcut too). But I rather dislike using the tmp variable and destroying it in the grep() call --- I'm sure there's a simpler/cleaner solution but it escapes me at the moment.
In reply to Re: Re: Need help with a Mastermind game
by danger
in thread Need help with a Mastermind game
by PsionicMan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |