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

Python贪吃蛇游戏问题:为何食物有时无法被蛇吃掉?

贪吃蛇游戏:紫色食物碰撞检测异常问题

我正在学习Python课程,自行编写了一款贪吃蛇游戏,大部分功能正常,但发现紫色食物有时即使被蛇头直接碰到也不会被吃掉。该情况随机发生,与当前分数无关,希望有经验的开发者帮忙查看代码定位问题,以下是完整代码:

from turtle import Turtle, Screen
import random
import time

class Snake():
    def __init__(self):
        screen.onkeypress(self.look_left, 'a')
        screen.onkeypress(self.look_right, 'd')
        screen.listen()

        self.snake_squares = {
            1: Turtle(),
            2: Turtle(),
            3: Turtle(),
        }

        for square in self.snake_squares:
            self.design_square(self.snake_squares[square])

        self.snake_head = self.snake_squares[1]
        self.look_left()

    def design_square(self, current_square):
        current_square.penup()
        current_square.shape('square')
        current_square.color('white')
        current_square.shapesize(1.00)
        current_square.pensize(1)

    def add_square(self, new_score):
        square_amount = new_score + 3
        self.snake_squares[square_amount] = Turtle()
        self.design_square(self.snake_squares[square_amount])
        self.snake_squares[square_amount].setposition(self.old_position)


    def look_left(self):
        self.snake_head.left(90)

    def look_right(self):
        self.snake_head.right(90)

    def move(self):
        self.old_position = self.snake_head.position()
        self.snake_head.forward(10.00)

        all_square_positions = []

        for square in self.snake_squares:
            if square != 1:
                next_square = self.snake_squares[square]
                new_position = self.old_position
                self.old_position = next_square.position()
                next_square.setposition(new_position)
                all_square_positions.append(new_position)
        return self.snake_head.position(), all_square_positions


    def check_self_hit(self, head_position, tail_positions):
        if head_position in tail_positions:
            return False
        else:
            return True



class Board():
    def __init__(self, height):
        self.score_board = Turtle()
        self.score_board.hideturtle()
        self.score_board.setposition(0, height + 10)
        self.score_board.color('white')
        self.score = 0

    def add_to_score(self, old_score):
        self.score_board.color('black')
        self.score_board.write(arg=f"Score: {self.score}", font=('Arial', 25, "normal"), align='center')
        self.score = old_score + 1
        self.score_board.color('white')
        self.score_board.write(arg=f"Score: {self.score}", font=('Arial', 25, "normal"), align='center')
        return self.score



class Border():
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.positive_borders = [self.width, self.height]
        self.negative_borders = [- self.width, - self.height]


    def check_borders(self, snake_position):
        no_hit = True
        for border in self.positive_borders:
            if snake_position[0] >= border:
                no_hit = False
            elif snake_position[1] >= border:
                no_hit = False
            else:
                pass
        for border in self.negative_borders:
            if snake_position[0] <= border:
                no_hit = False
            elif snake_position[1] <= border:
                no_hit = False
            else:
                pass
        return no_hit


    def print_border(self, width, height):
        line = Turtle()
        line.hideturtle()
        line.setposition(-float(width), -float(height))
        line.shape("circle")
        line.speed('fastest')
        line.color('white')
        for wall in range(4):
            line.forward(800)
            line.left(90)


class Food():
    def __init__(self, width, height):
        self.width = width
        self.height = height

        self.food = Turtle()
        self.food.hideturtle()
        self.food.speed('fastest')
        self.food.penup()
        self.food.pensize(3)
        self.food.shape('circle')
        self.food.color('purple')

    def create_food(self):
        self.food.showturtle()
        self.food.clear()
        return self.random_position()


    def random_position(self):
        x_min = -self.width + 10                #-390
        x_max = self.width - 10                 #390
        y_min = -self.height + 10               #-390
        y_max = self.height - 10                #390

        x = 11
        y = 11
        while x % 10.00 != 0.00:
            x = float(random.randint(x_min, x_max))

        while y % 10.00 != 0.00:
            y = float(random.randint(y_min, y_max))

        self.food.setposition((x, y))

        x += 10.00
        y += 10.00

        all_possible_hits = []
        for hits in range(3):
            all_possible_hits.append((x, y -10.00))
            x -= 10.00

        for hits in range(3):
            all_possible_hits.append((x + 10.00, y))
            y -= 10.00

        return all_possible_hits


    def erase_food(self):
        self.food.hideturtle()


screen = Screen()
screen.tracer(0)
canvas_width = 400
canvas_height = 400
screen.bgcolor("black")
border = Border(canvas_width, canvas_height)
border.print_border(canvas_width, canvas_height)
snake = Snake()
food = Food(canvas_width, canvas_height)

board = Board(canvas_height)
current_score = board.add_to_score(-1)
current_food_positions = food.create_food()
snake_alive = True
screen.update()

snake_path = []
while snake_alive:
    time.sleep(0.03)
    screen.update()
    snake_current_position, all_positions = snake.move()
    snake_path.append(snake_current_position)
    if snake.check_self_hit(snake_current_position, all_positions):
        if border.check_borders(snake_current_position):
            if snake_current_position in current_food_positions:
                current_score = board.add_to_score(current_score)
                snake.add_square(current_score)
                food.erase_food()
                current_food_positions = food.create_food()
                screen.update()
        else:
            snake_alive = False
    else:
        snake_alive = False

screen.exitonclick()

内容的提问来源于stack exchange,提问作者jakob.py

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:01:30