Skip to content

Instantly share code, notes, and snippets.

@kedarbellare
Created July 24, 2012 06:59
Show Gist options
  • Save kedarbellare/3168484 to your computer and use it in GitHub Desktop.
Save kedarbellare/3168484 to your computer and use it in GitHub Desktop.
Rock paper scissors
def match(player1, player2):
moves1 = []
moves2 = []
wins1 = 0
wins2 = 0
for i in xrange(1000):
move1 = player1(moves1, moves2)
move2 = player2(moves2, moves1)
#print move1, move2
moves1.append(move1)
moves2.append(move2)
if winner(move1, move2) == 1:
wins1 += 1
# print "Player 1 wins! (%s vs. %s)" %(move1, move2)
elif winner(move1, move2) == -1:
wins2 += 1
# print "Player 2 wins! (%s vs. %s)" %(move1, move2)
print "%s won %d games and %s won %d games" %(
player1.__name__, wins1, player2.__name__, wins2)
return
def winner(move1, move2):
dict = {'rock': 0, 'paper': 1, 'scissors': 2}
a = dict[move1]
b = dict[move2]
if a == b:
return 0
elif a - b == 1 or a - b == -2:
return 1
else:
return -1
def dumb_player_mirror(my_moves, opp_moves):
if opp_moves:
return opp_moves[-1]
else:
return 'rock'
def dumb_player_next(my_moves, opp_moves):
moves = rps()
i = moves.index(dumb_player_mirror(opp_moves, my_moves))
return moves[(i+1)%3]
def dumb_player_rock(my_moves, opp_moves):
return 'rock'
def dumb_player_paper(my_moves, opp_moves):
return 'paper'
def dumb_player_scissors(my_moves, opp_moves):
return 'scissors'
def random_player1(my_moves, opp_moves):
return random.choice(rps())
## strategies
import random
def rps():
return ['rock', 'paper', 'scissors']
def sample(probs):
cum = 0.0
p = random.random()
cum = 0.0
for i in xrange(len(probs)):
cum += probs[i]
if p < cum: return i
return len(probs)-1
def max_index(probs):
mi = 0
for i in xrange(len(probs)):
if probs[i] > probs[mi]: mi = i
return mi
def history_choice(my_moves, opp_moves):
moves = rps()
all_moves = zip(opp_moves, my_moves)
current = all_moves[-1]
counts = [0.0, 0.0, 0.0]
total = 0
for i in xrange(1, len(all_moves)):
if all_moves[i-1] == current:
total += 1
counts[moves.index(opp_moves[i])] += 1
probs = [(count+1)/(total+3) for count in counts]
return moves[max_index(probs)]
def frequency_choice(my_moves, opp_moves):
moves = rps()
probs = [1.0*(opp_moves.count(move)+1)/(len(opp_moves)+3) for move in moves]
return moves[max_index(probs)]
def random_choice(my_moves, opp_moves):
return random.choice(rps())
def player(my_moves, opp_moves):
moves = rps()
num_moves = len(opp_moves)
if num_moves == 0: his_move = random_choice(my_moves, opp_moves)
elif num_moves <= 5: his_move = frequency_choice(my_moves, opp_moves)
else: his_move = history_choice(my_moves, opp_moves)
i = moves.index(his_move)
return moves[(i+1)%3]
if __name__ == '__main__':
match(dumb_player_next, player)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment