Building Tetris in Pygame – Part I

# 000 Introduction

My interest in programming grew from playing video games as a kid. I don’t think I’m at all unique in that respect. So it’s natural that when I learned to program, one of the first things I wanted to do was write a game. Lately I’ve been using the Pygame framework to move up from the terminal to graphics.

There are a lot of Pygame tutorials out there. However, by and large, they all show signs of serious code smell — abuse of globals, magic numbers, etc. Since these are generally short one-file projects that’s not a problem, but it quickly becomes an issue if you want to scale up.

I want to attempt to build games using solid practices — clean namespaces, TDD-style unit testing, and so on. This will be a “live” series; when I inevitably screw something up, I’ll show how I work around it. While this isn’t necessarily a tutorial per se, feel free to follow along. (Some knowledge of basic programming and Python syntax is recommended. Zed Shaw’s Learn Python The Hard Way should get you up to speed should you need it.)

We’ll start with a Tetris clone. Tetris is fairly complex, with plenty of common game issues (controlling speed, collision detection) without being obscenely hard. It’s also a highly addicting game, and what better way to celebrate when we’re done than a six-hour gaming binge?

# 001 Project Setup

First things first, let’s get our project folders laid out, and setup source control (I prefer git).

$ mkdir tetris
$ cd tetris
$ mkdir tetris lib tests
$ touch tetris/__init__.py lib/__init__.py tests/__init__.py
$ touch tetris.py run_tests.py
$ touch .gitignore README
$ git init

Our project layout:

tetris/
|--README
|--tetris.py
|--run_tests.py
|--.gitignore
|--tetris/
|  `--__init__.py
|--lib/
|  `--__init__.py
`--tests/
   `--__init__.py

Open up .gitignore in your editor of choice, and copy and paste our boilerplate ignore files (modified from the Python template hosted at GitHub):

*.py[cod]

# C extensions
*.so

# Packages
*.egg
*.egg-info
dist
build
eggs
parts
bin
var
sdist
develop-eggs
.installed.cfg

# Installer logs
pip-log.txt

(Modify this as needed for your editor/IDE’s particular configuration and project files.)

And we’re done for this time. Add and commit to git:

$ git add .
$ git status
...
$ git commit -m "Project Setup"

Next time, we’ll talk about data structures, testing, and start writing code!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s