#!/usr/bin/perl -w use strict; # Colors: [y]ellow [b]lue [g]reen [r]ed blac[k] [w]hite my $x; my @correctguesses; my @getridofthese; my $y; my $their_guess; my @their_guess; my $guess_count = 0; my $theyre_incorrect = 1; my $number_completely_right; my $number_correct_colour; my @pattern_to_match; my @previous_guesses; my @numbers_to_colours = qw{y b g r k w}; print "\nMastermind!!!\nColors are: [y]ellow [b]lue [g]reen [r]ed blac[k] [w]hite\n"; print "Please guess four pegs\n\n"; #Choose our hidden pegs foreach (0..3) { $pattern_to_match[$_]=$numbers_to_colours[rand 5]; } my $pattern_to_match=join "", @pattern_to_match; #Main loop while ($guess_count <=9 ) { #Set our default variables my @new_pattern_to_match = @pattern_to_match; my $new_pattern_to_match = join "", @pattern_to_match; $number_completely_right = 0; $number_correct_colour = 0; $their_guess = ; chomp $their_guess; #Cheat. Print out answer if they type 'showme' if ($their_guess eq "showme") { print @pattern_to_match; print "\n"; next; } #Check for a proper input an complain if we don't get it. do{print "Incorrect guess. Please enter four letters as described above\n"; next; } unless $their_guess=~ /^([ybgrkw])([ybgrkw])([ybgrkw])([ybgrkw])$/; #Push their guess onto the guess stack $previous_guesses[$guess_count]{guess} = $their_guess; #Check to see if any character of their guess occurs in the correct #answer string. If it does, remove it from the answer string and #move onto the next character of their guess. @their_guess = split //,$their_guess; foreach my $x (@their_guess) { my $z=index($new_pattern_to_match,$x); if (($z+1)) { substr $new_pattern_to_match,$z,1," "; $number_correct_colour++; } } #Now check for each character in it's right place. If it is there, #decrement the right colour, wrong place counter do{$number_completely_right++;$number_correct_colour--;} if $pattern_to_match=~ /$their_guess[0].../; do{$number_completely_right++;$number_correct_colour--;} if $pattern_to_match=~ /.$their_guess[1]../; do{$number_completely_right++;$number_correct_colour--;} if $pattern_to_match=~ /..$their_guess[2]./; do{$number_completely_right++;$number_correct_colour--;} if $pattern_to_match=~ /...$their_guess[3]/; $previous_guesses[$guess_count]{"reply"} = "$number_completely_right, $number_correct_colour"; print "\nMastermind!!!\nColors are: [y]ellow [b]lue [g]reen [r]ed blac[k] [w]hite\n"; for ($x=$guess_count;$x>=0;$x--) { print $x . " | " . $previous_guesses[$x]{"guess"} . " | " . $previous_guesses[$x]{"reply"} . "\n"; } do{print "Yay! You win!\n\n\n";exit;} if ($number_completely_right == 4); $guess_count++; } print "You lost.\n\n\n";