📚 The CoCalc Library - books, templates and other resources
License: OTHER
class Match():1''' Defines a match which takes two rules and facilitates a game of iterated2prisoner's dilemma between them.3'''4def __init__(self, ruleA, ruleB, length):5''' Init method for Match class.67ruleA, ruleB: instances of rules8length (int): the number of rounds to be played in this match9'''1011order = [ruleA, ruleB]12self.rule0 = order[0]13self.rule0.order = 01415self.rule1 = order[1]16self.rule1.order = 11718self.round = 019self.length = length20self.history = [[],[]]2122self.name = name(self.rule0) + '-' + name(self.rule1)2324def run(self):25while True:26self.step_round()27if self.round >= self.length:28break2930def halted_run(self):31while True:32self.step_round()33if self.round >= self.length:34break35print(self.history)36print(self.score())37input()3839def step_round(self):40''' Runs one round of iterated prisoners dilemma by running the step41functions of each rule and adding them to the history, then42advancing a round.43'''4445action0 = self.rule0.step(self.history, self.round)46action1 = self.rule1.step(self.history, self.round)4748if (action0 not in [0, 1]):49raise ValueError(name(self.rule0) + 'did not provide a valid action')50if (action1 not in [0, 1]):51raise ValueError(name(self.rule1) + 'did not provide a valid action')5253self.history[0].append(action0)54self.history[1].append(action1)5556self.round += 15758def score(self):59''' Calculate scores for the match based on the history.6061Both cooperate: 3 points for both.62One cooperates, one defects: 5 points for the one who defected, 063for the other.64Both defect: 1 point for both.65'''6667outcome = [[[1,1], [5,0]], [[0,5], [3,3]]]68scoring = [0, 0]6970for i in range(len(self.history[0])):71round_score = outcome[self.history[0][i]][self.history[1][i]]72scoring[0] += round_score[0]73scoring[1] += round_score[1]7475return scoring7677def name(rule):78n = type(rule).__name__79return n8081def print_history(match):82print(match.name)83for i in range(len(match.history[0])):84print(' ' + str(match.history[0][i]) + ' ' + str(match.history[1][i]))8586