Snoop2001
Snoop2001

Reputation: 25

Pygame - Issue with Randomly Generating Sprites

I need help with randomly generating sprites.

The idea is: One head moves down the screen. Once it leaves the screen, a new random head starts moving down the screen. And so on...

I have 4 images I want to randomly select from.

My issue is: the moving "head" image is just a constant flickering cycle of all the heads in the list. The function appears to constantly blit

Here is the relevant code:

ran_head = [head1, head2, head3, head4]

def heads(img, headx, heady):
  gameDisplay.blit(img, (headx, heady))


def game_loop():
  head_width = 150
  head_height = 192
  head_startx = random.randrange(0, (display_width-150))
  head_starty = -200
  head_speed = 5

  heads(random.choice(ran_head), head_startx, head_starty)

  head_starty += head_speed

  if head_starty > display_height:
      head_starty = -200
      head_startx = random.randrange(0, (display_width-140))
      dodged += 1   #add 1 point
      head_speed += 0.5    #increase speed each time by 0.5

Upvotes: 0

Views: 35

Answers (1)

sloth
sloth

Reputation: 101072

You call heads(random.choice(ran_head), head_startx, head_starty) every tick, so every tick you blit a random image. Just call random.choice(ran_head) once before the loop and only when the head moves out of screen, something like this:

ran_head = [head1, head2, head3, head4]
head_img = random.choice(ran_head) # variable to store the currently choosen image

def heads(img, headx, heady):
  gameDisplay.blit(img, (headx, heady))


def game_loop():
  head_width = 150
  head_height = 192
  head_startx = random.randrange(0, (display_width-150))
  head_starty = -200
  head_speed = 5

  heads(head_img , head_startx, head_starty)

  head_starty += head_speed

  if head_starty > display_height:
      head_starty = -200
      head_startx = random.randrange(0, (display_width-140))
      dodged += 1   #add 1 point
      head_speed += 0.5    #increase speed each time by 0.5
      head_img = random.choice(ran_head) # select a new image randomly

Upvotes: 2

Related Questions