Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Obstacle keeps disappearing after each event tick. I need it to stay on the screen

I’m creating a small game in pygame with obstacles that fall from the top of the screen to the bottom. At each event tick, an obstacle is created. However, at each new tick (1500milliseconds) the current obstacle is removed before it can reach the bottom and a new one is created. I need the obstacles to stay on the screen while new ones are generated.

I’m trying to get this done with classes and functions only.

So I want to create an obstacle_movement() function within the obstacle class.
Can you help please?
My code is below.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import pygame
import sys
from random import randint
from pygame import surface
import time
import os


class obstacle(pygame.sprite.Sprite):
  def __init__(self):
    super().__init__()

    Obstacle_directory = r'C:\\Users\\ctcar\\Documents\\CompSci\\GameDev\\selfgame\\Graphics\\Obstacles'

    obstacle_lst = []
    self.obstacle_frames = []

    for filename in sorted(os.listdir(Obstacle_directory), key = len):
      if filename.endswith('.png'):
        obstacle_lst.append('Graphics/Obstacles/' + filename)
      
    for sprite in obstacle_lst:
      alpha_sprite = pygame.image.load(sprite).convert_alpha()
      self.obstacle_frames.append(alpha_sprite)  

    y_pos = -20
    self.obstacle_idx = 0
    self.frames = self.obstacle_frames
    self.image = self.frames[self.obstacle_idx]
    self.rect = self.image.get_rect(midbottom = (randint(50, 750), y_pos))

  def obstacle_animation(self):
    self.obstacle_idx += 0.1
    if self.obstacle_idx >= len(self.frames):
      self.obstacle_idx = 0
    self.image = self.frames[int(self.obstacle_idx)]

  def update(self):
    self.obstacle_animation()
    self.rect.y += 4



obstacle_group = pygame.sprite.GroupSingle()


obstacle_timer = pygame.USEREVENT + 1
pygame.time.set_timer(obstacle_timer, randint(1000, 1100))

game_active = True
while True: 
  
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()

  if game_active:

    screen.blit(sky_surface,(0,0))
    screen.blit(ground_surface,(100,710))

    if event.type == obstacle_timer:
      obstacle_group.add(obstacle())


    obstacle_group.draw(screen) 
    obstacle_group.update()
          
    pygame.display.update()
    clock.tick(60)




>Solution :

You need to use a pygame.sprite.Group insterad of a pygame.sprite.GroupSingle:

obstacle_group = pygame.sprite.GroupSingle()

obstacle_group = pygame.sprite.Group()

See obstacle_group = pygame.sprite.GroupSingle():

The GroupSingle container only holds a single Sprite. When a new Sprite is added, the old one is removed.


Furthermore, the events must be handled in the event loop:

game_active = True
run = True
while run: 

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

        if game_active:    
            if event.type == obstacle_timer:
                obstacle_group.add(obstacle())

    if game_active:

        screen.blit(sky_surface,(0,0))
        screen.blit(ground_surface,(100,710))
        obstacle_group.draw(screen) 
        obstacle_group.update()
            
    pygame.display.update()
    clock.tick(60)

pygame.quit()
sys.exit()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading