-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstrategy.py
76 lines (61 loc) · 2.11 KB
/
strategy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""Module containing Prisoner's Dilemma strategy classes."""
# Standard library modules
import random
# Define the values for cooperation and defection
COOP = False
DEFECT = True
class Player(object):
def __init__(self, strategy):
self.strategy = strategy
self.reset()
def reset(self):
self.total_payoff = 0
self.players_played = []
def move(self, game):
return self.strategy.move(self, game)
def record(self, game):
# Save the opponent for future reference
opponent = game.get_opponent(self)
if opponent not in self.players_played:
self.players_played.append(opponent)
# Add the game score to the total payoff
self.total_payoff += game.payoff_dict[self]
def evolve(self):
# Get the top scoring strategies of all opponents that have previously
# been played.
top_strategies = [self.strategy]
top_payoff = self.total_payoff
for opponent in self.players_played:
payoff = opponent.total_payoff
if payoff > top_payoff:
top_payoff = payoff
top_strategies = [opponent.strategy]
elif payoff == top_payoff:
top_strategies.append(opponent.strategy)
# Randomly "adopt" one of the top strategies
self.strategy = random.choice(top_strategies)
class CDIStrategy(object):
def __init__(self, c=0.5, d=0.5, i=0.5):
self.c = c
self.d = d
self.i = i
self.name = 'CDI (%s/%s/%s)' % (c, d, i)
def move(self, player, game):
# Get the opponent's last move
try:
last_move = game.get_opponent_move(player, -1)
except IndexError:
last_move = None
# Respond to opponent's last move
if last_move is None:
p_defect = self.i
elif last_move == COOP:
p_defect = self.c
elif last_move == DEFECT:
p_defect = self.d
else:
raise ValueError()
if random.uniform(0, 1) < p_defect:
return DEFECT
else:
return COOP