Fundamentals 6 min read

Drawing a 3×3 Magic Square with Python Turtle and Random Shuffle

This tutorial explains how to use Python's turtle graphics and the random module to draw a 3×3 magic square, covering functions for drawing squares, filling colors, displaying numbers, and a brute‑force algorithm that shuffles numbers until the magic‑square condition is met.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Drawing a 3×3 Magic Square with Python Turtle and Random Shuffle

The article demonstrates a simple approach to creating a 3×3 magic square visualization using Python. It first introduces the turtle library for drawing squares and provides a function zfx(a=200) that draws a single square of side length a.

Next, a helper function zfx2(a=100, x=0, y=0, c='gray', s='') is defined to position the turtle, fill the square with a specified color, and write a label at its center.

Using these helpers, the jgg(s='012345678') function draws the full 3×3 grid by calling zfx2 nine times with appropriate coordinates, colors, and characters from the input string.

To start, the grid can be displayed with placeholder symbols using jgg('?'*9).

The second part implements a brute‑force search for a valid magic square. It imports random, creates a list n = [1,2,3,4,5,6,7,8,9], and sets up a click handler run(x, y) that repeatedly shuffles n. After each shuffle it checks eight line‑sum conditions (rows, columns, diagonals) stored in real. If all conditions are true, the shuffled numbers are displayed with jgg(n) and the loop exits.

Finally, the program registers the click handler with w.onclick(run) and starts the turtle event loop with t.mainloop(). The complete code is provided in the article, aiming to help beginners quickly see visual results of their Python code.

import turtle as t<br/>t.speed(0)<br/>def zfx(a=200):<br/>    for i in range(4):<br/>        t.forward(a)<br/>        t.left(90)
def zfx2(a=100, x=0, y=0, c='gray', s=''):<br/>    t.up()<br/>    t.goto(x, y)<br/>    t.down()<br/>    t.fillcolor(c)<br/>    t.begin_fill()<br/>    zfx(a)<br/>    t.end_fill()<br/>    t.forward(a/2)<br/>    t.write(str(s), align='center', font=('宋体', 50, 'bold'))
def jgg(s='012345678'):<br/>    zfx2(x=-150, y=50, c='gray', s=s[0])<br/>    zfx2(x=-50, y=50, c='white', s=s[1])<br/>    zfx2(x=50, y=50, c='gray', s=s[2])<br/>    zfx2(x=-150, y=-50, c='white', s=s[3])<br/>    zfx2(x=-50, y=-50, c='gray', s=s[4])<br/>    zfx2(x=50, y=-50, c='white', s=s[5])<br/>    zfx2(x=-150, y=-150, c='gray', s=s[6])<br/>    zfx2(x=-50, y=-150, c='white', s=s[7])<br/>    zfx2(x=50, y=-150, c='gray', s=s[8])
jgg('?'*9)
import random<br/>n = [1,2,3,4,5,6,7,8,9]<br/>w = t.Screen()<br/>def run(x, y):<br/>    while True:<br/>        random.shuffle(n)<br/>        real = [(n[0]+n[1]+n[2])==15,<br/>                (n[3]+n[4]+n[5])==15,<br/>                (n[6]+n[7]+n[8])==15,<br/>                (n[0]+n[3]+n[6])==15,<br/>                (n[1]+n[4]+n[7])==15,<br/>                (n[2]+n[5]+n[8])==15,<br/>                (n[0]+n[4]+n[8])==15,<br/>                (n[2]+n[4]+n[6])==15]<br/>        if all(real):<br/>            jgg(n)<br/>            break<br/>w.onclick(run)<br/>t.mainloop()
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GraphicsalgorithmPythonturtlemagic-square
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.