pygame实现贪吃蛇
时间: 2025-01-13 13:44:59 浏览: 35
### 使用 Pygame 实现贪吃蛇游戏
#### 安装 Pygame 库
为了能够使用 Pygame 开发游戏,首先需要安装该库。可以通过以下命令来完成安装:
```bash
pip install pygame -i https://pypi.tuna.tsinghua.edu.cn/simple
```
这会从清华大学的镜像源下载并安装最新版本的 Pygame[^4]。
#### 初始化 Pygame 和设置窗口
创建一个新的 Python 文件,在文件开头导入必要的模块,并初始化 Pygame 环境以及设定屏幕尺寸等参数:
```python
import sys, time
import random
import pygame
from pygame.locals import *
pygame.init()
fps_clock = pygame.time.Clock()
play_surface = pygame.display.set_mode((720, 460))
pygame.display.set_caption('Snake Game')
```
上述代码片段设置了游戏运行的基础环境,包括帧率控制对象 `fps_clock` 及显示表面 `play_surface` 的定义[^1]。
#### 定义颜色变量和其他常量
为了让后续编码更加简洁明了,可以提前声明一些常用的颜色值及其他固定数值作为全局变量:
```python
red_color = pygame.Color(255, 0, 0) # 游戏结束时使用的红色
black_color = pygame.Color(0, 0, 0) # 蛇的身体部分采用黑色
white_color = pygame.Color(255, 255, 255)# 食物位置标记白色方块
green_color = pygame.Color(0, 255, 0)
snake_position = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
food_position = [random.randrange(1, 72)*10, random.randrange(1, 46)*10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
```
这里不仅包含了用于绘制图形的颜色配置,还设定了初始状态下蛇的位置、长度及其移动方向;同时也随机生成了一个食物坐标点等待被吃掉[^3]。
#### 控制逻辑处理函数
编写一个名为 `main()` 的主循环函数用来持续监听键盘输入事件并对相应操作做出反应,比如改变前进路径或是退出程序:
```python
def main():
global change_to
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_RIGHT or event.key == ord('d'):
change_to = 'RIGHT'
if event.key == K_LEFT or event.key == ord('a'):
change_to = 'LEFT'
if event.key == K_UP or event.key == ord('w'):
change_to = 'UP'
if event.key == K_DOWN or event.key == ord('s'):
change_to = 'DOWN'
validate_direction_and_change(direction, change_to)
...
```
此段落展示了如何捕捉用户的按键动作以调整当前运动轨迹的方向。值得注意的是,当检测到关闭窗口请求时,则调用 `pygame.quit()` 方法释放资源后终止整个应用程序进程[^2]。
#### 更新状态与渲染画面
最后一步是在每次迭代过程中更新场景中的各个元素的状态(如蛇身增长与否),并通过绘图指令刷新屏幕上呈现的内容:
```python
...
if snake_position[0] == food_position[0] and snake_position[1] == food_position[1]:
score += 1
food_spawn = False
else:
snake_body.pop()
if not food_spawn:
food_position = [random.randrange(1, 72)*10, random.randrange(1, 46)*10]
food_spawn = True
play_surface.fill(black_color)
for pos in snake_body:
pygame.draw.rect(play_surface, green_color, Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(play_surface, white_color, Rect(food_position[0], food_position[1], 10, 10))
show_score(1, white_color, 'consolas', 20)
pygame.display.flip()
fps_clock.tick(23)
...
def show_score(choice, color, font, size):
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : {0}'.format(score), True, color)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.midtop = (80, 10)
else:
score_rect.midtop = (360, 120)
play_surface.blit(score_surface, score_rect)
```
这段代码实现了碰撞检测机制——判断是否吃到食物从而增加分数;同时负责重置新的食物位置,并且利用矩形填充的方式画出最新的地图布局给玩家查看.
阅读全文
相关推荐












