首页 > 解决方案 > 如何使用循环创建一个类的随机多个实例?

问题描述

我已经看了一遍,但找不到如何最好地实现我的编程目标。

目前正在为 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_1ball_2ball_3

这可能吗?

标签: pythonclasspygame

解决方案


为你的球使用一个列表。

balls = []
if count == 1000:
    balls.append(Ball(your_radius,your_mass,your_color))

稍后您可以通过索引在列表中引用它们:

balls[0].tick()
balls[1].apply_force()
etc.

推荐阅读