PYTHON
Recreate the classic Pac-Man in Python
Being chased down endless corridors by spectral apparitions is all in a day’s work for Andrew Smith and his Python skills…
OUR EXPERT
Andrew Smith is a software developer for NHS Digital, and likes video gaming and scripting in Python
QUICK TIP
Call your variables something meaningful so that you can easily identify what part they play in the program.
This issue we’re going to look at a game of Pac-Man created in Python using the PyGame library. The code for this project has been adapted from https://pacmancode.comwhere the original source code can be downloaded.
We’ll install and setup Python 3.10 for the benefit of this tutorial. For those that have Python/PyGame already installed, Python 3.8+ should be a good-enough version to use with this tutorial. Type the following to install Python 3.10 and PyGame:
This project uses the numpy Python library and can be installed using pip by using the following commands if it’s not already installed.
$ pip install numpy
To ensure you’re calling the correct pip version, check the Scripts folder of the Python installation folder. There may be a version number of pip to use, such as pip3.8. Check the versions of python and pygame, too. Next, git clone from repository:
$ git clone https://github.com/asmith1979/lxf294_ pacman/
The project has been placed in a folder called PythonProjects, which was created before downloading the project. The source code and project can also be retrieved from the Linux Format archive. This tutorial will focus on the source code located in the folder called lxf294_pacman. If you’re not already in that folder type cd lxf294_pacman to access the Python source code.
To edit and view the source code you can either use a default text editor or you could use something more specific such as Notepad++, PyCharm or VS Code. In this tutorial, we’ll be using gedit to view and edit the source files with. If and when using this method to view/edit source files, consider opening two console windows. Use one for editing/viewing source files and the other terminal window for executing the PyGame code
This game project consists of a lot of Python, image and text files that are required to run the project. Not all of the Python code will be covered in this tutorial, but a selection of some of the Python files will be studied, including run.py, sprites.py, constants.py, pacman.pyand ghosts.py.