Build a game framework with Python using
the Pygame module
The first part of this series explored Python by
creating a simple dice game. Now it's time to make your own game from scratch.
By
632 readers like this.

Image by:
OpenGameArt.org
In my first article in this series, I explained how
to use Python to create a simple, text-based dice game. You also used the
Turtle module to generate some simple graphics. In this article, you start
using a module called Pygame to create a game with
graphics.
The Turtle module is included with Python by
default. Anyone who's got Python installed also has Turtle. The same is not
true for an advanced module like Pygame. Because it's
a specialized code library, you must install Pygame
yourself. Modern Python development uses the concept of virtual environments,
which provides your Python code its own space to run in, and
also helps manage which code libraries your application uses. This
ensures that when you pass your Python application to another user to play, you
know exactly what they need to install to make it work.
You can manage your Python virtual environment
manually, or you can let your IDE help you. For now, you can let PyCharm do all
the work. If you're not using PyCharm, read László Kiss Kollár's article
about managing Python packages.
Getting started with Pygame
Pygame is a library, or Python module.
It's a collection of common code that prevents you from having to reinvent the
wheel with every new game you write. You've already used the Turtle module, and
you can imagine how complex that could have been if you'd had to write the code
to create a pen before drawing with it. Pygame offers
similar advantages, but for video games.
A video game needs a setting, a world in which
it takes place. In Pygame, there are two different
ways to create your setting:
Either way, your background is only an image or
a color. Your video game characters can't interact with things in the
background, so don't put anything too important back there. It's just set
dressing.
Setting up your first Pygame script
To start a new Python project, you would
normally create a new folder on your computer and place all your game files go
into this directory. It's vitally important that you keep all the files needed
to run your game inside of your project folder.
PyCharm (or whatever IDE you use) can do this
for you.
To create a new project in PyCharm, navigate to
the File menu and select New Project. In the
window that appears, enter a name for your project (such as game_001.)
Notice that this project is saved into a special PycharmProjects folder
in your home directory. This ensures that all the files your game needs stays in one place.
When creating a new project, let PyCharm create
a new environment using Virtualenv, and accept all
defaults. Enable the option to create a main.py file (and to
set up some important defaults.)