Advertisement
Ramaraunt1

pygame_pathfinding_algorithims

May 1st, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. import pygame
  2. import math
  3.  
  4. class Node:
  5. def __init__(self):
  6. self.neighbors=[]
  7. self.moveCosts=[]
  8. self.blocked = False
  9. self.cost = None
  10. self.x = 0
  11. self.y = 0
  12. fScore= 0
  13. gScore= 0
  14. moveScore= 0
  15. parent= None
  16. child= None
  17.  
  18. class Grid:
  19. def __init__(self):
  20. self.nodes=[]
  21.  
  22. def returnDistanceBetweenPoints(x1, x2, y1, y2):
  23. return math.sqrt((x1-x2)^2 + (y1-y2)^2)
  24.  
  25. def autoBuildNeighborsLists(grid, min_dist=30):
  26. for node in grid.nodes:
  27. for potential in grid.nodes:
  28. if (potential != node and returnDistanceBetweenPoints(node.x,potential.x,node.y,potential.y) <= min_dist):
  29. node.neighbors.append(potential)
  30. node.moveCosts.append(1)
  31.  
  32. def pathfind(startNode, endNode, nodeSize):
  33. openList = []
  34. openListPriorities = []
  35. closedList = []
  36. curNode = startNode
  37. closedList.append(curNode)
  38. while curNode != endNode:
  39. for neighbor in curNode.neighbors:
  40. if not neighbor.blocked:
  41. if not neighbor in openList:
  42. neighbor.hScore= curNode.hScore + curNode.moveCosts[curNode.neighbors.index(neighbor)]
  43. neighbor.gscore = returnDistanceBetweenPoints(neighbor.x,endNode.x,neighbor.y,endNode.y)/nodeSize
  44. neighbor.mscore = neighbor.hscore + neighbor.gscore
  45. openList.append(neighbor)
  46. openListPriorities.append(neighbor.mscore)
  47. elif curNode.hScore + curNode.moveCosts[curNode.neighbors.index(neighbor)] < neighbor.hscore:
  48. del openListPriorities[openList.index(neighbor)]
  49. openList.remove(neighbor)
  50. neighbor.hscore = curNode.hScore + curNode.moveCosts[curNode.neighbors.index(neighbor)]
  51. neighbor.mscore = neighbor.hscore + neighbor.gscore
  52. if len(openList)==0:
  53. del openList
  54. del closedList
  55. return None
  56. else:
  57. minVal = 9999999999999
  58. minIndex = -1
  59. for index in range(0,len(openListPriorities)-1):
  60. if openListPriorities[index] < minVal:
  61. minIndex = Index
  62. minVal = openListPriorities[index]
  63. del openListPriorities[minIndex]
  64. newNode = openList[minIndex]
  65. openList.remove(newNode)
  66. newNode.parent = curNode
  67. curNode = newNode
  68. closedList.append(curNode)
  69. while curNode != startNode:
  70. curNode.parent.child=cur_node
  71. curNode=curNode.parent
  72. del openList
  73. del closedList
  74. return curNode.child
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement