加载内容...
署名-非商业性使用-禁止演绎
LOADING...
正在加载页面资源
LOADING...
正在初始化系统
博弈程序开发涉及数学建模、算法设计和软件工程的综合应用。
纳什均衡是指在一个博弈中,每个参与者的策略都是对其他参与者策略的最优反应。
1import numpy as np
2from scipy.optimize import linprog
3
4def find_nash_equilibrium(payoff_matrix):
5 """
6 求解两人零和博弈的纳什均衡
7
8 Args:
9 payoff_matrix: 支付矩阵 (m x n)
10
11 Returns:
12 (p, q, v): 玩家1策略、玩家2策略、博弈值
13 """
14 m, n = payoff_matrix.shape
15
16 # 转换为线性规划问题
17 c = np.zeros(m + 1)
18 c[0] = -1 # 最大化 v
19
20 A_ub = np.hstack([np.ones((n, 1)), -payoff_matrix.T])
21 b_ub = np.zeros(n)
22
23 A_eq = np.hstack([[0], np.ones(m)]).reshape(1, -1)
24 b_eq = [1]
25
26 bounds = [(0, None)] * (m + 1)
27 bounds[0] = (None, None) # v 无约束
28
29 result = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq, bounds=bounds)
30
31 v = result.x[0]
32 p = result.x[1:]
33
34 return p, v1import math
2import random
3
4class MCTSNode:
5 def __init__(self, state, parent=None, action=None):
6 self.state = state
7 self.parent = parent
8 self.action = action
9 self.children = []
10 self.visits = 0
11 self.wins = 0
12 self.untried_actions = state.get_legal_actions()
13
14 def ucb1(self, exploration=1.414):
15 if self.visits == 0:
16 return float('inf')
17 return (self.wins / self.visits +
18 exploration * math.sqrt(math.log(self.parent.visits) / self.visits))
19
20 def best_child(self):
21 return max(self.children, key=lambda c: c.ucb1())
22
23 def expand(self):
24 action = self.untried_actions.pop()
25 next_state = self.state.apply_action(action)
26 child = MCTSNode(next_state, self, action)
27 self.children.append(child)
28 return child
29
30 def is_fully_expanded(self):
31 return len(self.untried_actions) == 0
32
33 def is_terminal(self):
34 return self.state.is_terminal()
35
36class MCTS:
37 def search(self, root_state, iterations=1000):
38 root = MCTSNode(root_state)
39
40 for _ in range(iterations):
41 node = self._select(root)
42 reward = self._simulate(node.state)
43 self._backpropagate(node, reward)
44
45 return max(root.children, key=lambda c: c.visits).action
46
47 def _select(self, node):
48 while not node.is_terminal():
49 if not node.is_fully_expanded():
50 return node.expand()
51 node = node.best_child()
52 return node
53
54 def _simulate(self, state):
55 while not state.is_terminal():
56 action = random.choice(state.get_legal_actions())
57 state = state.apply_action(action)
58 return state.get_reward()
59
60 def _backpropagate(self, node, reward):
61 while node:
62 node.visits += 1
63 node.wins += reward
64 node = node.parent1博弈引擎
2├── 规则引擎 (Rule Engine)
3│ ├── 状态验证
4│ ├── 合法动作检查
5│ └── 终局判定
6├── 搜索算法 (Search)
7│ ├── Minimax
8│ ├── Alpha-Beta
9│ └── MCTS
10├── 评估函数 (Evaluation)
11│ ├── 特征提取
12│ └── 神经网络评估
13└── 接口层 (API)
14 ├── REST API
15 └── WebSocket