def create(self): assert not self.grow assert not self.body assert not self.direction # try to spawn snake at some distance from world's borders distance = settings.INIT_LENGTH + settings.INIT_MIN_DISTANCE_BORDER x = randint(distance, World.SIZE_X - distance) y = randint(distance, World.SIZE_Y - distance) self.direction = self.current_direction = self.DIRECTIONS[randint( 0, 3)] # create snake from tail to head render = [] pos = Position(x, y) for i in range(0, settings.INIT_LENGTH): target = self._world[pos.y][pos.x] if target.char != self.CH_VOID: raise SnakePlacementError( 'Cannot place snake on %r because the position ' 'is occupied by %r', pos, target) if i == 0: char = self.CH_TAIL elif i == settings.INIT_LENGTH - 1: char = self.CH_HEAD else: char = self.CH_BODY self.body.appendleft(pos) render.append(Draw(pos.x, pos.y, char, self.color)) pos = self.next_position() return render
def render_new_snake(self): # try to spawn snake at some distance from world's borders distance = settings.INIT_LENGHT + 2 x = randint(distance, settings.FIELD_SIZE_X - distance) y = randint(distance, settings.FIELD_SIZE_Y - distance) self.direction = self.DIRECTIONS[randint(0, 3)] # create snake from tail to head render = [] pos = Position(x, y) for i in range(0, settings.INIT_LENGHT): self.snake.appendleft(pos) if i == 0: char = self.TAIL_CHAR elif i == settings.INIT_LENGHT - 1: char = self.HEAD_CHAR else: char = self.BODY_CHAR render.append(Draw(pos.x, pos.y, char, self.color)) pos = self.next_position() return render
def next_position(self): # next position of the snake's head return Position(self.snake[0].x + self.direction.xdir, self.snake[0].y + self.direction.ydir)