python - 如何使用循环创建类的随机多个实例?

标签 python class pygame

我已经查看了所有内容,但找不到如何最好地实现我的编程目标。

目前正在设计 pygame 物理引擎的基础知识。

我希望能够使用我每 10 秒创建的 Ball 类创建一个新球 我需要为这些球编写操作代码,但我需要一种自动创建实例的方法

类代码:

class Ball:
    def __init__(self, radius, mass, colour):
        self.name = self
        self.radius = radius
        self.colour = colour
        self.mass = mass
        self.pos = [50, 50]
        self.vel = [0, 0]
        self.acc = [0, 0]
        self.forces = [0, 0]
        self.on_ground = False

    def get_pos(self):
        return self.pos[0], self.pos[1]

    def tick(self):
        self.forces = [0, GRAVITY]
        Ball.apply_force(self)
        Ball.update_attributes(self)
        pygame.draw.circle(screen, self.colour, (int(self.pos[0]), int(self.pos[1])), self.radius)

    def apply_force(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] == 1 and self.on_ground:
            self.forces[0] -= 0.2
        if keys[pygame.K_RIGHT] == 1 and self.on_ground:
            self.forces[0] += 0.2
        if keys[pygame.K_SPACE] == 1 and self.on_ground:
            self.on_ground = False
            self.forces[1] = -20
        if self.on_ground:
            self.forces[1] = 0
            if self.vel[0] > 0:
                self.forces[0] -= (abs(self.vel[0])) * 0.1
            else:
                self.forces[0] += (abs(self.vel[0])) * 0.1

    def update_attributes(self):
        self.acc = [self.forces[0] / self.mass, self.forces[1] / self.mass]
        self.vel = [self.vel[0] + self.acc[0], self.vel[1] + self.acc[1]]
        if (self.pos[1] + self.vel[1]) > (300-self.radius) and not self.on_ground:
            self.pos[1] = (300 - self.radius)
            self.vel[1] = 0
            self.on_ground = True
        else:
            self.pos[1] += self.vel[1]
        self.pos[0] += self.vel[0]

while 循环:

count = 0
name = ball_1
while running:
    pygame.time.delay(10)
    count += 1
    if count == 1000:
        #create instance here called name

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    blueBall.tick()
    redBall.tick()
    pygame.draw.rect(screen, (0, 200, 0), (0, 300, 1300, 200))
    pygame.display.update()
    screen.fill((100, 100, 255))

我希望能够索引球的名称,以便能够轻松访问它们
例如ball_1 , ball_2 , ball_3

这可能吗?

最佳答案

您可以按照以下方式执行操作:

balls = [Ball(rand_radius, rand_mass, rand_color) for i in range(10)]

关于python - 如何使用循环创建类的随机多个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60118200/

相关文章:

python numpy机器epsilon

python - 当 n 定义为正整数时,为什么 sympy 不计算 sin(n* pi) = 0 和 cos(n * pi) = (-1)^n ?

python - 如何检查 numpy/pandas 对象,即 R 中的 str()

Java 从泛型 Class 对象获取方法

python - Pygame 随机移动敌人

python - 有没有办法在 python 中将 SQL 表用作类或对象?

c++ - 为什么我的类(class)规模为零?如何确保不同的对象具有不同的地址?

Java初学者对构造函数的使用感到困惑

user-interface - 在 pygame 中添加 wxpython

python - 我在哪里可以找到并安装 pygame 的依赖项?