囚徒困境合作、背叛、以牙还牙、随机python代码
时间: 2023-07-10 16:39:23 浏览: 223
下面是一个实现囚徒困境合作、背叛、以牙还牙和随机策略的 Python 代码示例:
```python
import random
# 策略:合作
def cooperate(last_opponent_action):
return 'cooperate'
# 策略:背叛
def defect(last_opponent_action):
return 'defect'
# 策略:以牙还牙
def tit_for_tat(last_opponent_action):
if last_opponent_action == 'cooperate':
return 'cooperate'
else:
return 'defect'
# 策略:随机
def random_choice(last_opponent_action):
return random.choice(['cooperate', 'defect'])
# 主函数
def play_game(player1, player2, num_rounds):
p1_cooperated = True
p2_cooperated = True
p1_score = 0
p2_score = 0
for i in range(num_rounds):
p1_action = player1('cooperate' if p1_cooperated else 'defect')
p2_action = player2('cooperate' if p2_cooperated else 'defect')
if p1_action == 'cooperate' and p2_action == 'cooperate':
p1_score += 3
p2_score += 3
p1_cooperated = True
p2_cooperated = True
elif p1_action == 'cooperate' and p2_action == 'defect':
p1_score += 0
p2_score += 5
p1_cooperated = True
p2_cooperated = False
elif p1_action == 'defect' and p2_action == 'cooperate':
p1_score += 5
p2_score += 0
p1_cooperated = False
p2_cooperated = True
else:
p1_score += 1
p2_score += 1
p1_cooperated = False
p2_cooperated = False
return p1_score, p2_score
# 测试代码
if __name__ == '__main__':
player1 = cooperate
player2 = defect
num_rounds = 5
p1_score, p2_score = play_game(player1, player2, num_rounds)
print(f'Player 1 score: {p1_score}')
print(f'Player 2 score: {p2_score}')
player1 = tit_for_tat
player2 = tit_for_tat
p1_score, p2_score = play_game(player1, player2, num_rounds)
print(f'Player 1 score: {p1_score}')
print(f'Player 2 score: {p2_score}')
player1 = random_choice
player2 = random_choice
p1_score, p2_score = play_game(player1, player2, num_rounds)
print(f'Player 1 score: {p1_score}')
print(f'Player 2 score: {p2_score}')
```
这个代码实现了一个囚徒困境游戏,其中有四种不同的策略:合作、背叛、以牙还牙和随机。在每一轮中,两个玩家都会根据它们的策略来做出决策,然后根据它们的决策来更新分数和合作状态。最后,输出两个玩家的得分。
阅读全文