Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
User Interaction: Get into the Game 227

while keep_going:
for event in pygame.event.get():
if event.type == pygame.QUIT:
keep_going = False
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]: # Regular left mouse button, draw
mousedown = True
elif pygame.mouse.get_pressed()[2]: # Right mouse button, pop
pos = pygame.mouse.get_pos()
clicked_smileys = [s for s in sprite_list if s.rect.collidepoint(pos)]
sprite_list.remove(clicked_smileys)
if event.type == pygame.MOUSEBUTTONUP:
mousedown = False
screen.fill(BLACK)
sprite_list.update()
sprite_list.draw(screen)
clock.tick(60)
pygame.display.update()
if mousedown:
speedx = random.randint(-5, 5)
speedy = random.randint(-5, 5)
newSmiley = Smiley(pygame.mouse.get_pos(),speedx,speedy)
sprite_list.add(newSmiley)


pygame.quit()


Remember that you’ll have to have the CrazySmile.bmp image
file stored in the same folder or directory as the code to make it
work. Once it does work, this program is so much fun to play with,
it’s almost addictive! In the next chapter, we’ll learn about the
elements of game design that make games fun, and we’ll build a
complete game from scratch!

What You Learned


In this chapter, we combined user interaction with animation to
create an explosion of smileys on the screen, and we used sprite
graphics to make even hundreds of smiley images easy and fast to
animate. We learned how to build our own Sprite class so that we
could customize sprites with the features and behaviors we wanted,
including data variables, an initialization function, and a custom
update function. We also learned how to scale images in Pygame so
that our smileys could come in all different shapes and sizes, and we
learned the advantages of using pygame.sprite.Group() to store all our
sprites for quick updating and drawing on the screen.
Free download pdf