1

I'm getting into the pygame module in python and no matter what i search on the internet, i never seem to come to any conclusions for my problem.

In a nutshell, it's a game where you have to avoid or pick objects falling from above (in this case numbers). I randomized the x and y coordinates by using random.randint and then in the main game loop i made them fall by iterating y += 5. This part works, but it only spawns one image and ends there.

This is how the mechanism of the images works in full detail:

#x and y position for the picture

x1 = random.randint(200,1000)
y1 = 10

#randomize images- pick a random image from the /numbers folder
file_path_type = ["./numbers/*png"]
image_pick = glob.glob(random.choice(file_path_type))
random_image = random.choice(image_pick)
random_image_load = pygame.image.load(random_image).convert()

random_image_load = pygame.transform.scale(random_image_load, 60, 60))

Ok and now this is the whole game loop:

running = True
while running:
  clock.tick(40)
  text_surface, rect = game_font.render(num, (0, 0, 0))
  screen.blit(imageoverlay, (0,0))
  screen.fill
  screen.blit(text_surface, (x, y))
  text_score_time, rect = game_font.render(str(score_time), (0, 0, 0))
  screen.blit(text_score_time, (1100, 50))
  score_display, rect = game_font.render('Time:', (255, 0, 0))
  screen.blit(score_display, (975, 50))
  score_time += 1

  #this blits the initial image on the screen, but it only works one time

  screen.blit(random_image_load, (x1, y1))
  y1 += 5

  keys = pygame.key.get_pressed()
  if keys[pygame.K_LEFT]:
    x -= vel
  if keys[pygame.K_RIGHT]:
    x += vel

  if y1>700 and x1-20<x<x1+20:
    print('You collided')
    
  pygame.display.flip()
  pygame.display.update()

  
    
  
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      running = False
    

      pygame.display.update()
      pygame.display.flip()
      

pygame.quit()

Can someone explain how do i keep on spawning game objects (each one with a new set of x and y coordinates that are randomly generated), lets say every second? I tried a couple of methods but they didn't work.

  • I would be helpful if you could edit your question to provide a [mcve]. For the top portion that generates a random image, do you need some logic to call this code again after `y1` is greater than the screen height? Or maybe after some time delay, although you'd need to track the different x and y positions. I recommend using [sprites](http://programarcadegames.com/index.php?chapter=introduction_to_sprites&lang=en) to make your life easier. – import random Mar 17 '22 at 12:56
  • You need a list of objects. – Rabbid76 Mar 17 '22 at 20:24

0 Answers0