You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Pygame贪吃蛇游戏中蛇头禁止向相反方向移动?

解决Pygame贪吃蛇的方向限制问题

要实现蛇头不能反向移动的逻辑(比如向右时不能直接向左转),核心是记录当前移动方向,在处理按键时判断是否为反向操作,仅允许非反向的方向切换。以下是修改后的完整代码及关键说明:

修改后的完整代码

# Snake game.
import pygame
import random

pygame.init()

# Kleur voor slang / food.
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (50, 153, 213)
green = (0, 255, 0)

# Start screen.
win_width = 800
win_height = 600
window_screen = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption('Snake game by Smerfy')

snake_block = 10
snake_speed = 20

clock = pygame.time.Clock()
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)


def your_score(score):
    value = score_font.render(f"Your Score: {score}", True, red)
    window_screen.blit(value, [0, 0])


def snake(snake_blk, snake_list):
    for x in snake_list:
        pygame.draw.rect(window_screen, red, [x[0], x[1], snake_blk, snake_blk])


def message(msg, color):
    msg = font_style.render(msg, True, color)
    msg_rect = msg.get_rect(center=(win_width / 2, win_height / 2))
    window_screen.blit(msg, msg_rect)


def game_loop():
    game_over = False
    game_close = False

    # Start punt snake hoofd x,y.
    x1 = win_width / 2
    y1 = win_height / 2

    x1_change = 0
    y1_change = 0
    # 新增:记录当前移动方向
    current_direction = None

    snake_list = []
    lenght_of_snake = 1

    foodx = round(random.randrange(0, win_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, win_height - snake_block) / 10.0) * 10.0

    while not game_over:

        while game_close:
            window_screen.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            your_score(lenght_of_snake - 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:
                    # 不是向右时才允许切换向左
                    if current_direction != 'RIGHT':
                        x1_change = -snake_block
                        y1_change = 0
                        current_direction = 'LEFT'
                elif event.key == pygame.K_RIGHT:
                    # 不是向左时才允许切换向右
                    if current_direction != 'LEFT':
                        x1_change = snake_block
                        y1_change = 0
                        current_direction = 'RIGHT'
                elif event.key == pygame.K_UP:
                    # 不是向下时才允许切换向上
                    if current_direction != 'DOWN':
                        y1_change = -snake_block
                        x1_change = 0
                        current_direction = 'UP'
                elif event.key == pygame.K_DOWN:
                    # 不是向上时才允许切换向下
                    if current_direction != 'UP':
                        y1_change = snake_block
                        x1_change = 0
                        current_direction = 'DOWN'
        if x1 >= win_width or x1 < 0 or y1 >= win_height or y1 < 0:
            game_close = True

        x1 += x1_change
        y1 += y1_change

        window_screen.fill('black')
        pygame.draw.rect(window_screen, green, [foodx, foody, snake_block, snake_block])
        snake_head = [x1, y1]
        snake_list.append(snake_head)
        if len(snake_list) > lenght_of_snake:
            del snake_list[0]

        for x in snake_list[:-1]:
            if x == snake_head:
                game_close = True

        snake(snake_block, snake_list)
        your_score(lenght_of_snake - 1)

        pygame.display.update()

        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, win_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, win_height - snake_block) / 10.0) * 10.0
            lenght_of_snake += 1
        # Snelheid van de slang.
        clock.tick(snake_speed)
    pygame.quit()
    quit()


game_loop()

关键修改说明

  • 新增current_direction变量,用于记录蛇头当前的移动方向(初始为None,表示未开始移动)
  • 处理每个方向按键时,增加反向判断:比如当前方向是RIGHT时,忽略向左的按键输入,确保蛇不会直接反向移动
  • 每次允许切换方向时,同步更新current_direction的值,保证后续判断准确

内容的提问来源于stack exchange,提问作者starter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:10:39