Виктория обнови решението на 15.05.2013 13:22 (преди почти 12 години)
+class WorldObject():
+ pass
+
+
+class Food(WorldObject):
+ def __init__(self, energy):
+ self.energy = energy
+
+
+class Vec2D:
+ def __init__(self, x, y):
+ self.x = x
+ self.y = y
+
+ def __add__(self, vector):
+ return Vec2D(self.x + vector.x, self.y + vector.y)
+
+ def __sub__(self, vector):
+ return Vec2D(self.x - vector.x, self.y - vector.y)
+
+ def __mul__(self, number):
+ return Vec2D(number*self.x, number*self.y)
+
+ def __neg__(self):
+ return Vec2D(-self.x, -self.y)
+
+ def __iter__(self):
+ yield self.x
+ yield self.y
+
+
+class PythonPart(WorldObject):
+ pass
+
+
+class PythonHead(PythonPart):
+ pass
+
+
+class Death(Exception):
+ pass
+
+
+class Python:
+ LEFT = Vec2D(-1, 0)
+ UP = Vec2D(0, -1)
+ RIGHT = Vec2D(1, 0)
+ DOWN = Vec2D(0, 1)
+ energy = 0
+
+ def __init__(self, world, coords, size, direction):
+ self.world = world
+ self.coords = coords
+ self.size = size
+ self.direction = direction
+ self.world[coords.x][coords.y] = Cell(PythonHead())
+ for i in range(size):
+ coords = coords - direction
+ self.world[coords.x][coords.y] = Cell(PythonPart())
+ self.last_part = coords
+
+ def find_python(self, coords):
+ for direction in [self.LEFT, self.RIGHT, self.UP, self.DOWN]:
+ next = coords + direction
+ if type(self.world[next.x][next.y].contents) == PythonPart:
+ return next
+
+ def move(self, direction):
+ coords = self.coords
+ self.coords = self.coords + direction
+ if not self.world.is_valid_coords(self.coords.x, self.coords.y):
+ raise Death
+ target_cell = self.world[self.coords.x][self.coords.y]
+
+ if target_cell.is_empty():
+ self.world[self.last_part.x][self.last_part.y] = Cell()
+ self.last_part = self.find_python(self.last_part)
+ elif type(target_cell.contents) == Food:
+ self.energy += target_cell.contents.energy
+ else:
+ raise Death
+
+ self.world[self.coords.x][self.coords.y] = Cell(PythonHead())
+ self.world[coords.x][coords.y] = Cell(PythonPart())
+ self.direction = direction
+
+
+class Cell:
+ def __init__(self, *contents):
+ if contents == ():
+ self.contents = None
+ else:
+ self.contents = contents[0]
+ if not isinstance(self.contents, WorldObject):
+ raise TypeError
+
+ def is_empty(self):
+ return not self.contents
+
+
+class World:
+ def __init__(self, width):
+ self.width = width
+ self.world = [[Cell() for i in range(width)] for i in range(width)]
+
+ def is_valid_coords(self, x, y):
+ return 0 <= x <= len(self) and 0 <= y <= len(self)
+
+ def __getitem__(self, index):
+ if index < 0 or index >= self.width:
+ raise IndexError
+ return self.world[index]
+
+
+def len(world):
+ return world.width