Google


Thursday, September 23, 2010

Rock Paper Scissors bot

I read this post http://flowingdata.com/2010/07/30/how-to-win-rock-paper-scissors-every-time/ and wrote some Python code which uses 2 of the hints given in the diagram. This bot will win 57% of the games.

I simulate a human draw using the % given and hence the bot never draws scissors unless it's a response to a 2 in a row from the human player.

#simulate a human player
#and answer with best strategy

import random

games=1000
wins=0
draws=0
hist=[]

def humandraw(hist):
    rand=random.random()
    if rand<.296: d='P'
    elif rand<.296+.354: d='R'
    else: d='S'
    if len(hist)>1:
        if hist[-1]==hist[-2]:
            while d==hist[-1]:
                rand=random.random()
                if rand<.296: d='P'
                elif rand<.296+.354: d='R'
                else: d='S'           
    return d

def winner(p1,p2):
    if p1==p2: win=0
    elif p1=='R' and p2=='S': win=1
    elif p1=='S' and p2=='R': win=2
    elif p1=='P' and p2=='R': win=1
    elif p1=='R' and p2=='P': win=2
    elif p1=='S' and p2=='P': win=1
    elif p1=='P' and p2=='S': win=2
    return win
   
for g in range(games):
    d=humandraw(hist)
    rand=random.random()
    if rand<.5: a='P'
    else: a='R'
    if len(hist)>1:
        if hist[-1]==hist[-2]:
            if hist[-1]=='P': #will draw S or R
                if rand<.5: a='R'
                else: a='P'
            elif hist[-1]=='R': #will draw P or S
                if rand<.5: a='R'
                else: a='S'
            elif hist[-1]=='S': #will draw P or R
                if rand<.5: a='S'
                else: a='P'
    win=winner(a,d)
    #print a,d,win
    if win==1: wins+=1
    elif win==0: draws+=1
    hist.append(d)

print games,wins,draws
print float(wins)/(games-draws)

No comments: