1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| HeuristicType = { Manhattan = 1, Euclidean = 2, Diagonal = 3 }
MoveDirection = { FourWay = 1, EightWay = 2 }
function calculateHeuristic(type, a, b) if type == HeuristicType.Manhattan then return math.abs(a.x - b.x) + math.abs(a.y - b.y) elseif type == HeuristicType.Euclidean then return math.sqrt((a.x - b.x)^2 + (a.y - b.y)^2) else return math.max(math.abs(a.x - b.x), math.abs(a.y - b.y)) end end
function aStarSearch(grid, start, goal, heuristicType, moveDirection) local openList = {} local closedSet = {} local directions = {} if moveDirection == MoveDirection.FourWay then directions = { {0,1}, {1,0}, {0,-1}, {-1,0} } else directions = { {0,1}, {1,0}, {0,-1}, {-1,0}, {1,1}, {1,-1}, {-1,1}, {-1,-1} } end table.insert(openList, { x = start.x, y = start.y, g = 0, h = calculateHeuristic(heuristicType, start, goal), f = 0 + calculateHeuristic(heuristicType, start, goal), parent = nil }) while #openList > 0 do table.sort(openList, function(a,b) return a.f < b.f end) local current = table.remove(openList, 1) local key = current.x .. "," .. current.y closedSet[key] = true if current.x == goal.x and current.y == goal.y then local path = {} local node = current while node do table.insert(path, 1, {x=node.x, y=node.y}) node = node.parent end return path end for _, dir in ipairs(directions) do local nx = current.x + dir[1] local ny = current.y + dir[2] local keyNeighbor = nx .. "," .. ny if nx >= 0 and ny >= 0 and nx < #grid and ny < #grid[1] and grid[nx+1][ny+1] == 0 and not closedSet[keyNeighbor] then table.insert(openList, { x = nx, y = ny, g = current.g + 1, h = calculateHeuristic(heuristicType, {x=nx, y=ny}, goal), f = current.g + 1 + calculateHeuristic(heuristicType, {x=nx, y=ny}, goal), parent = current }) end end end return nil end
local grid = { {0, 0, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 1, 1, 0}, {0, 0, 0, 0, 0} }
local start = {x=0, y=0} local goal = {x=4, y=4}
local fourWayPath = aStarSearch(grid, start, goal, HeuristicType.Manhattan, MoveDirection.FourWay) local eightWayPath = aStarSearch(grid, start, goal, HeuristicType.Diagonal, MoveDirection.EightWay)
if fourWayPath then print("4-Direction Path found:") for _, p in ipairs(fourWayPath) do print("(" .. p.x .. ", " .. p.y .. ")") end else print("No 4-Direction path found") end
if eightWayPath then print("8-Direction Path found:") for _, p in ipairs(eightWayPath) do print("(" .. p.x .. ", " .. p.y .. ")") end else print("No 8-Direction path found") end
|