Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132930 views
License: OTHER
1
class Match():
2
''' Defines a match which takes two rules and facilitates a game of iterated
3
prisoner's dilemma between them.
4
'''
5
def __init__(self, ruleA, ruleB, length):
6
''' Init method for Match class.
7
8
ruleA, ruleB: instances of rules
9
length (int): the number of rounds to be played in this match
10
'''
11
12
order = [ruleA, ruleB]
13
self.rule0 = order[0]
14
self.rule0.order = 0
15
16
self.rule1 = order[1]
17
self.rule1.order = 1
18
19
self.round = 0
20
self.length = length
21
self.history = [[],[]]
22
23
self.name = name(self.rule0) + '-' + name(self.rule1)
24
25
def run(self):
26
while True:
27
self.step_round()
28
if self.round >= self.length:
29
break
30
31
def halted_run(self):
32
while True:
33
self.step_round()
34
if self.round >= self.length:
35
break
36
print(self.history)
37
print(self.score())
38
input()
39
40
def step_round(self):
41
''' Runs one round of iterated prisoners dilemma by running the step
42
functions of each rule and adding them to the history, then
43
advancing a round.
44
'''
45
46
action0 = self.rule0.step(self.history, self.round)
47
action1 = self.rule1.step(self.history, self.round)
48
49
if (action0 not in [0, 1]):
50
raise ValueError(name(self.rule0) + 'did not provide a valid action')
51
if (action1 not in [0, 1]):
52
raise ValueError(name(self.rule1) + 'did not provide a valid action')
53
54
self.history[0].append(action0)
55
self.history[1].append(action1)
56
57
self.round += 1
58
59
def score(self):
60
''' Calculate scores for the match based on the history.
61
62
Both cooperate: 3 points for both.
63
One cooperates, one defects: 5 points for the one who defected, 0
64
for the other.
65
Both defect: 1 point for both.
66
'''
67
68
outcome = [[[1,1], [5,0]], [[0,5], [3,3]]]
69
scoring = [0, 0]
70
71
for i in range(len(self.history[0])):
72
round_score = outcome[self.history[0][i]][self.history[1][i]]
73
scoring[0] += round_score[0]
74
scoring[1] += round_score[1]
75
76
return scoring
77
78
def name(rule):
79
n = type(rule).__name__
80
return n
81
82
def print_history(match):
83
print(match.name)
84
for i in range(len(match.history[0])):
85
print(' ' + str(match.history[0][i]) + ' ' + str(match.history[1][i]))
86