You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4KB

  1. class Grid():
  2. def __init__(self, x, y, initial):
  3. self.x = x
  4. self.y = y
  5. self.initial = initial
  6. self.data = [initial] * x * y
  7. def get(self, x, y):
  8. return self.data[self.x * y + x]
  9. def set(self, x, y, v):
  10. self.data[self.x * y + x] = v
  11. def in_bounds(self, x, y):
  12. return x < self.x and x >= 0 and y < self.y and y >= 0
  13. def __getitem__(self, coord):
  14. (x, y) = coord
  15. return self.get(x, y)
  16. def __setitem__(self, coord, value):
  17. (x, y) = coord
  18. self.set(x, y, value)
  19. def neighbors(self, x, y):
  20. r = []
  21. for direction in [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]:
  22. xc, yc = direction
  23. tx, ty = x + xc, y + yc
  24. if self.in_bounds(tx, ty):
  25. r.append((tx, ty))
  26. return r
  27. def bresenhams(x1, y1, x2, y2):
  28. r = []
  29. dx = abs(x2 - x1)
  30. dy = abs(y2 - y1)
  31. x, y = x1, y1
  32. sx = -1 if x1 > x2 else 1
  33. sy = -1 if y1 > y2 else 1
  34. if dx > dy:
  35. err = dx / 2.0
  36. while x != x2:
  37. r.append((x, y))
  38. err -= dy
  39. if err < 0:
  40. y += sy
  41. err += dx
  42. x += sx
  43. else:
  44. err = dy / 2.0
  45. while y != y2:
  46. r.append((x, y))
  47. err -= dx
  48. if err < 0:
  49. x += sx
  50. err += dy
  51. y += sy
  52. r.append((x, y))
  53. return r