Pygame Rect 类在更改位置值时不支持操作数类型

问题描述 投票:0回答:1

按下 D 键时尝试将屏幕上的矩形 b1 向右移动,但是在尝试更改对象的 x 值时出现类型错误。我确信这与我试图创建的子类错误有关。应用程序启动并在屏幕上显示矩形。一按D键就崩溃了。

代码:

import pygame
print ("Hello world")
pygame.init()
run = True

#Screen
resolutionX = int(1000)
resolutionY = int(1000)
screenColor = (30, 200, 100)
screen = pygame.display.set_mode((resolutionX,resolutionY))
screen.fill(screenColor)

#Classes
class bug(pygame.Rect):
    speed = 5
    left = 500
    top = 500
    width = 10
    height = 10
    bugColor = (64,86,102)
    tetrad = (left,top,width,height)

#Objects
b1 = bug

#Main loop
while run:
    pygame.draw.rect(screen,b1.bugColor,b1.tetrad)

    for event in pygame.event.get():
        key = pygame.key.get_pressed()

        if key[pygame.K_d] == True:
            b1.x += 5

        if event.type == pygame.QUIT:
            run = False

    pygame.display.update()

终端:

pygame 2.5.2 (SDL 2.28.3, Python 3.12.1)Hello from the pygame community. https://www.pygame.org/contribute.htmlHello worldTraceback (most recent call last):File "c:\Users\Matthew\Desktop#Creek.py", line 35, in <module>b1.x += 5TypeError: unsupported operand type(s) for +=: 'getset_descriptor' and 'int'

如果我不使用 bug 类而是这样做。我没有收到任何错误。

player = pygame.Rect(0,0,10,10)
if key[pygame.K_d] == True:
player.x += 5

尽管为了绘制多个对象,我仍然喜欢使用类。

python pygame
1个回答
0
投票

发生错误是因为

b1
是一个类,而不是
bug
类的实例。当您分配
b1 = bug
时,您实际上是将类本身分配给
b1
,而不是类的实例。要解决此问题,您需要创建
bug
类的实例并将其分配给
b1

    class bug(pygame.Rect):
    def __init__(self, left, top, width, height, color):
        super().__init__(left, top, width, height)
        self.speed = 5
        self.bugColor = color

# Objects
b1 = bug(500, 500, 10, 10, (64, 86, 102))
© www.soinside.com 2019 - 2024. All rights reserved.