PYTHON
Developing Noughts and Crosses in Python
Calvin Robinson details how to program the classic strategy game.
Calvin Robinson
OUR EXPERT
Calvin Robinson is a former assistant principal and computer science teacher with a degree in computer games design and programming.
During this series of tutorials we’ve been using Python to develop a range of retro video games. Python is an incredibly versatile high-level programming language with a relatively simple syntax; it suits our needs.
Over the past few issues we’ve built a lunar space module landing game, a side-scrolling platformer, Pac-Man, the Game of Life and a 2D shooter. This issue we’ll build a very recognisable minigame, with challenges for those who want to take things a step further.
Before we begin, we’ll need to make sure we have the latest version of Python 3 installed. For everyone running a Debian-based distro this is as simple as sudo apt-get install python3 , after a brief sudo apt-get update , of course.
The beauty of Python is that we can use any text-based editor to work in: nano, emacs, vim and so on. Simply create a file with the extension .py and you’re good to go. The terminal command python3 before the name of the file will execute it. If you prefer a graphical user interface then there’s always the default IDLE. When launching Python3 IDLE always remember to select File>New File and type in the script window, rather than the shell. Python’s shell is a real-time development tool for testing commands. The script window offers save and edit functionality, and pressing F5 will do both simultaneously.
X marks the spot
Our game this issue is Tic Tac Toe, also known as Noughts and Crosses. For those unfamiliar, a three-bythree grid is drawn out and two players take it in turns to drawn their mark attempting to create a row of three. Player one is usually a cross ‘X’ and player two is a circle ‘O’. The first successful combination of three Xs or Os in a row is a win, including diagonal lines. Interestingly, you’re twice as likely to win as an X, so you’re definitely better off going first. For that reason, Tic Tac Toe is usually played on a ‘best of three’ rotation, taking turns to play Xs and Os each game.
Let’s begin. Start a new Python file, whether in a text editor or IDLE, and import Turtle graphics.