【问题标题】:Is there a way to pass a class as an argument in a function without it running the entire class?有没有办法将类作为参数传递给函数而不运行整个类?
【发布时间】:2019-08-18 08:13:40
【问题描述】:

我正在使用 Pygame 尝试将一个类作为参数传递给函数,这样我就可以调用该方法,而不是整个类。每次我通过 class 参数时,它似乎都会运行该类,并且由于它处于循环状态,因此很快就会将其磨碎。任何人都可以帮忙吗?我的代码结构还好吗?我试图从组中删除雨滴,然后生成一个新行,但现在,只是想办法从组中删除雨滴。谢谢!!!顺便说一句,对 Python 和一般编码(不包括 HTML5 和 CSS3)有点陌生。

我已尝试将类设置为变量 (drop = Droplet()),然后尝试运行要删除的函数。我还尝试将类中的函数设置为方法,但也失败了。我真的很感激任何帮助。谢谢!我对 Stack Overflow 和 Google 进行了详尽的研究。我试过 .kill 和 .remove。

class Droplet(Sprite):
    def __init__(self):
        super(Droplet, self).__init__(rainfall)
        self.screen = screen
        self.screen_rect = screen.get_rect
        self.image = pygame.image.load('images/Glossy_Raindrop.bmp')
        self.rect = self.image.get_rect()
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

    def blitme(self):
        self.screen.blitme(self.image, self.rect)


def dropground(Droplet):
    drop = Droplet()
    screenie = screen.get_rect()
    if not screen.get_rect().contains(drop.rect):
        print("delete")
        drop.kill()


def update_screen(rainfall):
    screen.fill((135, 206, 235))
    print(len(rainfall))
    rain_y_move(Droplet, rainfall)
    dropground(Droplet)
    rainfall.draw(screen)
    pygame.display.flip()

最终我一次产生了大量的雨滴,这减慢了它的速度。我希望它删除组中的雨滴,然后从那里开始并生成一个新行。就像在屏幕上下雨一样。

【问题讨论】:

    标签: python class methods pygame


    【解决方案1】:

    您必须创建一个Droplet 对象并将该对象传递给函数。

    但是,我建议使用pygame.sprite.Group

    Droplet 类中添加一个.update 方法,该方法用于y 运动,并且如果跌落到地面上则“杀死”跌落。传递给Group.update 方法的所有参数都委托给所包含元素的.updtate 方法:

    class Droplet(Sprite):
    
       # [...]
    
       def update(self)
    
           self.rect = self.rect.move(0, speed)           
    
           screenie = screen.get_rect()
           if not screen.get_rect().contains(self.rect):
               print("delete")
               self.kill()    
    

    创建组并附加drop:

    例如

    rainfall = pygame.sprite.Group()
    my_drop = Droplet()
    rainfall.add(my_drop)
    

    Droplet.blitme 可以被删除,因为pygame.sprite.Group 提供了一个.draw 方法,它“blit”组的每个表面——为此,Sprite.rect.image 属性必须是设置。

    def update_screen(rainfall):
        screen.fill((135, 206, 235))
        print(len(rainfall))
    
        rainfall.update();
        rainfall.draw(screen)        
    
        pygame.display.flip()
    
    while run:
    
        update_screen(rainfall)
    

    【讨论】:

    • 我是否将 drop = Droplet() 设为全局变量?
    • 如果不是 screen.get_rect().contains(drop.rect) 怎么会:在雨滴离开屏幕并且可能是 rect 后不成立?
    • 谢谢Rabbid76!你真棒!我赞成你的回答,但我太新了,在这里没有任何意义。但是你有我的感激之情!
    猜你喜欢
    • 2019-07-30
    • 2019-06-28
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2020-06-24
    • 2021-03-23
    相关资源
    最近更新 更多