I'm not sure if the title gave the best description. But this here is my problem. I have a class named 'Ball'. Each ball has its own width, radius and color. My code worked great while I was adding my own balls before the loop eg. ball1 = Ball() .... ball2 = Ball() I'm using pygame and what I want is so that whenever I press 'Space' it adds another ball with it's own characteristics. I have it so that it randomly gives a width, radius and color. Here is my code:
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()
The for r in range(Ball.ballCount): is used so I don't have to type the functions for every ball. This works perfectly. If you know an easier way let me know.
So what I need to add is:
if keys[K_SPACE]:
#add another ball, ball3, ball4,..etc.
If this means changing some of my code please feel free to tell me or even do so yourself. Thanks for the replies in advance. (I HAVE MY PROBLEM WITHIN THE HASHTAGS)
Dennis