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.
classsaw(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=xself.y=yself.width=widthself.height=heightself.rotateCount=0self.vel=1.4defdraw(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)ifself.rotateCount>=8:# This is what will allow us to animate the sawself.rotateCount=0win.blit(pygame.transform.scale(self.rotate[self.rotateCount//2],(64,64)),(self.x,self.y))# scales our image down to 64x64 before drawingself.rotateCount+=1
Now we can code our spike class.
classspike(saw):# We are inheriting from sawimg=pygame.image.load(os.path.join('images','spike.png'))defdraw(self,win):self.hitbox=(self.x+10,self.y,28,315)# defines the hitboxpygame.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
defredrawWindow():win.blit(bg,(bgX,0))win.blit(bg,(bgX2,0))runner.draw(win)# Loops through all obstaclesforobstacleinobstacles:obstacle.draw(win)pygame.display.update()
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.
ifevent.type==USEREVENT+2:r=random.randrange(0,2)ifr==0:obstacles.append(saw(810,310,64,64))elifr==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.
if obstacle.x < obstacle.width * -1: # If our obstacle is off the screen we will remove it obstacles.pop(obstacles.index(obstacle))
# This should go in the game loop