|
- class Grid():
- def __init__(self, x, y, initial):
- self.x = x
- self.y = y
- self.initial = initial
- self.data = [initial] * x * y
-
- def get(self, x, y):
- return self.data[self.x * y + x]
-
- def set(self, x, y, v):
- self.data[self.x * y + x] = v
-
- def in_bounds(self, x, y):
- return x < self.x and x >= 0 and y < self.y and y >= 0
-
- def __getitem__(self, coord):
- (x, y) = coord
- return self.get(x, y)
-
- def __setitem__(self, coord, value):
- (x, y) = coord
- self.set(x, y, value)
-
- def neighbors(self, x, y):
- r = []
- for direction in [(-1, -1), (0, -1), (1, -1), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0)]:
- xc, yc = direction
- tx, ty = x + xc, y + yc
- if self.in_bounds(tx, ty):
- r.append((tx, ty))
- return r
-
- def bresenhams(x1, y1, x2, y2):
- r = []
- dx = abs(x2 - x1)
- dy = abs(y2 - y1)
- x, y = x1, y1
- sx = -1 if x1 > x2 else 1
- sy = -1 if y1 > y2 else 1
- if dx > dy:
- err = dx / 2.0
- while x != x2:
- r.append((x, y))
- err -= dy
- if err < 0:
- y += sy
- err += dx
- x += sx
- else:
- err = dy / 2.0
- while y != y2:
- r.append((x, y))
- err -= dx
- if err < 0:
- x += sx
- err += dy
- y += sy
- r.append((x, y))
- return r
|