From e7d594fbdb14fbdf51d82c4240309fc0ea6092b7 Mon Sep 17 00:00:00 2001 From: HuangHai <10402852@qq.com> Date: Wed, 2 Apr 2025 11:13:17 +0800 Subject: [PATCH] 'commit' --- AI/Game/map.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/AI/Game/map.py b/AI/Game/map.py index 1cc355e5..2f183294 100644 --- a/AI/Game/map.py +++ b/AI/Game/map.py @@ -73,8 +73,9 @@ class Character: self.grid_y = grid_y # 小人的网格 y 坐标 self.x = grid_x * cell_size + cell_size // 2 # 小人的像素 x 坐标 self.y = grid_y * cell_size + cell_size // 2 # 小人的像素 y 坐标 - self.radius = cell_size // 3 # 小人的半径 + self.radius = cell_size // 3 - 1 # 稍微减小半径,避免卡住 self.speed = 3 # 移动速度 + self.collision_margin = 2 # 碰撞检测的边缘余量,减小这个值可以让小球更容易通过狭窄通道 def move(self, dx, dy): # 计算目标位置 @@ -83,7 +84,13 @@ class Character: # 检测是否与墙壁碰撞 if self.will_collide(new_x, new_y): - return + # 尝试单独移动 X 或 Y 方向 + if dx != 0 and not self.will_collide(new_x, self.y): + new_y = self.y # 只移动 X 方向 + elif dy != 0 and not self.will_collide(self.x, new_y): + new_x = self.x # 只移动 Y 方向 + else: + return # 两个方向都不能移动 # 更新位置 self.x = new_x @@ -92,20 +99,23 @@ class Character: self.grid_y = self.y // cell_size def will_collide(self, x, y): + # 计算碰撞检测的实际半径 + collision_radius = self.radius - self.collision_margin + # 检测小球是否会与墙壁碰撞 # 计算小球边缘的四个点 points = [ - (x - self.radius, y), # 左 - (x + self.radius, y), # 右 - (x, y - self.radius), # 上 - (x, y + self.radius) # 下 + (x - collision_radius, y), # 左 + (x + collision_radius, y), # 右 + (x, y - collision_radius), # 上 + (x, y + collision_radius) # 下 ] # 检测每个点是否在墙壁内 for px, py in points: # 计算点所在的网格位置 - grid_x = px // cell_size - grid_y = py // cell_size + grid_x = int(px // cell_size) + grid_y = int(py // cell_size) # 检测是否超出边界 if grid_x < 0 or grid_x >= grid_width or grid_y < 0 or grid_y >= grid_height: