使用Python不能创建多个类实例

Dennis Hua
# 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()

我正在尝试创建一个第二类实例,该实例将显示一个红点,但似乎没有出现。第一类实例起作用,并且在显示器上创建了一个蓝点。我做错了什么?

BłażejMichalik

尝试这个:

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

这将获取所有消息并将其从队列中删除。


此外,您的事件循环看起来不对。应该是(在Main):

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章