|
| 1 | +from axelrod.action import Action |
| 2 | +from axelrod.player import Player |
| 3 | + |
| 4 | +C, D = Action.C, Action.D |
| 5 | + |
| 6 | +class AdaptiveCooperator(Player): |
| 7 | + """ |
| 8 | + This is an adaptive strategy where the player starts |
| 9 | + by cooperating, but switches to Tit-For-Tat if the |
| 10 | + opponent's score exceed's its own score. Then, it |
| 11 | + switches to Defector if the opponent's score is twice |
| 12 | + its own score. |
| 13 | + """ |
| 14 | + |
| 15 | + name = 'Adaptive Cooperator' |
| 16 | + classifier = { |
| 17 | + 'memory': 1, |
| 18 | + 'stochastic': False, |
| 19 | + 'inspects_source': False, |
| 20 | + 'manipulates_source': False, |
| 21 | + 'manipulates_state': False |
| 22 | + } |
| 23 | + |
| 24 | + def __init__(self): |
| 25 | + super().__init__() |
| 26 | + self.is_tft = False |
| 27 | + self.is_defect = False |
| 28 | + self.current_score = 0 |
| 29 | + self.opponent_score = 0 |
| 30 | + |
| 31 | + def _score_last_round(self, opponent): |
| 32 | + game = self.match_attributes["game"] |
| 33 | + last_round = (self.history[-1], opponent.history[-1]) |
| 34 | + scores = game.score(last_round) |
| 35 | + self.current_score += scores[0] |
| 36 | + self.opponent_score += scores[1] |
| 37 | + |
| 38 | + def strategy(self, opponent): |
| 39 | + turn = len(self.history) + 1 |
| 40 | + if turn > 1: |
| 41 | + self._score_last_round(opponent) |
| 42 | + |
| 43 | + if self.opponent_score > self.current_score * 2: |
| 44 | + self.is_defect = True |
| 45 | + elif self.opponent_score > self.current_score: |
| 46 | + self.is_tft = True |
| 47 | + |
| 48 | + #response to strategies |
| 49 | + if self.is_defect: |
| 50 | + return D |
| 51 | + elif self.is_tft: |
| 52 | + if not opponent.history or len(self.history) == 0: |
| 53 | + return C |
| 54 | + else: |
| 55 | + return opponent.history[-1] |
| 56 | + else: #cooperate |
| 57 | + return C |
| 58 | + |
| 59 | + def reset(self): |
| 60 | + super().__init__() |
| 61 | + self.is_defect = False |
| 62 | + self.is_tft = False |
| 63 | + |
0 commit comments