def pb2struct(self, framestate, lastaction): obs, _ = framestate self.stepno =…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def pb2struct(self, frame_state, last_action): obs, _ = frame_state self.step_no = obs["frame_state"]["step_no"]
hero = obs["frame_state"]["heroes"][0]
self.cur_pos = (hero["pos"]["x"], hero["pos"]["z"])
# History position
# 历史位置
self.history_pos.append(self.cur_pos)
if len(self.history_pos) > 10:
self.history_pos.pop(0)
# End position
# 终点位置
for organ in obs["frame_state"]["organs"]:
if organ["sub_type"] == 4:
end_pos_dis = RelativeDistance[organ["relative_pos"]["l2_distance"]]
end_pos_dir = RelativeDirection[organ["relative_pos"]["direction"]]
self.end_status = organ["status"] # 保存終點狀態
if organ["status"] != -1:
self.end_pos = (organ["pos"]["x"], organ["pos"]["z"])
self.is_end_pos_found = True
# if end_pos is not found, use relative position to predict end_pos
# 如果终点位置未找到,使用相对位置预测终点位置
elif (not self.is_end_pos_found) and (
self.end_pos is None
or self.step_no % 100 == 0
or self.end_pos_dir != end_pos_dir
or self.end_pos_dis != end_pos_dis
):
distance = end_pos_dis * 20
theta = DirectionAngles[end_pos_dir]
delta_x = distance * math.cos(math.radians(theta))
delta_z = distance * math.sin(math.radians(theta))
self.end_pos = (
max(0, min(128, round(self.cur_pos[0] + delta_x))),
max(0, min(128, round(self.cur_pos[1] + delta_z))),
)
self.end_pos_dir = end_pos_dir
self.end_pos_dis = end_pos_dis
self.last_pos_norm = self.cur_pos_norm
self.cur_pos_norm = norm(self.cur_pos, 128, -128)
self.feature_end_pos = self._get_pos_feature(self.is_end_pos_found, self.cur_pos, self.end_pos)
# History position feature
# 历史位置特征
self.feature_history_pos = self._get_pos_feature(1, self.cur_pos, self.history_pos[0])
# 更新狀態信息用於reward計算
current_end_dist = self.feature_end_pos[-1] if self.end_pos else float('inf')
# 記錄距離變化
if self.last_end_dist is not None:
distance_change = self.last_end_dist - current_end_dist
self.progress_history.append(distance_change)
if len(self.progress_history) > 10:
self.progress_history.pop(0)
self.last_end_dist = current_end_dist
# 追蹤已訪問位置
pos_key = (round(self.cur_pos[0]), round(self.cur_pos[1]))
self.visited_positions.add(pos_key)
# 檢測是否卡住
if len(self.history_pos) >= 3:
recent_pos = self.history_pos[-3:]
if all(np.linalg.norm(np.array(pos) - np.array(self.cur_pos)) < 2 for pos in recent_pos):
self.stuck_counter += 1
else:
self.stuck_counter = 0
self.move_usable = True
# 更新閃現冷卻狀態
if self.flash_cooldown > 0:
self.flash_cooldown -= 1
self.flash_usable = False
else:
self.flash_usable = True
# 如果上一個動作是閃現動作(8-15),啟動冷卻
if last_action >= 8 and last_action <= 15:
self.flash_cooldown = 100 # 根據環境配置設置冷卻時間
self.flash_usable = False
self.last_action = last_action
詳細代碼解釋
這段代碼是一個名為 pb2struct 的方法,屬於某個類(因為有 self 參數)。它的主要功能是將遊戲框架的狀態(frame_state)和上一次的動作(last_action)轉換並處理成智能體(Agent)需要的結構化數據,用於後續的決策、特征提取和獎勵計算。
這段代碼看起來像是針對類似 MOBA 遊戲(例如王者榮耀、英雄聯盟)的強化學習環境設計的。我們逐步拆解每個部分的功能與邏輯。
方法簽名
def pb2struct(self, frame_state, last_action):
self:指向當前對象實例,用於訪問類的屬性。frame_state:遊戲當前幀的狀態(Observation),包含遊戲中的各種信息(比如英雄位置、器官狀態等)。last_action:智能體上一步執行的動作,用於更新內部狀態(比如技能冷卻)。frame_state,獲取基本信息obs, _ = frame_state
self.step_no = obs["frame_state"]["step_no"]
hero = obs["frame_state"]["heroes"][0]
self.cur_pos = (hero["pos"]["x"], hero["pos"]["z"])
功能:
frame_state 解包出 obs(遊戲觀測數據),另一個返回值 _ 暫時忽略。step_no),用於後續邏輯判斷(比如定期更新目標位置)。heroes 列表的第一個英雄,即 heroes[0])。cur_pos),只取 x 和 z 坐標(假設 y 軸是垂直方向,在 2D 遊戲平面中不重要)。遊戲坐標系說明:
(x, y, z) 三維坐標,但平面戰鬥中 y 通常代表高度,所以只用 (x, z) 表示 2D 地圖上的位置。history_pos)self.history_pos.append(self.cur_pos)
if len(self.history_pos) > 10:
self.history_pos.pop(0)
功能:記錄英雄的最近 10 步位置,用於:
feature_history_pos)。實現邏輯:
cur_pos 加入 history_pos 列表。history_pos = [(10, 20), (11, 21), ..., (15, 25)],最新的是 self.cur_pos。end_pos)終點(end_pos)在這裡應該是,比如等。代碼中判斷終點的依據是 。
organ["sub_type"] == 4status != -1)if organ["status"] != -1:
self.end_pos = (organ["pos"]["x"], organ["pos"]["z"])
self.is_end_pos_found = True
功能:
status != -1),直接獲取終點的真實坐標。is_end_pos_found = True,表示已精確找到終點位置。elif (not self.is_end_pos_found) and (
self.end_pos is None
or self.step_no % 100 == 0
or self.end_pos_dir != end_pos_dir
or self.end_pos_dis != end_pos_dis
):
distance = end_pos_dis * 20
theta = DirectionAngles[end_pos_dir]
delta_x = distance * math.cos(math.radians(theta))
delta_z = distance * math.sin(math.radians(theta))
self.end_pos = (
max(0, min(128, round(self.cur_pos[0] + delta_x))),
max(0, min(128, round(self.cur_pos[1] + delta_z))),
)
功能:如果沒看到終點真實位置,則根據相對距離和方向估算終點。
end_pos_dis 和 end_pos_dir 是相對距離和方向枚舉值:
RelativeDistance 枚舉了不同的距離級別(例如近、中、遠)。RelativeDirection 枚舉了方向(例如 0°、45°、90°...)。distance = end_pos_dis * 20:將相對距離轉為遊戲單位(假設每個級別對應 20 單位)。theta = DirectionAngles[end_pos_dir]:把方向枚舉值轉為角度(例如 DirectionAngles[3] 可能對應 135°)。delta_x 和 delta_z:
[
\Delta x = \text{distance} \cdot \cos(\theta), \quad \Delta z = \text{distance} \cdot \sin(\theta)
]self.end_pos = (cur_pos[0] + delta_x, cur_pos[1] + delta_z):預測的終點 = 當前位置 + 位移。max(0, min(128, ...)):限制在地圖範圍內(0 ~ 128),避免坐標越界。什麼時候觸發預測?
self.end_pos is None(從未估算過)。self.step_no % 100 == 0(每 100 步更新一次預測,避免誤差累積)。end_pos_dir 或 end_pos_dis 變化,說明相對位置有更新。self.last_pos_norm = self.cur_pos_norm
self.cur_pos_norm = norm(self.cur_pos, 128, -128)
self.feature_end_pos = self._get_pos_feature(self.is_end_pos_found, self.cur_pos, self.end_pos)
self.feature_history_pos = self._get_pos_feature(1, self.cur_pos, self.history_pos[0])
功能:
cur_pos_norm:將當前位置歸一化到 [-1, 1] 範圍,公式為:
[
\text{norm}(x, 128, -128) = \frac{x - (-128)}{128 - (-128)} \times 2 - 1
]
這樣 x=0 對應 -1,x=128 對應 1。feature_end_pos:調用 _get_pos_feature 方法,生成終點的特征向量,輸入參數為:
is_end_pos_found(是否精確找到終點)。cur_pos(當前位置)。end_pos(終點位置)。feature_history_pos:同樣調用 _get_pos_feature,但:
is_end_pos_found=1(視為精確位置)。cur_pos 和 history_pos[0](最早歷史位置)。_get_pos_feature 大致功能(未展示實現):
current_end_dist = self.feature_end_pos[-1] if self.end_pos else float('inf')
if self.last_end_dist is not None:
distance_change = self.last_end_dist - current_end_dist
self.progress_history.append(distance_change)
if len(self.progress_history) > 10:
self.progress_history.pop(0)
self.last_end_dist = current_end_dist
功能:跟蹤與終點的距離變化,用於設計獎勵函數(reward)。
current_end_dist:取出 feature_end_pos 最後一個值(假設是距離終點的歸一化距離)。
float('inf')。distance_change = self.last_end_dist - current_end_dist。
distance_change > 0,表示靠近終點(獎勵為正)。distance_change < 0,表示遠離終點(獎勵為負)。progress_history,保留最近 10 步的進展,可用於:
visited_positions)pos_key = (round(self.cur_pos[0]), round(self.cur_pos[1]))
self.visited_positions.add(pos_key)
功能:記錄英雄走過的位置,用於:
為什麼四捨五入?
10.00001 和 10.0 其實是同一個格子),統一 round 成整數。stuck_counter)if len(self.history_pos) >= 3:
recent_pos = self.history_pos[-3:]
if all(np.linalg.norm(np.array(pos) - np.array(self.cur_pos)) < 2 for pos in recent_pos):
self.stuck_counter += 1
else:
self.stuck_counter = 0
功能:判斷英雄是否長時間停在原地(卡 bug 或被困)。
recent_pos。cur_pos 的歐氏距離:
np.linalg.norm(pos - cur_pos) < 2 表示移動距離小於 2 單位。stuck_counter += 1(計數器加 1)。後續可以用 stuck_counter 設計獎勵:
stuck_counter > 5 時給予大懲罰,強制智能體離開當前狀態。flash_cooldown)if self.flash_cooldown > 0:
self.flash_cooldown -= 1
self.flash_usable = False
else:
self.flash_usable = True
if last_action >= 8 and last_action <= 15:
self.flash_cooldown = 100
self.flash_usable = False
功能:模擬閃現技能的冷卻機制。
flash_cooldown > 0 時,每幀減 1。flash_usable = False(技能不可用)。flash_cooldown == 0 時,flash_usable = True。8~15 是閃現相關動作):
100 幀(約 6~8 秒,取決於遊戲幀率)。flash_usable = False。這樣設計是為了讓智能體:
self.move_usable = True
self.last_action = last_action
move_usable = True:目前代碼中未看到具體用途,可能與移動操作是否可用有關(比如某些狀態下不能移動)。last_action,為下次調用 pb2struct 時判斷上一步操作。| 模塊 | 功能 |
|---|---|
| 解析遊戲狀態 | 獲取當前步數 step_no、英雄位置 cur_pos |
| 歷史位置管理 | 維護最近 10 步位置,用於檢測卡頓 |
| 終點位置處理 | 若終點可見則直接獲取,否則用相對距離/方向預測 |
| 歸一化與特征提取 | 計算 cur_pos_norm、feature_end_pos、feature_history_pos |
| 距離變化監測 | 跟蹤與終點距離變化,存入 progress_history 用於獎勵計算 |
| 已訪問位置記錄 | visited_positions 集合避免重複探索 |
| 卡頓檢測 | 檢查 history_pos,若 3 步內移動距離 < 2,則 stuck_counter++ |
| 閃現技能狀態更新 | 管理 flash_cooldown,決定 flash_usable |
這段代碼結合了:
最終目的是把原始遊戲數據轉成強化學習智能體能用的結構化信息:
feature_end_pos、feature_history_pos)。stuck_counter、flash_cooldown、progress_history)。這樣,下游的強化學習模型(比如 DQN、PPO)就能基於這些特征做動作決策,並根據獎勵信號優化策略。