不能用Python创建多个类实例

2024-09-25 08:40:03 发布

您现在位置:Python中文网/ 问答频道 /正文

# Creates a Dot Instance.
class Dot(object):
    velx=0
    vely=0
    def __init__(self, xloc=0, yloc=0,color=(0,7,0)):
        self.color=color
        self.xloc=xloc
        self.yloc=xloc

    def entity(self):
     for event in pygame.event.get():
        pygame.draw.rect(gameDisplay, (self.color), (self.xloc,self.yloc, 50, 50))
        pygame.display.update()


GameExit=False

# Main Function
def Main():
    global x,y,gameDisplay
    Red=Dot(50,50,color=(0,0,255))
    Blue=Dot(150,150,color=(255,0,0))
    Red.entity()
    Blue.entity()

    pygame.display.update()
    while not GameExit:
        if GameExit==False:
            pygame.QUIT

Main()

我试图创建第二个类实例,它将显示一个红点,但它似乎没有出现。第一个类实例工作,它在显示器上创建了一个蓝点。我做错了什么?你知道吗


Tags: selfeventfalsemaindefdisplayupdatepygame
1条回答
网友
1楼 · 发布于 2024-09-25 08:40:03

试试这个:

def entity(self):
    pygame.draw.rect(gameDisplay, self.color, (self.xloc, self.yloc, 50, 50))
    pygame.display.update()

在pyGame的在线REPL中查看:https://repl.it/repls/ActiveMisguidedApplescript


这个问题源于.entity()的实现。你知道吗

在代码中:

for event in pygame.event.get():
    ...

只有在队列中有事件的情况下,你才是在画东西。 所以对Red.entity()的调用耗尽了这个队列。对Blue.entity()的调用甚至没有进入前面提到的for循环,因为在那个特定时刻没有什么可以迭代的-pygame.event.get()返回一个空列表。你知道吗


pygame.event.get() docs

This will get all the messages and remove them from the queue.


而且,您的事件循环看起来是错误的。它应该是(在Main):

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

相关问题 更多 >