繁体   English   中英

在 python 中使用 for 循环创建多个 class 对象

[英]Creating multiple class objects with a for loop in python

使用 class 时,我无法在屏幕上绘制多条线。 我不想为同一件事制作几个 class 实例,只是希望能够将 append 列在一个列表中并让它下降。 我只设法让一个出现在屏幕上,仅此而已。 任何帮助将不胜感激,谢谢。

import pygame
import random

#Classes
class Drop:
    def __init__(self, window, color, x, y,speed):
        self.x = x
        self.y = y
        self.speed = speed
        self.window = window
        self.color = color
        
    def fall(self):
        self.y = self.y + self.speed
        pygame.draw.line(self.window , self.color ,[ self.x , self.y],[self.x, self.y + 30], 2)
        
        


#functions

        
#Program Loop
def main():
    
    gameExit = True
    
#Making the raindrops
    for i in range(500):
        x = random.randint(10,500)
        y = 1
        uno = Drop(window , purple,x,y,speed)  
        rain.append(uno)
        

        
    while gameExit != False:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = False

        window.fill(white)
        
        uno.fall()
            
        pygame.display.update()
     

#Variables
DISPLAY_HEIGHT = 500
DISPLAY_WIDTH = 800




rain = []

speed = 0.5

purple = (128,0,128)
white = (255,255,255)



#Game init

pygame.init()
window = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
pygame.display.set_caption("Purple Rain")


main()

pygame.quit()

这条线

uno.fall()

应该在for循环中。 外面它将指最后一滴 -> 你只看到一个

正确的代码:

window.fill(white) # screen-cleaning should be done first
for i in range(500):
    x = random.randint(10,500)
    y = 1
    uno = Drop(window , purple,x,y,speed)  
    rain.append(uno) 
    uno.fall() # changed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM