python - 如何使用循环创建一个类的随机多个实例?
问题描述
我已经看了一遍,但找不到如何最好地实现我的编程目标。
目前正在为 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 = []
if count == 1000:
balls.append(Ball(your_radius,your_mass,your_color))
稍后您可以通过索引在列表中引用它们:
balls[0].tick()
balls[1].apply_force()
etc.
推荐阅读
- node.js - Nodejs - 错误 [ERR_HTTP_HEADERS_SENT]:在将标头发送到客户端后无法设置标头
- javascript - 如何更新已动态设置属性名称的属性值?
- lua - 如何确定一个数字是否有小数点或浮点数?
- facebook - Facebook Graph API - 如何获取包含作者的视频评论?
- java - 为什么我的 Spring 应用程序使用 @RestController 而不是 @Controller
- javascript - 如何使用 JavaScript 在树中查找节点并获取用于查找或替换该特定对象的路径?
- azure - Azure 应用服务和证书颁发机构
- javascript - 如何修剪/剥离 URL 以获取特定数据?
- ios - 无法在嵌套的 ScrollView 中点击 UIView
- gdprconsentform - 使用 Google 的 Consent SDK 的 Android 应用同意书根本不显示