Interested to start computer programming for coding special programs to introduce computer games. This tutorial of how to build games for python using pygame helps you figure out how to initiate and write games in python and on every platform. That’s how I found out Pygame and want to learn how to use it to build games python and other graphical programs. Make use of the below modules and become a primer on pygame.
Read Also: Java Program to Check Whether the Matrix is a Magic Square or Not
We will be covering the following topics in this Build Games for Python Using Pygame Tutorial:
- What is Pygame?
- Installing PyGame
- Importing and Initializing PyGame
- Basic PyGame Program
- How to Build Games in Python using Pygame?
- Game Architecture
- Directory and File Structure
- The GameObject Class
What is Pygame?
Pygame is a set of modules designed to help you write Python games by providing you with extra functionalities and libraries. It’s free, supports Python 3.2 and up, runs on just about every operating system and platform, and has over a million downloads, so it’s very widely used.
- How to Pickle Unpickle Tutorial | Understanding Python Pickling & Unpickling with Example
- Top 5 Free Python Resources for Beginners | Best Free Python Learning Resources
- How to Use Python to Convert Miles to Kilometers | Python Program to Convert Miles to KM Unit Measurement
Pygame is super speedy because it uses optimized C for core functions (C can be up to 10 or 20 times faster than Python). The library also provides speedy and attentive support — expect them to be very responsive if you find a bug or run into any issues with the code. Thousands of games have been made using Pygame, including this arcade-style game where the objective is to shoot as many asteroids as you can and pick up stranded astronauts to return to the space station.
Not only is it fun to make games using Pygame (the creators say that “silliness is included”), but it’s also loads of fun to play the games created using the library. If you’re a game maker who’s been looking for modules and libraries that make the process of creating Python games quicker and more efficient, Pygame might be the right tool for you. If you need help getting started, be sure to check out the tutorials page.
Also Read: Check Object Type Python
Installing PyGame
It is quite straightforward and simple to install PyGame. However, the first requirement is to install Python 2.7. Also, the installation of Python on both Windows and Linux is very easy and manageable.
The next process is to download the official PyGame installer and run the corresponding files and follow the on-screen instructions carefully. Installation is simple. Just follow through and the defaults are considered fine.
I myself use PyCharm and install all of these add-ons there and run using that for my Python requirements. Simply use whichever IDE you are comfortable with and start along with that.
Importing and Initializing PyGame
The pygame library determines several things in addition to modules and classes. Also, describes a few local constants for things like keystrokes, mouse movements, and display attributes. You can refer to these constants utilizing the syntax pygame <CONSTANT>. By importing particular constants from pygame.locals, you can utilize the syntax <CONSTANT> instead. That will save you some keystrokes and develop overall readability.
Once you import the pygame, it is mandatory to initialize it. This provides pygame to connect its abstractions to your special hardware:
# Import the pygame module import pygame # Import pygame.locals for easier access to key coordinates # Updated to conform to flake8 and black standards from pygame.locals import ( K_UP, K_DOWN, K_LEFT, K_RIGHT, K_ESCAPE, KEYDOWN, QUIT, # Initialize pygame pygame.init()
Basic PyGame Program
Before going down to the main concept, let’s have a glance at the simple & basic pygame program. This program makes a window, fills the background with white, and draws a blue circle in the middle of it:
# Simple pygame program # Import and initialize the pygame library import pygame pygame.init() # Set up the drawing window screen = pygame.display.set_mode([500, 500]) # Run until the user asks to quit running = True while running: # Did the user click the window close button? for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Fill the background with white screen.fill((255, 255, 255)) # Draw a solid blue circle in the center pygame.draw.circle(screen, (0, 0, 255), (250, 250), 75) # Flip the display pygame.display.flip() # Done! Time to quit. pygame.quit()
After executing this python pygame program, you’ll observe a window which is shown below:
How to Build Games in Python using Pygame?
For this tutorial, I will be going to discuss my approach a little on its head. Rather than notifying you into a game step-by-step, I’m preferably going to provide you the code, and then we’re performing a breakdown to understand how it all works.
Initial, ensure you’ve read our basic introduction to Python code where you will familiar with the fundamentals so that you’ll be able to follow along. Also, you require Python IDE or code editor, like PyCharm or even Visual Studio.
Later, you’ll be going to write the game program in python using pygame and run it. You can use the above given basic pygame program or else copy the following code:
import pygame pygame.init() win = pygame.display.set_mode((1280, 720)) pygame.display.set_caption("Squarey") x = 100 y = 100 baddyX = 300 baddyY = 300 vel = 6 baddyVel = 4 run = True def draw_game(): win.fill((0, 0, 0)) pygame.draw.rect(win, (0, 0, 255), (x, y, 20, 20)) pygame.draw.rect(win, (255, 0, 0), (baddyX, baddyY, 40, 40)) pygame.display.update() while run: pygame.time.delay(100) if baddyX < x - 10: baddyX = baddyX + baddyVel drawGame() elif baddyX > x + 10: drawGame() baddyX = baddyX - baddyVel elif baddyY < y - 10: baddyY = baddyY + baddyVel elif baddyY > y + 10: baddyY = baddyY - baddyVel else: run = False for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: x -= vel if keys[pygame.K_RIGHT]: x += vel if keys[pygame.K_UP]: y -= vel if keys[pygame.K_DOWN]: y += vel draw_game() pygame.quit()
Game Architecture
Games manage a lot of data and execute similar operations on many objects. Breakout is a mini-game, yet trying to manage everything in one file would be awful. Rather, I opted to build a file structure and architecture that fits many larger games.
Directory and File Structure
├── Pipfile
├── Pipfile.lock
├── README.md
├── ball.py
├── breakout.py
├── brick.py
├── button.py
├── colors.py
├── config.py
├── game.py
├── game_object.py
├── images
│ └── background.jpg
├── paddle.py
├── sound_effects
│ ├── brick_hit.wav
│ ├── effect_done.wav
│ ├── level_complete.wav
│ └── paddle_hit.wav
└── text_object.py
The GameObject Class
The representation of a visual object that understands how to render itself, maintain its boundaries, and move around is GameObject Class. Truly, Pygame has a Sprite class that has the same role, but in this series, I aspire to show how things work at a low level and not rely on too much-prepackaged magic.
This GameObject class is intended to operate as a base class for different objects. It reveals immediately a lot of the properties of its self.bounds rectangle, and in its update() method it transfers the object as per its current speed. It doesn’t do anything in its draw() method, which should be overridden by sub-classes. The following is the GameObject class:
from pygame.rect import Rect class GameObject: def __init__(self, x, y, w, h, speed=(0,0)): self.bounds = Rect(x, y, w, h) self.speed = speed @property def left(self): return self.bounds.left @property def right(self): return self.bounds.right @property def top(self): return self.bounds.top @property def bottom(self): return self.bounds.bottom @property def width(self): return self.bounds.width @property def height(self): return self.bounds.height @property def center(self): return self.bounds.center @property def centerx(self): return self.bounds.centerx @property def centery(self): return self.bounds.centery def draw(self, surface): pass def move(self, dx, dy): self.bounds = self.bounds.move(dx, dy) def update(self): if self.speed == [0, 0]: return self.move(*self.speed)