用pygame开发的贪吃蛇小游戏
import pygame
import sys
import random
初始化Pygame
pygame.init()
游戏窗口的宽度和高度
WIDTH, HEIGHT = 400, 400
定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
设置游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
定义贪吃蛇的初始位置
snake_pos = [100, 50]
snake_body = [[100, 50], [90, 50], [80, 50]]
定义食物的初始位置
food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True
定义初始方向
direction = 'RIGHT'
change_to = direction
定义游戏速度(帧数)
FPS = 15
定义得分
score = 0
游戏主循环
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
# 防止贪吃蛇反向移动
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
# 根据方向移动贪吃蛇头部
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# 增加贪吃蛇的长度
snake_body.insert(0, list(snake_pos))
# 如果吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 10
food_spawn = False
else:
snake_body.pop()
if not food_spawn:
food_pos = [random.randrange(1, (WIDTH//10)) * 10, random.randrange(1, (HEIGHT//10)) * 10]
food_spawn = True
screen.fill(BLACK)
for pos in snake_body:
pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, WHITE, pygame.Rect(food_pos[0], food_pos[1], 10, 10))
if (snake_pos[0] < 0 or snake_pos[0] > WIDTH-10 or
snake_pos[1] < 0 or snake_pos[1] > HEIGHT-10):
pygame.quit()
sys.exit()
for block in snake_body[1:]:
if snake_pos[0] == block[0] and snake_pos[1] == block[1]:
pygame.quit()
sys.exit()
pygame.display.flip()
pygame.display.update()
pygame.time.Clock().tick(FPS)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话