import pygame
import random

# 初始化pygame
pygame.init()

# 定义游戏界面
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 定义游戏界面标题
pygame.display.set_caption('贪吃蛇小游戏') 

# 定义颜色
red = pygame.Color(255, 0, 0) # 蛇身
black = pygame.Color(0, 0, 0) # 背景
white = pygame.Color(255, 255, 255) # 文本

# 定义fps(每秒刷新屏幕的次数)
fps = 10
clock = pygame.time.Clock()

# 定义蛇的初始位置
snake_x = 100
snake_y = 100
snake_size = 10

# 定义蛇的移动方向
direction = 'right'

# 定义食物的位置
food_x = random.randint(0, screen_width // 10) * 10
food_y = random.randint(0, screen_height // 10) * 10

# 定义蛇的身体
snake_list = []
snake_length = 1

# 游戏循环
running = True
while running:
    
    # 定义游戏速度
    clock.tick(fps)

    # 定义游戏结束条件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 修改蛇的移动方向
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            direction = 'left'
        elif event.key == pygame.K_RIGHT:
            direction = 'right'
        elif event.key == pygame.K_UP:
            direction = 'up'
        elif event.key == pygame.K_DOWN:
            direction = 'down'

    # 根据方向移动蛇
    if direction == 'left':
        snake_x -= snake_size
    elif direction == 'right':
        snake_x += snake_size
    elif direction == 'up':
        snake_y -= snake_size
    elif direction == 'down':
        snake_y += snake_size

    # 绘制背景
    screen.fill(black)
    
    # 绘制食物
    pygame.draw.rect(screen, red, (food_x, food_y, snake_size, snake_size))
    
    # 当蛇吃到食物时
    if snake_x == food_x and snake_y == food_y:
        food_x = random.randint(0, screen_width // 10) * 10
        food_y = random.randint(0, screen_height // 10) * 10
        snake_length += 1
        
    # 绘制蛇的身体
    head = []
    head.append(snake_x)
    head.append(snake_y)
    snake_list.append(head)
    if len(snake_list) > snake_length:
        del snake_list[0]
    for x, y in snake_list:
        pygame.draw.rect(screen, white, (x, y, snake_size, snake_size))

    # 更新屏幕
    pygame.display.update()

# 关闭pygame
pygame.quit()
贪吃蛇游戏代码 Python 实现

原文地址: https://www.cveoy.top/t/topic/lgJf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录