map.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from graphics import *
  2. import time
  3. import numpy as np
  4. import math
  5. class Map:
  6. def __init__(self, width, height, file):
  7. self.width, self.height = width, height
  8. self.circle = []
  9. self.poly = []
  10. with open(file) as f:
  11. for line in f:
  12. line = line.split(" ")
  13. shape = line[0]
  14. info = line[1:-1]
  15. info = filter(lambda a: a != ']' and a != '[', info)
  16. info = np.array(list(info))
  17. info = info.astype(np.float)
  18. if shape == "REC" or shape == "TRIANGLE":
  19. vertices = info.reshape(-1, 2)
  20. self.poly.append(vertices)
  21. elif shape == "CIRCLE":
  22. self.circle.append(info)
  23. def draw(self, win, zoom):
  24. for c in self.circle:
  25. c = c/zoom
  26. circle = Circle(Point(c[0],c[1]), c[2])
  27. circle.setFill("white")
  28. circle.setOutline('white')
  29. circle.draw(win)
  30. for vertices in self.poly:
  31. vertices = vertices/zoom
  32. vertices = list(map(self.__toPoint__, vertices))
  33. poly = Polygon(vertices)
  34. poly.setFill('white')
  35. poly.setOutline('white')
  36. poly.draw(win)
  37. def white(self, x, y):
  38. for c in self.circle:
  39. dx = c[0]-x
  40. dy = c[1]-y
  41. if dx*dx+dy*dy <= c[2]*c[2]:
  42. return True
  43. for vertices in self.poly:
  44. if self.__inside_polygon__(x, y, vertices):
  45. return True
  46. return False
  47. def inside(self, x, y):
  48. if x > self.width or x < 0:
  49. return False
  50. if y > self.height or y < 0:
  51. return False
  52. return True
  53. def __inside_polygon__(self, x, y, points):
  54. """
  55. Return True if a coordinate (x, y) is inside a polygon defined by
  56. a list of verticies [(x1, y1), (x2, x2), ... , (xN, yN)].
  57. Reference: http://www.ariel.com.au/a/python-point-int-poly.html
  58. """
  59. n = len(points)
  60. inside = False
  61. p1x, p1y = points[0]
  62. for i in range(1, n + 1):
  63. p2x, p2y = points[i % n]
  64. if y > min(p1y, p2y):
  65. if y <= max(p1y, p2y):
  66. if x <= max(p1x, p2x):
  67. if p1y != p2y:
  68. xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) + p1x
  69. if p1x == p2x or x <= xinters:
  70. inside = not inside
  71. p1x, p1y = p2x, p2y
  72. return inside
  73. def __toPoint__(self, pair):
  74. return Point(pair[0],pair[1])