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



我试图使用乌龟库制作一个乒乓球游戏,但我得到了这个错误:"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(padp1((,";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()函数除了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()

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

相关内容

  • 没有找到相关文章

最新更新