Trying to make random image blitting at random time in PYGAME

Viewed 78

I have an interesting problem. I need to make such that image must appear every random time in a random place and if it collides with my GAMER it must affect GAMER(some function) with GAMER for exactly 3 sec and disappear and appear after a random time again. . I have an idea but it does not work.(note: this is a part of code i already initialized everythiing)

clock = pygame.time.Clock()  
FPS = 30 
playtime = 0
newtime=random.randint(3,10) 
while mainloop:
    milliseconds = clock.tick(FPS) 
    seconds = milliseconds / 1000.0
    playtime += seconds
    if playtime>=newtime:
    image.draw() 
    newtime=random.randint(2,6) #because next appear time must change 
    if collision(GAMER,image):
       GAMER.do_something()  #how to do it exactly for 3 sec?
       image.far_away() #just dissapear for some time
1 Answers

When you talk about an image, then you talk about a pygame.Surface. A pygame.Surface can be blit() to the display (respectively the Surface which is associated to the window). For instance

screen.blit(image, image_rect)

You cannot move a surface far away. You have to draw the entire scene in every frame and you have to draw (blit) the image on the display surface in every frame. You can change the position of the image. Create a random position when the time span exceeds:

position = random.randint(0, window_height), random.randint(0, window_width)
image_rect = image.get_rect(center = position)

When the player collides with the image, then set compute the time point 3 seconds in the future. Effect the player as long the 3 seconds are not exceeded:

if image_rect.colliderect(GAMER.rect):
    affecttime = playtime + 3

if playtime < affecttime:
    GAMER.do_something()

General process:

clock = pygame.time.Clock()  
FPS = 30 
newtime=random.randint(3,10)
playtime = 0
affecttime = 0

position = random.randint(0, window_height), random.randint(0, window_width)
image_rect = image.get_rect(center = position)

while mainloop:
    milliseconds = clock.tick(FPS)
    seconds = milliseconds / 1000.0
    playtime += seconds

    # handle events (event loop)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            mainloop = False

    if playtime >= newtime:
        newtime = playtime + random.randint(2,6) 
        position = random.randint(0, window_height), random.randint(0, window_width)
        image_rect = image.get_rect(center = position)

    if image_rect.colliderect(GAMER.rect):
        affecttime = playtime + 3
        position = .... # set position far away
        image_rect = image.get_rect(center = position)

    if playtime < affecttime:
        GAMER.do_something()

    # clear dispaly
    scree.fill(0)

    #draw image at the current position
    screen.blit(image, image_rect)

    # update disaply
    pygame.display.update()
Related