screen.update 返回错误(Python Turtle 模块)

screen.update returning an error (Python Turtle module)

在我的贪吃蛇代码项目中,我需要将跟踪器设置为 0,然后使用更新方法为我的海龟渲染一个类似贪吃蛇游戏的动画。这是我的代码:

# setup screen

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Welcome to the snake game!")
screen.tracer(0)

# create a snake body, aka three white turtles

starting_pos = [(0,0), (-20,0), (-40,0)]

segments = []

for position in starting_pos:

    new_seg = Turtle("square")
    new_seg.color("white")
    new_seg.penup()
    new_seg.goto(position)

    segments.append(new_seg)

# move the snake

game_is_on = True

while game_is_on:
    screen.update()
    time.sleep(0.1)

for seg_num in range(len(segments) - 1, 0, -1):

    new_x = segments[seg_num - 1].xcor
    new_y = segments[seg_num - 1].ycor
    segments[seg_num].goto(new_x, new_y)

这是它给出的错误:

TypeError: unsupported operand type(s) for +: 'method' and 'float'

我该怎么办?

你的直接问题是这两行:

new_x = segments[seg_num - 1].xcor
new_y = segments[seg_num - 1].ycor

xcorycor 是方法,不是属性,因此应该调用:

new_x = segments[seg_num - 1].xcor()
new_y = segments[seg_num - 1].ycor()

但是,仅此修复不会让您的蛇移动,这些部分只会相互堆积。您还需要向前移动头部。下面是我对你的代码的修改,它抛出了 while True:,它在像乌龟这样的 event-driven 世界中没有立足之地:

from turtle import Screen, Turtle

screen = Screen()
screen.setup(width=600, height=600)
screen.title("Welcome to the snake game!")
screen.bgcolor('black')
screen.tracer(0)

# create a snake body, aka three white turtles

starting_pos = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_pos:
    segment = Turtle('square')
    segment.color('white')
    segment.penup()
    segment.goto(position)

    segments.append(segment)

# move the snake

game_is_on = True

def move():
    if game_is_on:
        for seg_num in range(len(segments) - 1, 0, -1):
            new_position = segments[seg_num - 1].position()
            segments[seg_num].goto(new_position)

        segments[0].forward(20)

        screen.update()
        screen.ontimer(move, 100)  # milliseconds

move()

screen.mainloop()