def _add_noise(noise, s1, s2): r = random.random() if r < noise: s1 = flip_action(s1) r = random.random() if r < noise: s2 = flip_action(s2) return s1, s2
def strategy(self, opponent): # Random first move if not self.history: return random_choice() # Act opposite of opponent otherwise return flip_action(opponent.history[-1])
def strategy(self, opponent): # Random first move if not self.history: return random_choice(); # Act opposite of opponent otherwise return flip_action(opponent.history[-1])
def strategy(self, opponent): # Defect on the first move if not opponent.history: return D # Am I TFT? if self.is_TFT: return D if opponent.history[-1:] == [D] else C else: # Did opponent defect? if opponent.history[-1] == D: self.is_TFT = True return C if len(self.history) in [1, 2]: return C # Alternate C and D return flip_action(self.history[-1])
def strategy(self, opponent): round_number = len(self.history) + 1 # According to internet sources, the original implementation defected # on the first two moves. Otherwise it wins (if this code is removed # and the comment restored. # http://www.sci.brooklyn.cuny.edu/~sklar/teaching/f05/alife/notes/azhar-ipd-Oct19th.pdf if self.revised: if round_number == 1: self.move = C return self.move elif not self.revised: if round_number <= 2: self.move = D return self.move # Update various counts if round_number > 2: if self.history[-1] == D: if opponent.history[-1] == C: self.nice2 += 1 self.total_D += 1 self.bad = float(self.nice2) / self.total_D else: if opponent.history[-1] == C: self.nice1 += 1 self.total_C += 1 self.good = float(self.nice1) / self.total_C # Make a decision based on the accrued counts c = 6.0 * self.good - 8.0 * self.bad - 2 alt = 4.0 * self.good - 5.0 * self.bad - 1 if (c >= 0 and c >= alt): self.move = C elif (c >= 0 and c < alt) or (alt >= 0): self.move = flip_action(self.move) else: self.move = D return self.move
def test_flip_action(self): self.assertEqual(flip_action(D), C) self.assertEqual(flip_action(C), D)
def test_flip_action(self): self.assertEqual(flip_action(D), C) self.assertEqual(flip_action(C), D) with self.assertRaises(ValueError): flip_action('R')
def test_flip_action(self): self.assertEqual(flip_action(Actions.D), Actions.C) self.assertEqual(flip_action(Actions.C), Actions.D) with self.assertRaises(ValueError): flip_action('R')