Animating Squares Around the Edge of a Window in Python
Mar 22, 2016
4 minute read
Previously, I wrote about how I like to get students to try to create Processing code to emulate a simple animation of a square moving clockwise around the edges of a screen. In this post, I’ll do the same thing, but using Python Turtle graphics, as well as the PyGame Zero module.
Garth Flint was playing around with using state variables, and was nice enough to write about the process. He first had the students create the following animation in Small Basic:
He then worked on making the same animation in Python, which did not go quite a smoothly. I had a few minutes to spare this evening, so I thought I’d try it as well. In the end, I created versions using two different modules.
##Python Turtle Graphics
Every Python installation comes with the turtle module built in, which I like to use with my students to tackle some classic drawing challenges. So, naturally, I thought this might provide a reasonable way to replicate the animation. I ended up with this:
Although this does work, and idiomatically follows the spirit of turtle graphics, it does completely remove the need for a state variable. I wrote another turtle graphics version that shoehorns in state variables, though it’s pretty ugly.
Although these worked, and have the advantage of not requiring any additional modules to be installed on top of the stock Python installation, I thought I’d give PyGame Zero a go as well.
I was messing around with PyGame Zero earlier today, wondering if it might be suitable to introduce slightly more complicated GUI interfaces that what is possible with turtle graphics, but less complicated than pyGame. I thought this would be a good time to see if it is up to the task of some simple animations.
Installing the module could be a bit involved, depending on your setup. Since I already had pyGame installed (on both Mac and PC), all I had to do was call pip3 install pgzero from the terminal. After messing about for awhile, trying to wrap my head around the API, I came up with this (note that for this to work, I created a 20x20 png image that was simply a black box. That is what gets loaded in the first line of code):
Written by Dan Schellenberg, a computer science and math teacher in Saskatoon, Sk, Canada.