Христо обнови решението на 15.05.2013 14:30 (преди над 11 години)
+class Death(Exception):
+ pass
+
+
+class Vec2D:
+
+ def __init__(self, x_or_pair, y=None):
+ if y is None:
+ self.x = x_or_pair[0]
+ self.y = x_or_pair[1]
+ else:
+ self.x = x_or_pair
+ self.y = y
+
+ def __add__(self, other):
+ return Vec2D(self.x + other.x, self.y + other.y)
+
+ def __sub__(self, other):
+ return Vec2D(self.x - other.x, self.y - other.y)
+
+ def __mul__(self, other):
+ if isinstance(other, Vec2D):
+ return Vec2D(self.x * other.x, self.y * other.y)
+ else:
+ return Vec2D(self.x * other, self.y * other)
+
+ def __iter__(self):
+ yield self.x
+ yield self.y
+
+
+class WorldObject:
+ pass
+
+
+class Food(WorldObject):
+ symbol = ':3'
+
+ def __init__(self, energy=0):
+ self.energy = energy
+
+
+class PythonPart(WorldObject):
+ symbol = '##'
+
+
+class PythonHead(PythonPart):
+ symbol = '@@'
+
+
+class Cell:
+
+ def __init__(self, contents=None):
+ if contents is None or isinstance(contents, WorldObject):
+ self.contents = contents
+ else:
+ raise TypeError
+
+ def __str__(self):
+ if self.contents is None:
+ return '..'
+ else:
+ return self.contents.symbol
+
+ def is_empty(self):
+ return self.contents is None
+
+
+class World:
+
+ def __init__(self, width):
+ self.width = width
+ self.grid = []
+ for row in range(width):
+ self.grid.append([])
+ self.grid[row] = [Cell() for times in range(width)]
+
+ def __len__(self):
+ return self.width
+
+ def __getitem__(self, x):
+ return self.grid[x]
+
+ def __str__(self):
+ print_grid = ''
+ for row in self.grid:
+ for item in row:
+ print_grid += str(item)
+ print_grid += '\n'
+ return print_grid
+
+ def is_valid_move_position(self, move_position):
+ x, y = move_position
+ if (isinstance(self.grid[x][y].contents, PythonPart) or
+ (x < 0 or x > self.width or y < 0 or y > self.width)):
+ return False
+ return True
+
+ def get_cell_value(self, coords):
+ return self.grid[coords.x][coords.y]
+
+
+class Python:
+ UP = Vec2D(0, 1)
+ DOWN = Vec2D(0, -1)
+ LEFT = Vec2D(-1, 0)
+ RIGHT = Vec2D(1, 0)
+
+ def __init__(self, world, coords, size, direction):
+ self.world = world
+ self.coords = coords
+ self.size = size
+ self.direction = direction
+ self.energy = 0
+ self.body = []
+
+ def move(self, direction):
+ if self.direction + direction == Vec2D(0, 0):
+ raise ValueError
+
+ new_coords = self.coords + self.direction
+
+ if self.world.is_valid_move_position(new_coords) is not True:
+ raise Death
+
+ if isinstance(self.world.get_cell_value(new_coords).contents, Food):
+ self.energy += self.world.get_cell_value(
+ new_coords).contents.energy
+ self.size += 1