怎么用python做贪吃蛇

 人参与 | 时间:2026-10-17 06:53:45

贪吃蛇的贪吃核心逻辑只有三件事:蛇怎么动、食物怎么出现、贪吃撞了怎么办。贪吃用 Python 写它,贪吃最省事的贪吃路径是 pygame,装一个库就能把这三件事全塞进一个 while 循环里。贪吃别急着写图形界面,贪吃先把蛇当成一串坐标点,贪吃脑子会清楚很多。贪吃

我习惯用列表存蛇身,贪吃snake = [(5,贪吃5), (4,5), (3,5)],索引 0 是贪吃蛇头。每次移动就是贪吃往列表头部插一个新坐标,再把尾巴删掉——如果没吃到食物的贪吃话。吃到食物就只插不删,贪吃蛇自然变长。这个思路比操作像素简单得多。

import pygame, random, sys pygame.init() cell = 20 cols, rows = 30, 20 screen = pygame.display.set_mode((cols*cell, rows*cell)) clock = pygame.time.Clock() snake = [(5,5), (4,5), (3,5)] direction = (1, 0) food = (10, 10) def spawn_food(): while True: pos = (random.randint(0, cols-1), random.randint(0, rows-1)) if pos not in snake: return pos 

方向控制有个坑:不能直接反向。蛇往右走的时候按左键,如果立刻改方向,蛇头会撞上自己的脖子。所以得存一个“待生效方向”,等下一帧再真正切换。

next_dir = direction for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit(); sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_UP and direction != (0,1): next_dir = (0,-1) elif event.key == pygame.K_DOWN and direction != (0,-1): next_dir = (0,1) elif event.key == pygame.K_LEFT and direction != (1,0): next_dir = (-1,0) elif event.key == pygame.K_RIGHT and direction != (-1,0): next_dir = (1,0) direction = next_dir 

主循环里先算新蛇头,再判断边界和自撞。边界处理我偏向“撞墙即死”,比穿墙更有紧张感。自撞判断用 new_head in snake[:-1],排除掉当前尾巴,因为尾巴这一帧会移走。

head = (snake[0][0] + direction[0], snake[0][1] + direction[1]) if (head[0] < 0 or head[0] >= cols or head[1] < 0 or head[1] >= rows or head in snake[:-1]): pygame.quit(); sys.exit() snake.insert(0, head) if head == food: food = spawn_food() else: snake.pop() 

绘制部分没什么好说的,清屏、画食物、遍历蛇身画方块。给蛇头换个颜色,视觉上更容易分辨。速度用 clock.tick(10) 控制,数字越大蛇跑得越快,10 到 15 之间手感比较合适。

screen.fill((30,30,30)) pygame.draw.rect(screen, (200,60,60), (food[0]*cell, food[1]*cell, cell, cell)) for i, seg in enumerate(snake): color = (80,220,120) if i == 0 else (60,180,100) pygame.draw.rect(screen, color, (seg[0]*cell, seg[1]*cell, cell, cell)) pygame.display.flip() clock.tick(12) 

跑起来之后你会发现一个细节:食物可能刷在蛇身上,所以 spawn_food 里那个 while 循环不能省。另外蛇快速连按两个方向键时,next_dir 可能被覆盖两次,导致一帧内转了两次弯。严格来说应该用队列存方向,但休闲玩的话单变量也够用。

整个程序不到 60 行。真正花时间的地方是调手感——速度、格子大小、颜色。pygame 的 Rect 画方块比用图片资源省事,像素风反而更对味。想加分数就在吃到食物时累加一个变量,用 pygame.font 渲染到左上角,十分钟的事。

顶: 61857踩: 95799