Гергана обнови решението на 15.05.2013 16:49 (преди над 11 години)
+from collections import deque
+
+class World():
+ def __init__(self, width):
+ self.width = width
+ self.world = [[Cell() for row in range(width)] for col in range(width)]
+
+ def __getitem__(self, item):
+ return self.world[item]
+
+ def __len__(self):
+ return len(self.width)
+
+ def __str__(self): pass
+
+
+
+class Vec2D:
+
+ def __init__(self, x, y):
+ self.x = x
+ 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, s):
+ return Vec2D(self.x * s, self.y * s)
+
+ def __neg__(self):
+ return -1 * self
+
+ def __eq__(self):
+ return -1 * self.x == self.x and -1 * self.y == self.y
+
+
+class Cell:
+ def __init__(self, contents=None):
+ if contents:
+ if isinstance(contents, WorldObject):
+ self.contents = contents
+ self.empty = False
+ else:
+ raise TypeError
+ else:
+ self.contents = '..'
+ self.empty = True
+
+
+ def is_empty(self):
+ return self.empty
+
+
+class WorldObject(): pass
+
+
+class Food(WorldObject):
+
+ def __init__(self, energy):
+ self.energy = energy
+ self.char = ':3'
+
+ def __str__(self):
+ return self.char.__str__()
+
+
+class PythonPart(WorldObject):
+ def __init__(self):
+ self.char = '##'
+
+ def __str__(self):
+ return self.char.__str__()
+
+
+class PythonHead(PythonPart):
+ def __init__(self):
+ self.char = '@@'
+
+ def __str__(self):
+ return self.char.__str__()
+
+
+class Python:
+ x = 0
+ y = 0
+ LEFT = Vec2D(0, -1)
+ RIGHT = Vec2D(0, 1)
+ UP = Vec2D(-1, 0)
+ DOWN = Vec2D(1, 0)
+ p = Vec2D(0, 0)
+
+ def __init__(self, world, coords, size, direction):
+ self.direction = direction
+ self.world = world
+ self.coords = coords
+ self.size = size
+ self.energy = 0
+ self.head = PythonHead()
+ self.world[coords.x][coords.y] = Cell(self.head)
+ self.part = PythonPart()
+ self.segments = deque([])
+ self.make_queue()
+
+
+ def make_queue(self):
+ for tail in range(1, self.size+1):
+ j = self.coords - self.direction * tail
+ x=j.x
+ y=j.y
+ self.world[x][y] = Cell(self.part)
+ self.segments.append(self.world[x][y])
+
+ def move(self, direction):
+ old_head = self.world[self.x][self.y]
+ p = self.coords + direction
+ self.x = p.x
+ self.y = p.y
+ self.coords += direction
+ if isinstance(self.world[self.x][self.y].contents, PythonPart):
+ raise Death
+ elif isinstance(self.world[self.x][self.y].contents, Food):
+ self.energy += self.world[self.x][self.y].contents.energy
+ self.size += 1
+ self.world[self.x][self.y] = Cell(self.head)
+ old_head.contents = self.part
+ self.segments.appendleft(old_head)
+ else:
+ if 0 <= self.x < self.world.width \
+ and 0 <= self.y < self.world.width:
+ self.world[self.x][self.y] = Cell(self.head)
+ old_head.contents = self.part
+ self.segments[self.size - 1].contents = None
+ self.segments.appendleft(old_head)
+ else:
+ raise Death
+
+
+
+
+
+class Death(Exception):
+ pass
+