Random Object Generation

Subscribe to Tech With Tim!


In this game there will be two main obstacles that our player needs to avoid. A saw and a spike.

We will start by creating a class for our saw.

class saw(object):
    rotate = [pygame.image.load(os.path.join('images', 'SAW0.PNG')),pygame.image.load(os.path.join('images', 'SAW1.PNG')),pygame.image.load(os.path.join('images', 'SAW2.PNG')),pygame.image.load(os.path.join('images', 'SAW3.PNG'))]
    def __init__(self,x,y,width,height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.rotateCount = 0
        self.vel = 1.4

    def draw(self,win):
        self.hitbox = (self.x + 10, self.y + 5, self.width - 20, self.height - 5)  # Defines the accurate hitbox for our character 
        pygame.draw.rect(win, (255,0,0), self.hitbox, 2)
        if self.rotateCount >= 8:  # This is what will allow us to animate the saw
            self.rotateCount = 0
        win.blit(pygame.transform.scale(self.rotate[self.rotateCount//2], (64,64)), (self.x,self.y))  # scales our image down to 64x64 before drawing
        self.rotateCount += 1

Now we can code our spike class.

class spike(saw):  # We are inheriting from saw
    img = pygame.image.load(os.path.join('images', 'spike.png'))
    def draw(self,win):
        self.hitbox = (self.x + 10, self.y, 28,315)  # defines the hitbox
        pygame.draw.rect(win, (255,0,0), self.hitbox, 2)
        win.blit(self.img, (self.x,self.y))

Randomly Generating Objects

Now that we've created classes for both of our obstacles we need to create instances of them and draw them to the screen.

We will store all of our objects in a list and loop through the list to draw each one.

obstacles = []
# Should go above game loop

def redrawWindow():
    win.blit(bg, (bgX, 0))
    win.blit(bg, (bgX2,0))
    # Loops through all obstacles
    for obstacle in obstacles:


Now that we have a list storing all of our obstacles we need to populate it. We will need to create another timer event so that each time it is triggered we generate a new obstacle.

pygame.time.set_timer(USEREVENT+2, random.randrange(2000, 3500)) # Will trigger every 2 - 3.5 seconds
# This should go above the game loop

Like before we will check if this event is triggered from inside the game loop. If it is then we randomly decide on which obstacle to append into our list.

if event.type == USEREVENT+2:
    r = random.randrange(0,2)
    if r == 0:
        obstacles.append(saw(810, 310, 64, 64))
    elif r == 1:
        obstacles.append(spike(810, 0, 48, 310))
# This should go in the "for event in pygame.event.get():" loop

Moving The Objects

Now that we've generated our obstacles we need to move them. This is fairly simple and will be done from within the game loop.

 for obstacle in obstacles: 
     obstacle.x -= 1.4
     if obstacle.x < obstacle.width * -1: # If our obstacle is off the screen we will remove it
# This should go in the game loop