Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Rock, Paper, Scissors

by japhy (Canon)
on Mar 23, 2001 at 03:20 UTC ( [id://66512]=note: print w/replies, xml ) Need Help??


in reply to Rock, Paper, Scissors

From a totally raw point of view, I would keep track of "x previous moves" and "current move".

Warning: Spoiler Code Ahead

#!/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"; }
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.

japhy -- Perl and Regex Hacker

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://66512]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-03-28 20:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found