PyGame Basics
The Fun
Now to make the game actually fun and challenging, we need to introduce some levelling up, or increased difficulty as we play.
There are multitude of ways to achieve this, feel free to experiment. Here, we can just speed up the ball by checking the score.
Level up
First let's set score member function to keep track of the number of successful hits:
class Game():
def __init__(self):
pygame.init() # initialise pygame libraries
self.size = WIDTH, HEIGHT
self.display = pygame.display.set_mode(self.size)
self.disp_surf = self.init_display()
self.running = True if self.disp_surf else False
self.font = pygame.font.Font(pygame.font.get_default_font(), 36)
self.ball = Ball()
self.hand = Hand()
self.allsprites = pygame.sprite.RenderPlain((self.ball, self.hand))
self.sound_hit = pygame.mixer.Sound("thump.wav")
self.sound_missed = pygame.mixer.Sound("swish.wav")
self.score = 0
And increment the score with every successful hit:
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()
self.sound_hit.play()
self.score += 1
if self.score % 10 == 0:
self.ball.level_up()
else:
self.sound_missed.play()
elif event.type == pygame.MOUSEBUTTONUP:
self.hand.unhit()
return
And we add a level up function to our Ball object.
class Ball(pygame.sprite.Sprite):
"""Bounce a ball around the screen. It can spin when it is hit."""
.
.
.
def level_up(self):
self.speed = [2*x for x in self.speed]
Score
We should let the user know their score.
Let's edit out text:
def render(self):
'''Render surface'''
# background
self.disp_surf.fill(BLACK)
# draw text
text = "Spin the Ball : %s" % self.score
self.draw_text(text, GREEN, (int(WIDTH / 2), int(HEIGHT / 2)))
# Blit everything to screen
self.display.blit(self.disp_surf, (0,0))
# draw ball
self.allsprites.update()
self.allsprites.draw(self.display)
# update display
pygame.display.flip()
return
And now we have a simple !! Do drop me a note 📧 on the fun games you create, I'd love to hear about them !!