def move_down(snake): current_pos = inverse_map_grid(snake[0].pos) new_pos = (current_pos[0], current_pos[1] - 1) snake[-1].pos = map_grid_to_win(new_pos) return snake #################################### ## Need to finish the function below # def eat_apple(win, snake, apple): # for segment in snake: # if segment.pos == apple.pos: # add_segment(win, snake, )
def create_apple(win, square_size, snake): """ Creates an apple at a random place. \n Snake argument transmits snake's current position in order to avoid generating apple at the same position where the snake is. """ apple_pos = (randint(0, 31), randint(0, 31)) while apple_pos in [tuple(seg.pos) for seg in snake]: apple_pos = (randint(0, 31), randint(0, 31)) pos = map_grid_to_win(apple_pos, square_size) apple = visual.Rect(win, size=square_size, pos=pos, fillColor="red") return apple
def create_snake(win, square_size, position=None): """ Creates a snake with the length of one segment at a random place by default. \n The position may optionally be specified with the help of position argument. \n The function returns a snake object embedded in a list since new segments of snake might be added later with the help of add_segment() function. """ if position == None: pos = map_grid_to_win((randint(0, 31), randint(0, 31)), square_size) else: pos = position snake = visual.Rect(win, size=square_size, pos=pos, fillColor="green") return [snake]
def move_left(snake): current_pos = inverse_map_grid(snake[0].pos) new_pos = (current_pos[0] - 1, current_pos[1]) snake[-1].pos = map_grid_to_win(new_pos) return snake
def move_up(snake): current_pos = inverse_map_grid(snake[0].pos) new_pos = (current_pos[0], current_pos[1] + 1) snake[-1].pos = map_grid_to_win(new_pos) return snake