一.寻路

A_算法Lua实现 - 图1

  1. --3个任务
  2. local class = require "middleclass"
  3. Point = class('Point')
  4. function Point:initialize(x,y)
  5. self.x = x
  6. self.y = y
  7. end
  8. function Point:__tostring()
  9. return 'Point:[' .. tostring(self.x) .. ',' .. tostring(self.y) .. ']'
  10. end
  11. --从图中建造数据模型
  12. aStar = {
  13. --0表示可走
  14. --1表示不可走
  15. {0,0,0,0,0,0,0},
  16. {0,0,0,1,0,0,0},
  17. {0,0,0,1,0,0,0},
  18. {0,0,0,1,0,0,0},
  19. {0,0,0,0,0,0,0},
  20. }
  21. startPoint = Point(3,2)
  22. endPoint = Point(3,6)
  23. local openTab,closeTab = {},{}
  24. function openTab:__tostring()
  25. local ret = ""
  26. for k = 1 ,#self do
  27. ret = ret .. tostring(self[k])
  28. end
  29. return ret
  30. end
  31. setmetatable(openTab,openTab)
  32. function nextPos(aStar,point)
  33. --遍历上下左右添加到开启表
  34. local tmp = {Point(point.x,point.y - 1),Point(point.x,point.y + 1),
  35. Point(point.x - 1 ,point.y ),Point(point.x + 1,point.y)
  36. }
  37. if point.x == endPoint.x and point.y == endPoint.y then
  38. --print("结束")
  39. openTab[#openTab + 1] = point
  40. if #openTab < 10 then
  41. print(openTab)
  42. end
  43. table.remove(openTab)
  44. return
  45. else
  46. for i = 1,4 do
  47. --处于边界内并且可走
  48. if tmp[i].x >= 1 and tmp[i].x <= 5 and tmp[i].y >= 1 and tmp[i].y <= 7 and aStar[tmp[i].x][tmp[i].y] == 0 then
  49. aStar[point.x][point.y] = 1 --当前位置设置不可走
  50. openTab[#openTab + 1] = point
  51. nextPos(aStar,tmp[i]) --选择下一个位置
  52. table.remove(openTab)
  53. aStar[point.x][point.y] = 0
  54. else
  55. -- 不可走的舍弃,裁枝
  56. end
  57. end
  58. end
  59. end
  60. nextPos(aStar,startPoint)