PyGame Basics
Collision
In games, when an object touches another object or boundary, we call it a collision. As an event that we want to handle.
Here, let's spin the ball and reverse it's direction whenever the hand hits the ball.
First, let's set a spin flag and set the movements for the ball.
class Ball(pygame.sprite.Sprite):
"""Bounce a ball around the screen. It can spin when it is hit."""
def __init__(self):
pygame.sprite.Sprite.__init__(self) # call Sprite intializer
self.screen = pygame.display.get_surface()
self.image = pygame.image.load("ball.png")
self.rect = self.image.get_rect()
self.speed = [2, 2]
self.spin = 0
def update(self):
"""move or spin, depending on the spin state"""
if self.spin:
self._spin()
else:
self._move()
def _move(self):
"""move the ball across the screen, reverse speed at the ends"""
self.rect = self.rect.move(self.speed)
if self.rect.left < 0 or self.rect.right > WIDTH:
self.speed[0] = -self.speed[0]
if self.rect.top < 0 or self.rect.bottom > HEIGHT:
self.speed[1] = -self.speed[1]
def _spin(self):
"""spin the ball image"""
center = self.rect.center
self.spin += 60
if self.spin >= 360:
self.spin = 0
self.image = self.original
else:
rotate = pygame.transform.rotate
self.image = rotate(self.original, self.spin)
self.rect = self.image.get_rect(center=center)
def hit(self):
"""this will cause the ball to start spinning"""
if not self.spin:
self.spin = 60
self.original = self.image
# Reverse direction
self.speed = [-x for x in self.speed]
We now do the same for the hand. Add a hit flag and check for collision with the ball and return True or False if collision occurs.
class Hand(pygame.sprite.Sprite):
"""moves a hand icon on the screen, following the mouse"""
def __init__(self):
pygame.sprite.Sprite.__init__(self) # call Sprite initializer
self.image = pygame.image.load("hand.png")
self.rect = self.image.get_rect()
self.hitting = 0
def update(self):
"""move the hand based on the mouse position"""
pos = pygame.mouse.get_pos()
self.rect.midtop = pos
if self.hitting:
self.rect.move_ip(5, 10)
def hit(self, target):
"""returns true if the hand collides with the target"""
if not self.hitting:
self.hitting = 1
hitbox = self.rect.inflate(-5, -5)
return hitbox.colliderect(target.rect)
def unhit(self):
"""called to pull the hand back"""
self.hitting = 0
Handle events
To trigger the actions, we will need to handle it in the check_events
loop.
def check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
self.running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if self.hand.hit(self.ball):
self.ball.hit()
elif event.type == pygame.MOUSEBUTTONUP:
self.hand.unhit()
return
Now, play the game!! 🎈