5. Sounds and Sprites¶
# set up the block data structure
player = pygame.Rect(300,100,40,40)
playerImage = pygame.image.load('player.png')
plyaerStretchedImage = pygame.transform.scale(playerImage(40,40))
foodImage = pygame.image.load('cherry.png')
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0,WINDOWWIDTH - 20),random.randint(0,WINDOWHEIGHT - 20),20,20))
Player.png appears in the desired scale
Generate 20 initial cherries randomly
# set up music
pickUpSound = pygame.mixer.Sound('pickup.wav')
pygame.mixer.music.load('background.mid')
pygame.mixer.music.play(-1,0.0)
musicPlaying = True
Use two channels, one for background music and one for each picked cherry
if event.key == ord('m'):
if musicPlaying:
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1,0,0)
musicPlaying = not musicPlaying
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(event.pos[0]-10,event.pos[1] - 10,20,20))
Key ‘m’ pauses or resumes background music and mouse click plants a cherry at clicked position
foodCounter += 1
if foodCounter >= NEWFOOD:
#add new food
foodCounter = 0
foods.append(pygame.Rect(random.randint(0,WINDOWWIDTH-20),random.randint(0,WINDOWHEIGHT - 20),20,20))
Cherries are randomly generated with each pass in the main loop. principal
# check if the block has intersected with any food squares.
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
player = pygame.Rect(player.left,player.top,player.right,player.down)
playerStretchedImage = pygame.transform.scale(player.left,player.top,player.right,player.down)
if musicPlaying:
pickUpSound.play()
# draw the food
for food in foods:
windowSurface.blit(foodImage,food)
Remove “eaten” cherries, of course bulking up!
All blits appear in the update
FPS == Frames Per Second
Variable that controls the mainClock.tick()
The monsters have a minimum and maximum size and their speed is controlled
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
baddieSize = random.randint(BADDIEMINSIZE,BADDIEMAXSIZE)
newBaddie = {'rect':pygame.Rect(random.randint(0,WINDOWWIDTH-baddieSize),0-baddieSize,baddieSize,baddieSize),'speed':random.randint(BADDIEMINSPEED,BADDIEMAXSPEED),'surface':pygame.transform.scale(baddieImage,(baddieSize,baddieSize))}
baddies.append(newBaddie)
You have attempted of activities on this page