【发布时间】:2013-01-31 19:02:47
【问题描述】:
我不确定标题是否给出了最好的描述。但这是我的问题。 我有一个名为“球”的课程。 每个球都有自己的宽度、半径和颜色。 当我在循环之前添加自己的球时,我的代码运行良好 例如。球1 = 球() .... 球2 = 球() 我正在使用 pygame,我想要的是,每当我按下“空格”时,它都会添加另一个具有自己特征的球。我有它,所以它随机给出宽度、半径和颜色。 这是我的代码:
BLACK = (0,0,0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
fps = 30
color_list = [BLACK, BLUE, GREEN, RED]
col = None
siz = None
wit = None
posx = None
posy = None
ball = None
class Ball:
ballCount = 0
def __init__(self):
Ball.ballCount +=1
self.col = random.choice(color_list)
self.siz = random.randint(20, 80)
self.wit = random.randint(1, 3)
self.posx = random.randint(self.siz, width-self.siz)
self.posy = random.randint(self.siz, height-self.siz)
def blitball(self):
pygame.draw.circle(screen, self.col, (self.posx, self.posy),self.siz, self.wit)
def move(self):
self.posx+=1
ball2 = Ball()
ball1 = Ball()
ball3 = Ball()
while True:
amount = 0
event = pygame.event.poll()
keys = pygame.key.get_pressed()
if event.type == QUIT:
pygame.quit()
sys.exit()
if keys[K_q]:
pygame.quit()
sys.exit()
#############################################################
if keys[K_SPACE]:
eval("ball"+str(Ball.ballCount+1)) = Ball()
#############################################################
screen.fill(WHITE)
for r in range(Ball.ballCount):
amount+=1
eval("ball"+str(amount)).move()
eval("ball"+str(amount)).blitball()
pygame.time.wait(int(1000/fps))
pygame.display.update()
使用了for r in range(Ball.ballCount):,因此我不必为每个球键入函数。这完美地工作。如果您知道更简单的方法,请告诉我。
所以我需要补充的是:
if keys[K_SPACE]:
#add another ball, ball3, ball4,..etc.
如果这意味着更改我的某些代码,请随时告诉我,甚至自己动手。 感谢您提前回复。 (我在标签中有我的问题)
丹尼斯
【问题讨论】:
-
您已经使用过列表,因此您应该了解它们。为什么不也使用它们呢?
-
这里看起来更像是一个设计问题——你试图让 Balls 做两件事——代表一个 Ball 对象,同时跟踪所有其他 ball 对象。如果您将它们作为两个独立的问题处理,您的设计似乎会简单得多;球列表和球本身。
标签: python class object python-3.x pygame