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

Python Turtle蛇游戏碰撞后蛇无法隐藏的问题求助

Python蛇游戏碰撞时隐藏蛇的解决方案

要实现碰撞后隐藏蛇、只显示GAME OVER和总分,核心是控制游戏状态,在结束时停止绘制蛇并单独渲染结束界面。以下是具体修改方案:

关键修改点

  • 用全局状态变量game_over标记游戏结束,碰撞时设为True。
  • 只有当game_over=False时,才执行蛇的位置更新和绘制操作。
  • 游戏结束时清空屏幕,只显示GAME OVER文本和总分,不再绘制蛇身。

完整修改代码

import pygame
import random

pygame.init()

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

# 屏幕设置
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")

# 游戏参数
block_size = 10
speed = 15

font = pygame.font.SysFont(None, 55)

def message(msg, color):
    screen_text = font.render(msg, True, color)
    screen.blit(screen_text, [width/6, height/3])

def body_collision(snake_list):
    head = snake_list[0]
    for segment in snake_list[1:]:
        if head == segment:
            global game_over
            game_over = True

def gameLoop():
    global game_over
    game_over = False
    game_close = False

    # 蛇的初始位置和移动方向
    x1 = width / 2
    y1 = height / 2
    x1_change = 0
    y1_change = 0

    snake_list = []
    length_of_snake = 1

    # 食物位置
    foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
    foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0

    clock = pygame.time.Clock()

    while not game_over:
        # 重试/退出逻辑(保留原功能)
        while game_close == True:
            screen.fill(black)
            message("You Lost! Press Q-Quit or C-Play Again", red)
            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:
                        gameLoop()

        # 事件处理
        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 and x1_change != block_size:
                    x1_change = -block_size
                    y1_change = 0
                elif event.key == pygame.K_RIGHT and x1_change != -block_size:
                    x1_change = block_size
                    y1_change = 0
                elif event.key == pygame.K_UP and y1_change != block_size:
                    y1_change = -block_size
                    x1_change = 0
                elif event.key == pygame.K_DOWN and y1_change != -block_size:
                    y1_change = block_size
                    x1_change = 0

        # 边界碰撞判断
        if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
            game_over = True

        # 仅游戏未结束时,更新蛇的位置并绘制元素
        if not game_over:
            x1 += x1_change
            y1 += y1_change
            screen.fill(black)
            pygame.draw.rect(screen, 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) > length_of_snake:
                del snake_list[0]

            # 检测身体碰撞
            body_collision(snake_list)

            # 绘制蛇身
            for x in snake_list:
                pygame.draw.rect(screen, green, [x[0], x[1], block_size, block_size])

            # 绘制实时分数
            score_text = font.render(f"Score: {length_of_snake - 1}", True, white)
            screen.blit(score_text, [0, 0])

            pygame.display.update()

            # 吃食物逻辑
            if x1 == foodx and y1 == foody:
                foodx = round(random.randrange(0, width - block_size) / 10.0) * 10.0
                foody = round(random.randrange(0, height - block_size) / 10.0) * 10.0
                length_of_snake += 1

            clock.tick(speed)
        else:
            # 游戏结束:清空屏幕,只显示GAME OVER和总分
            screen.fill(black)
            message(f"GAME OVER! Total Score: {length_of_snake - 1}", red)
            pygame.display.update()
            # 可选:停留2秒后允许退出
            pygame.time.wait(2000)

    pygame.quit()
    quit()

gameLoop()

说明

碰撞触发后,body_collision函数将game_over设为True,游戏进入结束分支。结束分支中不再执行蛇的更新和绘制,仅渲染黑色背景、GAME OVER文本和最终分数,完美实现蛇隐藏的效果。如果你的原代码结构不同,核心逻辑不变:用状态变量控制蛇的绘制开关,结束时单独渲染界面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 16:47:42