Using object oriented programming in C++ to create an ESP8266 breakout game

Recently I’ve been making a breakout game for an ESP8266 module that has a 64×128 OLED display and a 4-way joystick:

Up until now I’ve avoided using any object oriented programming with Arduino. However, I wanted to have a go at it, and this seemed like a good project to start.

You can see the code here: https://github.com/brychanthomas/ESP8266-OLED-breakout

I ended up with the following classes:

  • Sprite – an abstract class to represent a sprite that can be drawn on the OLED screen
  • Paddle – represents the movable paddle at the bottom of the screen, inherits from Sprite
  • Ball – a class to represent the ball that bounces off things and destroys bricks, also inherits from Sprite
  • Brick – represents a single brick, inherits from Sprite
  • Bricks – contains and manages all of the bricks in the game
  • BreakoutGame – the overall game, creates Paddle, Ball and Bricks instances and calls their update and draw methods each frame

Here’s a UML class diagram:

Initially a “push to play” message is displayed. When the button is pushed the game starts. The paddle is moved left and right using the joystick. If the ball hits the bottom of the screen, the game pauses and a “push to play” message appears. When the user pushes the button the game resumes, with the ball moved upwards. Once all of the bricks have been destroyed, a “winner!” message is displayed for five seconds before the game resets to the “push to play” message, and can be played again.

Here is a (poor quality) GIF showing some gameplay:

The part I found most difficult was the collision detection between the ball and the bricks. The display is supposed to be used horizontally, not vertically like I was using it, so the x axis went downwards from the top, and the y axis went from right to left. It took me a while to get my head around it because I’m so used to y going upwards or downwards and x going from left to right.

To detect collisions the program finds the point on the edge of the brick closest to the ball. If the distance between this point and the centre of the ball is less than the radius, the two sprites are overlapping and the ball should bounce and the brick be destroyed. This page helped me a lot.

Another problem I had is that, because the display was rotated, using the text rendering functions of the OLED library showed the text sideways, and there isn’t a way of rotating it. As a result, I had to use XBM images instead. I created the “push to play” and “winner!” messages in MS Paint, saved them as BMP files and converted them to XBM using an online converter. I could then display them in the program with the correct orientation.

I’ve enjoyed my first foray into OOP with C++ and I feel more confident that I can use it on future Arduino projects.

Leave a comment

Design a site like this with WordPress.com
Get started