下面是一个基于 Python 的简单贪吃蛇代码:

import pygame
import random

# 初始化游戏
pygame.init()

# 定义窗口大小
window_width = 800
window_height = 600

# 定义蛇身方格大小
block_size = 20

# 定义蛇的速度
snake_speed = 15

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 创建游戏窗口
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇')

# 创建时钟对象
clock = pygame.time.Clock()

# 定义字体
font_style = pygame.font.SysFont(None, 50)

# 定义得分函数
def score(score):
    value = font_style.render('得分:' + str(score), True, black)
    window.blit(value, [0, 0])

# 定义蛇的形状和位置
def snake(block_size, snake_list):
    for x in snake_list:
        pygame.draw.rect(window, black, [x[0], x[1], block_size, block_size])

# 显示游戏结束信息
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    window.blit(mesg, [window_width / 6, window_height / 3])

# 游戏主循环
def game_loop():
    game_over = False
    game_close = False

    # 初始化蛇的位置
    x1 = window_width / 2
    y1 = window_height / 2
    x1_change = 0
    y1_change = 0

    # 初始化蛇的长度和位置列表
    snake_list = []
    snake_length = 1

    # 初始化食物的位置
    foodx = round(random.randrange(0, window_width - block_size) / 20.0) * 20.0
    foody = round(random.randrange(0, window_height - block_size) / 20.0) * 20.0

    # 游戏循环
    while not game_over:

        while game_close == True:
            window.fill(white)
            message('游戏结束!按Q-退出或C-重新开始', red)
            score(snake_length - 1)
            pygame.display.update()

            # 处理按键事件
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        game_loop()

        # 处理按键事件
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -block_size
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = block_size
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -block_size
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = block_size
                    x1_change = 0

        # 判断蛇是否触碰到边界
        if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
            game_close = True

        # 更新蛇的位置
        x1 += x1_change
        y1 += y1_change
        window.fill(white)
        pygame.draw.rect(window, red, [foodx, foody, block_size, block_size])
        snake_head = []
        snake_head.append(x1)
        snake_head.append(y1)
        snake_list.append(snake_head)

        # 如果蛇的长度超过最大长度,则删除最早的位置
        if len(snake_list) > snake_length:
            del snake_list[0]

        # 判断蛇是否触碰到自己的身体
        for x in snake_list[:-1]:
            if x == snake_head:
                game_close = True

        # 绘制蛇和食物
        snake(block_size, snake_list)
        score(snake_length - 1)

        # 更新窗口
        pygame.display.update()

        # 判断蛇是否吃到食物
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, window_width - block_size) / 20.0) * 20.0
            foody = round(random.randrange(0, window_height - block_size) / 20.0) * 20.0
            snake_length += 1

        # 控制蛇的速度
        clock.tick(snake_speed)

    # 退出游戏
    pygame.quit()
    quit()

# 启动游戏
game_loop()

这个代码使用了 Pygame 库来创建游戏窗口、处理按键事件和绘制图形。在游戏循环中,蛇的位置和长度会不断更新,当蛇触碰到边界或自己的身体时,游戏结束。玩家通过按键控制蛇的移动,吃到食物后蛇的长度增加。游戏的得分会显示在窗口左上角。


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

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