Thursday, December 29, 2022

Debugging Pygame Zero Games in VSCode

As part of my ongoing effort to expose my kids to various science topics, I picked up a Python game development book for kids and I'm working through it with my youngest. As part of that process, I was just setting up Pygame and Visual Studio Code (VSCode) over the holidays.

The setup didn't take long, but I did run into an issue. When I ran our code from the terminal, the games worked fine. However, when we tried to debug from VSCode, the Pygame Zero game window wouldn't--Pygame opened on the taskbar but just closed again. I did find the solution, so I thought I'd same some other people some Googling and document it here. The book just references IDLE, so it doesn't get into running the example games in an IDE such as VSCode.

The book I chose is Coding Games in Python*. It's specifically targeted at kids, so it's a colourful book filled with a basic introduction to coding and some simple game examples. I highly recommend it.


Getting back to the issue, I could successfully set breakpoints, but as soon as they were done, Pygame would close, and the game window would never appear. The answer is on page 25 of the book (which I skipped because I already had the setup done :) and it's also in the Pygame Zero doc page about IDEs. Here's the solution (paraphrased):

Pygame Zero includes a way of writing a full Python program that can be run using python. To set up VSCode for debugging, add this line at the top of your file:

import pgzrun

Then add this line to the end of your file:

pgzrun.go()

* Coding Games in Python was written by Carole Vorderman MBE, Craig Steele, Dr. Claire Quigley, Daniel McCafferty, and Dr. Martin Goodfellow.