python贪吃蛇
jackwsd 人气:0紧接上回,已经完成了单独的贪食蛇的控制,但是呢,居然没有苹果可以吃,所以,非常简单的加入苹果,同时呢,修改一下主程序中贪食蛇的创建,单独编写一个贪食蛇身体生成函数,这样将来要做双蛇也很简单了。
#创建一条新的蛇 def create_new_snake(): snake_body = [] snake_x = random.randint(5, rows - 5) snake_y = random.randint(5, columns - 5) snake_body.append([snake_x, snake_y]) snake_body.append([snake_x, snake_y + 1]) snake_body.append([snake_x, snake_y + 2]) return snake_body
把主程序中所有生成新蛇的地方换成
snake = create_new_snake()
创建新苹果,苹果不能出现在蛇的身体里,所以
def create_new_apple(snake_body): apple_in_game = False while not apple_in_game: apple_x = random.randint(0, rows - 1) apple_y = random.randint(0, columns - 1) # print(apple_x, apple_y) if (apple_x, apple_y) not in snake_body: new_apple = pygame.image.load('apple.png') new_apple = pygame.transform.scale(new_apple, (tile_size - 2, tile_size - 2)) apple_x_location = apple_y * tile_size + x_margin/2 apple_y_location = apple_x * tile_size + y_margin/2 display.blit(new_apple, (apple_x_location, apple_y_location)) apple_in_game = True return new_apple, (apple_x, apple_y), apple_x_location, apple_y_location
在主程序中,主循环之前创建一个苹果
if __name__ == '__main__': pygame.init() snake = create_new_snake() # 未按下按键时,默认的初识移动方向 direction = directions[random.randint(0, 3)] # 创建一个小苹果 apple, apple_location, apple_left, apple_top = create_new_apple(snake) # 吃到苹果标志 apple_was_eaten = False
因为蛇与苹果之间有交互关系,如果蛇吃到苹果,那么蛇的身体会增加一格,也就是此次循环不删除列表的最后一个元素,所以定义了一格标志位。
在主循环中,与监测按键平级的地方,放入蛇与苹果关系检查。
if apple_location in snake: apple, apple_location, apple_left, apple_top = create_new_apple(snake) apple_was_eaten = True my_score += 1
无论
加载全部内容