Skip to content

Instantly share code, notes, and snippets.

@abhijitmamarde
Created December 1, 2023 06:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhijitmamarde/4fb1a4088bfb008cb6ff5c998b17a820 to your computer and use it in GitHub Desktop.
Save abhijitmamarde/4fb1a4088bfb008cb6ff5c998b17a820 to your computer and use it in GitHub Desktop.
Draws and Traces the magic grid using Turtle, works only for odd length grid
import sys
import turtle
def generate_magic_square(n):
"""
This works only for odd grid size 3x3, 5x5, 11x11 etc., not for even
"""
magic_square = [[0] * n for _ in range(n)]
num = 1
i, j = 0, n // 2
while num <= n * n:
magic_square[i][j] = num
num += 1
newi, newj = (i - 1) % n, (j + 1) % n
if magic_square[newi][newj]:
i += 1
else:
i, j = newi, newj
return magic_square
def dump_magic_square(magic_square):
with open("out_grid.csv", "w") as f:
for row in magic_square:
# print(" ".join(str(num).rjust(3) for num in row))
f.write(",".join(str(num).rjust(3) for num in row) + "\n")
print("Done writing to out_grid.csv")
def draw_trace(t, magic_square):
t.speed(0.1)
last_points = None
cell_size = 50 # Adjust cell size as needed
for num in range(1, len(magic_square) * len(magic_square) + 1):
for i in range(len(magic_square)):
for j in range(len(magic_square[0])):
if magic_square[i][j] == num:
t.penup()
t.goto((j - len(magic_square[0]) / 2) * cell_size, (len(magic_square) / 2 - i) * cell_size)
t.pendown()
t.circle(10)
curr_pos = t.pos()
if last_points is not None:
t.pendown()
t.fillcolor('green')
t.penup()
t.goto(last_points[0], last_points[1])
t.pendown()
t.goto(curr_pos[0], curr_pos[1])
t.stamp()
last_points = curr_pos
else:
last_points = curr_pos
t.pendown()
t.write(num, align="center", font=("Arial", 12, "normal"))
# t.circle(20)
t.penup()
t.goto(cell_size, 0) # forward(cell_size)
t.pendown()
t.hideturtle()
def draw_trace_orig(t, magic_square):
t.speed(1)
cell_size = 50 # Adjust cell size as needed
for num in range(1, len(magic_square) * len(magic_square) + 1):
for i in range(len(magic_square)):
for j in range(len(magic_square[0])):
if magic_square[i][j] == num:
t.penup()
t.goto((j - len(magic_square[0]) / 2) * cell_size, (len(magic_square) / 2 - i) * cell_size)
t.pendown()
t.write(num, align="center", font=("Arial", 12, "normal"))
t.forward(cell_size)
t.hideturtle()
def main():
n = 5
if len(sys.argv) > 1:
n = int(sys.argv[1])
magic_square = generate_magic_square(n)
dump_magic_square(magic_square)
window = turtle.Screen()
window.title(f"Trace of {n}x{n} Magic Square")
t = turtle.Turtle()
# Drawing the trace of magic square creation using turtle
draw_trace(t, magic_square)
turtle.done()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment