'NoneType' 对象没有属性 'ycor'

'NoneType' object has no attribute 'ycor'

我尝试使用 turtle 库制作乒乓球游戏,但出现以下错误: 'NoneType' 对象没有属性 'ycor'。

这是我的代码:

#red, green, blue
import turtle

#Functions
def sprite(animation_speed, shape, color, x, y, size_width, size_height):
 sprite = turtle.Turtle()
 sprite.penup()
 sprite.speed(animation_speed)
 sprite.shape(shape)
 sprite.color(color)
 sprite.goto(x,y)
 sprite.shapesize(stretch_wid = size_height, stretch_len = size_width)

def paddle1Up():
 y = paddle1.ycor()
 y += 5
 paddle1.sety(y)

#Window settings
window = turtle.Screen()
window.title("Pong game")
window.bgcolor("#0096ff")
window.setup(width = 1920, height = 1080)
window.tracer(0)

#Start
paddle1 = sprite(0, "square", "purple", -800, 0, 3, 12)
paddle2 = sprite(0, "square", "purple", 800, 0, 3, 12)
ball = sprite(0, "circle", "white", 0, 0, 3, 3)

#keyboard biding
window.listen()
window.onkeypress(paddle1Up(), "w")

#Main game loop
while True:
 window.update()

错误在这一行:'window.onkeypress(paddle1Up(), "w")'。

此代码中有两个严重错误。首先是将三个变量分配给 sprite() 调用的结果:

paddle1 = sprite(0, "square", "purple", -800, 0, 3, 12)
paddle2 = sprite(0, "square", "purple", 800, 0, 3, 12)
ball = sprite(0, "circle", "white", 0, 0, 3, 3)

但是 sprite() 函数不 return None 之外的任何东西。下一个问题是这个调用不正确:

window.onkeypress(paddle1Up(), "w")

我们应该将函数 paddle1Up 传递给 onkeypress(),而不是调用函数 paddle1Up() 的结果。一个不太严重的问题是您有一个变量和一个函数都称为 sprite。一个危险的做法,避免它。解决上述所有三个问题,我们得到代码:

from turtle import Screen, Turtle

# Functions
def create_sprite(animation_speed, shape, color, x, y, size_width, size_height):
    sprite = Turtle()
    sprite.shape(shape)
    sprite.shapesize(stretch_wid=size_height, stretch_len=size_width)
    sprite.speed(animation_speed)
    sprite.color(color)
    sprite.penup()
    sprite.goto(x, y)

    return sprite

def paddle1Up():
    paddle1.sety(paddle1.ycor() + 5)

# Screen settings
screen = Screen()
screen.title("Pong game")
screen.bgcolor('#0096ff')
screen.setup(width=1920, height=1080)
screen.tracer(0)

paddle1 = create_sprite(0, 'square', 'purple', -800, 0, 3, 12)
paddle2 = create_sprite(0, 'square', 'purple', 800, 0, 3, 12)
ball = create_sprite(0, 'circle', 'white', 0, 0, 3, 3)

# keyboard binding
screen.onkeypress(paddle1Up, 'w')
screen.listen()

# Main game loop
while True:
    screen.update()

这基本上完成了您打算做的事情,但仍有一个问题可能会在您扩展此代码时成为问题。