当前位置:文档之家› 博弈论66个经典例子 python

博弈论66个经典例子 python

博弈论66个经典例子 python
在博弈论中,有许多经典的例子可以用Python来实现。

以下是其中的一些例子:
1. 石头剪刀布游戏:两个玩家依次出手,根据规则判断胜负。

```python
def rock_paper_scissors(player1, player2):
if player1 == player2:
return "Tie"
elif (player1 == "rock" and player2 == "scissors") or (player1 == "scissors" and player2 == "paper") or (player1 == "paper" and player2 == "rock"):
return "Player 1 wins"
else:
return "Player 2 wins"
print(rock_paper_scissors("rock", "scissors")) # 输出 Player 1 wins ```
2. 井字棋游戏:两个玩家轮流在3x3的棋盘上放置棋子,先连成一条线的玩家获胜。

```python
def tic_tac_toe(board):
# 检查行
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != "-":
return board[i][0]
# 检查列
for i in range(3):
if board[0][i] == board[1][i] == board[2][i] != "-":
return board[0][i]
# 检查对角线
if board[0][0] == board[1][1] == board[2][2] != "-":
return board[0][0]
if board[0][2] == board[1][1] == board[2][0] != "-":
return board[0][2]
# 平局
if all(board[i][j] != "-" for i in range(3) for j in range(3)): return "Tie"
# 游戏未结束
return "No winner"
board = [
["X", "-", "O"],
["O", "X", "-"],
["-", "O", "X"]
]
print(tic_tac_toe(board)) # 输出 X
```
3. 囚徒困境:两个囚徒面临合作或背叛的选择,根据选择和对方的选择获得不同的奖励。

```python
def prisoner_dilemma(choice1, choice2):
if choice1 == "cooperate" and choice2 == "cooperate":
return (3, 3)
elif choice1 == "cooperate" and choice2 == "betray":
return (0, 5)
elif choice1 == "betray" and choice2 == "cooperate":
return (5, 0)
elif choice1 == "betray" and choice2 == "betray":
return (1, 1)
print(prisoner_dilemma("cooperate", "betray")) # 输出 (0, 5)
```
这些例子只是博弈论中的一小部分,还有很多其他的经典例子可以用Python来实现。

相关主题