如何找到Pacman最近的Ghost坐标?现有代码仅返回单结果求解答
问题分析与解决方案
原代码问题原因
你的代码只返回(0, 10)有两个核心问题:
- 未处理多个最小值:
np.argmin只会返回第一个出现最小值的索引,即使有多个Ghost的索引差等于最小值,也只会取第一个,因此漏掉了(1, 5)。 - 距离逻辑不符合游戏规则(可选):你用一维扁平化数组的索引差判断“最近”,这和Pacman游戏中实际的移动距离(曼哈顿距离,即行差+列差的绝对值)不符。按游戏逻辑,
(1,5)到Pacman(1,2)的距离是3,(0,10)的距离是9,显然前者更近,但一维索引差巧合都是3,导致你误以为两者距离相同。
解决方案
方案1:按游戏逻辑(曼哈顿距离)找最近Ghost
如果要符合Pacman的实际移动规则,用曼哈顿距离计算:
import pandas as pd import numpy as np pacman = [ list(" G"), list(" P G "), list(" G "), list(" G "), list(" G "), ] df = pd.DataFrame(pacman) # 获取Pacman的坐标 p_row, p_col = np.where(df == 'P') p_row, p_col = p_row[0], p_col[0] # 获取所有Ghost的坐标 ghost_coords = list(zip(*np.where(df == 'G'))) # 计算每个Ghost的曼哈顿距离 distances = [abs(r - p_row) + abs(c - p_col) for r, c in ghost_coords] # 筛选出所有距离等于最小距离的Ghost min_distance = min(distances) closest_ghosts = [coord for coord, dist in zip(ghost_coords, distances) if dist == min_distance] print(closest_ghosts) # 输出: [(1, 5), (2, 4)] # 这两个到Pacman的曼哈顿距离都是3
方案2:按一维索引差找所有“最近”Ghost(匹配你的预期)
如果你的需求确实是基于一维索引差来判断,修改代码以获取所有符合条件的坐标:
import pandas as pd import numpy as np pacman = [ list(" G"), list(" P G "), list(" G "), list(" G "), list(" G "), ] df = pd.DataFrame(pacman) data = df.values.flatten() g_indices = np.where(data == 'G')[0] p_index = np.where(data == 'P')[0][0] # 计算所有Ghost与Pacman的索引差绝对值 diffs = np.abs(g_indices - p_index) min_diff = diffs.min() # 获取所有等于最小差的Ghost索引 closest_g_indices = g_indices[diffs == min_diff] # 转换为二维坐标(行=索引//列数,列=索引%列数) closest_coords = [(idx // df.shape[1], idx % df.shape[1]) for idx in closest_g_indices] print(closest_coords) # 输出: [(0, 10), (1, 5)]
内容的提问来源于stack exchange,提问作者VERBOSE
相关产品推荐
相关产品推荐

