囚徒困境python代码
时间: 2023-07-09 16:35:14 浏览: 128
下面是一个简单的囚徒困境的Python代码示例:
```python
# 两个囚徒的策略
def prisoner_1(history):
if not history:
return "C"
elif history[-1] == "C":
return "C"
else:
return "D"
def prisoner_2(history):
if not history:
return "C"
elif history[-1] == "C":
return "D"
else:
return "C"
# 模拟囚徒困境游戏
def play_pd(prisoner_1, prisoner_2, iterations):
history_1 = []
history_2 = []
score_1 = 0
score_2 = 0
# 迭代次数
for i in range(iterations):
move_1 = prisoner_1(history_2)
move_2 = prisoner_2(history_1)
history_1.append(move_1)
history_2.append(move_2)
# 计算分数
if move_1 == "C" and move_2 == "C":
score_1 += 3
score_2 += 3
elif move_1 == "C" and move_2 == "D":
score_1 += 0
score_2 += 5
elif move_1 == "D" and move_2 == "C":
score_1 += 5
score_2 += 0
else:
score_1 += 1
score_2 += 1
return (score_1, score_2)
# 运行游戏
print(play_pd(prisoner_1, prisoner_2, 10))
```
这个代码使用了两个囚徒的策略函数,`prisoner_1` 和 `prisoner_2`,它们分别返回每个囚徒在当前局面下应该采取的策略(合作 "C" 或者背叛 "D")。然后,`play_pd` 函数使用这两个策略函数进行模拟游戏,并返回最终的分数。在这个示例中,我们运行了 10 局游戏并打印了最终分数。
阅读全文