note
japhy
From a totally raw point of view, I would keep track of "x previous moves" and "current move".
<h3>Warning: Spoiler Code Ahead</h3>
<code>
#!/usr/bin/perl -w
# roshambo
# usage: roshambo [look-behind]
# look-behind number of previous turns AI examines
use strict;
my $look_behind = shift || 10;
my @beat = (1, 2, 0);
my @names = qw( Rock Paper Scissors );
my @chars = qw( R P S );
my (%freq,@last,$uw,$cw,$t);
while (1) {
my $rps;
### UPDATE
### FIXED SELECTION
for my $i (0 .. $#last) {
if (my $c = $freq{"@last[$i .. $#last]"}) {
$rps = $beat[ weighted(@$c) ];
last;
}
}
$rps = int rand 3 if not defined $rps;
print "Rock (1), Paper (2), Scissors (3): ";
chomp(my $user = <STDIN>);
last if !$user or $user > 3;
### UPDATE
### FIXED WEIGHTING
$user--;
for (0 .. $#last) {
$freq{"@last[0 .. $_]"}[$user]++;
}
shift @last if @last == $look_behind;
push @last, $user;
print "$names[$user] vs. $names[$rps] => ";
if ($rps == $user) { $t++; print "tied\n" }
elsif ($rps == $beat[$user]) { $cw++; print "AI wins\n" }
else { $uw++; print "you win\n" }
}
sub weighted {
my ($choice,$sum);
for my $i (0 .. $#_) {
$_[$i] ||= 0;
$choice = $i if rand($sum += $_[$i]) < $_[$i];
}
return $choice;
}
print "You won: $uw\n";
print "AI won: $cw\n";
print "Ties: $t\n\n";
for (sort { length($a) <=> length($b) } keys %freq) {
for (split ' ') { print $chars[$_] }
print " => ( ";
for my $i (0 .. 2) {
print "$chars[$i] = ", $freq{$_}[$i] || 0, ", ";
}
print ")\n";
}
</code>
All that code does is remember what move you made when you'd made a certain list of previous moves. It selects a weighted choice. The bottom section is output to show how well the AI did.
<br><br>
<tt><font color="#0000ff">japhy</font></tt> --
<a href="/index.pl?node=japhy&lastnode_id=1072">Perl and Regex Hacker</a>
66499
66499