The 21 Game with Python Turtle Graphics

Here’s something fun.

The 21 Game is a two-player counting game where each player can add 1, 2, or 3, starting at zero, to the total. the total must not exceed 21 and the player who lands on 21 loses.

Maybe find someone to play it with toady. You might find that it is possible to develop a winning strategy, depending on who starts. What is this winning strategy?

One way to figure it out is with the help of a visual representation. With Python, one of my favourite tools for creating visual representations is the Turtle Graphics Module.

The code below allows you to toggle the color of the squares in the representation of the game so you can see how you might win. If you need a hint on the strategy, think what might constitute a “safe square.”

Hopefully the comments will help to understand how this code works, but there are couple of things to point out.

  • The click callback (the function that is called when a click event is detected on a turtle) needs an additional parameter so it can be attached to a particular turtle. This had me stumped for a while, but then I found this link which explains how to do it. If you don’t know, the Turtle Module is build on Tkinter, so solving Turtle-related problems can involve thinking about what’s going on with Tkinter.

  • To save having to wait for the drawing to take place, I have used screen.tracer(0) then screen.tracer(1) to re-enable animation once the drawing is complete.

The “extra arguments” trick means that creating this code from scratch is more of an intermediate exercise than one for beginners, but as a demo of what’s possible with Python Turtle Graphics as well as a useful way to help you become an expert at the 21 Game, I think it’s pretty neat.

I hope you enjoy it.

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