Python Turtle Graphics - Drawing with Stamps

Python Turtle Graphics stamps are awesome.

They are not that well known, and learner python programmers often do things in a more complicated way than they need to as a result. Take this classic learner-programmer exercise:

Make a chessboard pattern using Python Turtle Graphics.

You might want to try the challenge for yourself before continuing to read…

Python Turtle Graphics - Drawing with Stamps

There are several approaches available for tackling this challenge:

  • Do the whole thing manually by moving and rotating the turtle, using begin_fill() and end_fill() as required.
  • Make a function to draw squares with a corner or center at given coordinates and do this in a [nested for loop][1].
  • Make a Square class and generate instances at the required locations, with the required color.
  • Use turtle.stamp().

We are going to look at the last approach from the above list in this article.

Python Turtle Graphics Stamp Example

I have had mixed success with embedding code from [repl.it][2]. Here is an iframe which should work fine, but I’ve also included the code listing below in case you want to copy/paste or even try typing it into a new Python file yourself (probably the best way to learn!)

How Does Python Turtle Stamp Work?

To explore the placement of turtle.stamp(), check out this very useful bit of Python turtle code for getting the coordinates from the screen. I’ve also printed the coordinates of the pen (which begins at the defualt location of (0, 0).

A little bit of experimentation will show that the stamp has been placed with its center at the position of the turtle which made it. This makes a lot of calculations involving positions on screen a whole lot easier, I find, than drawing a square with a corner a some position.

Exploring with Python Turtle Graphics Stamping

There is enough in this article to get you started with stamping in Python Turtle Graphics. I expect you can see some of the possibilities this method allows. Here’s just a few I can think of off the bat.

  • Board games
  • 2d games such and Snake/Tron clones
  • Exploring mazes
  • Pixel art

I hope you find fun ways to make use of Python Turtle stamps in your coding.

As always, happy computing.

Robin Andrews.

Leave a Repl​​​​​y

Your email address will not be published. Required fields are marked

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}

Get the code for the classic Retro Alien Blitz Game using Python Turtle Graphics when you join our mailing list