【问题标题】:AttributeError: 'Player' object has no attribute 'rect' (PyGame)AttributeError:“玩家”对象没有属性“矩形”(PyGame)
【发布时间】:2017-01-19 19:39:59
【问题描述】:

我创建了一个名为 Player 的类。我设法在屏幕上显示它(作为桨),但是当我试图移动它时(按键盘上的向下箭头),游戏崩溃,我留下了这个错误:

Traceback(最近一次调用最后一次):文件

“C:/Users/Optimus/Desktop/PongGame.py”,第 37 行,在

player.controlkeys() 文件“C:/Users/Optimus/Desktop/PongGame.py”,第 23 行,在 controlkeys 中

self.rect.move_ip(-50, 0) AttributeError: 'Player' object has no attribute 'rect'

代码(类):

class Player(object):
    def __init__(self):
        self.playerpaddle = pygame.rect.Rect((40,350,35,100))

    def controlkeys(self):
        key = pygame.key.get_pressed()
        if key[pygame.K_DOWN]:
            self.rect.move_ip(-50, 0)

    def draw(self, screen):
        self.draw = pygame.draw.rect(screen, white, self.playerpaddle)

pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

    player = Player()
    player.draw(screen)
    player.controlkeys()
    pygame.display.update()

完整代码:http://pastebin.com/inwVgcsk。 我做错了什么?

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    您的 Player 对象只有一个您定义的属性:playerpaddle。没有元素 rect。但是,请注意 playerpaddleRect 类型。我怀疑你想要的是类似的东西

    self.playerpaddle.move_ip(-50, 0)
    

    您不是在尝试移动特定的矩形——那个对象将具有 Rect 类的属性。

    这对你有好处吗?

    【讨论】:

    • 是的,现在它没有崩溃 :) 不过,矩形不会移动。明天玩 - 谢谢你的帮助。
    • 添加一些很好的跟踪 print 语句来证明您正在执行移动命令?
    • 我放了一些printprint 有效,每次我按住箭头键但矩形仍然不动时,文本都会显示在控制台中。
    • 好的——这就是进展。你还尝试过什么?你能让这个矩形移动吗?你能做任何其他矩形移动吗?还有其他对象吗?您是否可以移动您调用的代码部分?
    猜你喜欢
    • 2020-11-01
    • 2021-06-08
    • 2016-03-10
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多