废话不多说,直接上代码(确保已经安装 pygame)
import pygame
import random
# 基础设置
# 屏幕高度
SCREEN_HEIGHT = 480
# 屏幕宽度
SCREEN_WIDTH = 600
# 小方格大小
GRID_SIZE = 20
# 颜色设置
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# 初始化 Pygame
pygame.init()
# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("贪吃蛇游戏")
# 游戏时钟
clock = pygame.time.Clock()
# 初始蛇的位置和速度
snake_pos = [200, 100]
snake_speed = [0, 0]
# 食物的位置
food_pos = [random.randrange(1, (SCREEN_WIDTH // GRID_SIZE)) * GRID_SIZE,
random.randrange(1, (SCREEN_HEIGHT // GRID_SIZE)) * GRID_SIZE]
# 蛇的身体列表
snake_body = [[snake_pos[0], snake_pos[1]]]
# 游戏结束标志
game_over = False
# 得分
score = 0
def draw_snake(snake_body):
for pos in snake_body:
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
def show_score(score):
font = pygame.font.SysFont(None, 36)
score_text = font.render("Score: " + str(score), 1, WHITE)
screen.blit(score_text, [10, 10])
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_speed[1] != GRID_SIZE:
snake_speed = [0, -GRID_SIZE]
elif event.key == pygame.K_DOWN and snake_speed[1] != -GRID_SIZE:
snake_speed = [0, GRID_SIZE]
elif event.key == pygame.K_LEFT and snake_speed[0] != GRID_SIZE:
snake_speed = [-GRID_SIZE, 0]
elif event.key == pygame.K_RIGHT and snake_speed[0] != -GRID_SIZE:
snake_speed = [GRID_SIZE, 0]
# 根据速度移动蛇头
snake_pos[0] += snake_speed[0]
snake_pos[1] += snake_speed[1]
# 如果蛇头碰到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_pos = [random.randrange(1, (SCREEN_WIDTH // GRID_SIZE)) * GRID_SIZE,
random.randrange(1, (SCREEN_HEIGHT // GRID_SIZE)) * GRID_SIZE]
score += 1
else:
# 移除蛇尾以模拟移动
del snake_body[0]
# 检查是否撞到自己或边界,游戏结束
if [snake_pos[0], snake_pos[1]] in snake_body[1:]:
game_over = True
elif snake_pos[0] < 0 or snake_pos[0] >= SCREEN_WIDTH or snake_pos[1] < 0 or snake_pos[1] >= SCREEN_HEIGHT:
game_over = True
# 添加新的蛇头位置
snake_body.append(list(snake_pos))
# 绘制背景
screen.fill(BLACK)
# 绘制食物
pygame.draw.rect(screen, WHITE, [food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE])
# 绘制蛇
draw_snake(snake_body)
# 显示得分
show_score(score)
# 刷新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(10)
# 退出游戏
pygame.quit()
# 文字描述 主要功能技术
"""
food_pos = [random.randrange(1, (SCREEN_WIDTH // GRID_SIZE)) * GRID_SIZE,
random.randrange(1, (SCREEN_HEIGHT // GRID_SIZE)) * GRID_SIZE]
GRID_SIZE 是单元格的大小
(SCREEN_WIDTH // GRID_SIZE)) * GRID_SIZE 先对宽度除以单元格取整取得整个宽度的单元格个数
pygame.draw.rect(screen, GREEN, [pos[0], pos[1], GRID_SIZE, GRID_SIZE])
画矩形,在屏幕,用什么颜色,在什么位置
snake_body.append(list(snake_pos))
增加长度
pygame.display.flip()
刷新屏幕
pygame.draw.rect(screen, WHITE, [food_pos[0], food_pos[1], GRID_SIZE, GRID_SIZE])
控制食物出现位置
"""