Learn PureBasic by example. Follow the development step by step of a simple 2D game : the snake. This famous game lets you control a snake on a screen where apples appear at random. When the snake eats an apple, it grows in size. The goal is to survive the longest.
In this episode, I start with refactoring the code. Then, I make the whole game look better by adding a picture as the background. Finally, I add a pause/resume feature using a state machine. When paused, the screen displays a special screen with the shortcuts for the game.
I refactor the code first because it will make it easier to manage the different states. The refactoring consists of extracting code from the main procedure into separate procedures and macros : OpenGameWindow(), CreateSprites(), EmptyMessageQueue(event), PrepareFrame(), DrawFrame() and HandleKeys(). I also replace the code for hiding the mouse cursor by the "correct" one.
For the background, I downloaded and resized a nice photograph. I then make the board semi-transparent so the background can be seen through. Only the snake and the apple are fully opaque.
For the pause state, I introduce an enumeration for the state with 2 states : playing and pause and I add a simple state machine in the main procedure. When playing, I prepare and draw the game frames. I renamed the PrepareFrame() and DrawFrame() procedures to PrepareFramePlaying() and DrawFramePlaying(). When in pause, I draw a specific frame (using the new DrawFramePause() procedure). This frame is made of a game frame on top of which I add a semi-transparent image with some text that I have created. To manage the state correctly, I also have to manage the way the keyboard events are processed. Only in the playing state will the arrows, F and M shortcuts work. I finally add the handling of the spacebar key to toggle between the pause and playing states.
And voila!
I do not distribute the sound files for copyright reasons. But you can find sound effects at http://freesound.org
To convert files to OGG format, you can go to https://convertio.co
Download the code from this episode at https://bit.ly/3bP0Ubx
Download PureBasic at http://www.purebasic.com/pp
Pure Programming blog
https://pure-programming.com
Facebook
/ pureprogramming
Follow me on Instagram at @pure.programming
Support the channel with some Merchandising
EU : shop.spreadshirt.net/pure-programming
US : shop.spreadshirt.com/pure-programming
Photo by Kristopher Roller on Unsplash
Pause/Resume icons made by Freepik from www.flaticon.com