Python: simple square grid

gridpythonturtle-graphics

Recently, I've been trying to figure out a 20 by 20 square grid. so far I've only figured out how to draw 4 no matter what I put as my # of. it would be greatly appreciated if someone can figure out my flaws in the code!

what I'm trying to achieve

what I'm trying to achieve

my code

import turtle
turtle.hideturtle()
t = turtle.Turtle()
t.hideturtle()

def draw_square(t, size, num, angle):

for i in range(num):
    for x in range(4):
        turtle.forward(size)
        turtle.left(90)
    turtle.right(angle)

draw_square(t, 25, 4, 90)

Best Answer

Your code has a pair of nested loops. However, given the way you're drawing the grid, you really need three nested loops. Trying to figure out the least amount of code to get from where you are to where you want to be, I came up with the following:

from turtle import Screen, Turtle

def draw_square(turtle, size, num):
    for y in range(num):
        for x in range(num):
            for _ in range(4):
                turtle.forward(size)
                turtle.left(90)

            turtle.forward(size)

        parity = y % 2 == 0
        turn = turtle.left if parity else turtle.right

        turn(90)
        turtle.forward(size * 2 * parity)
        turn(90)

screen = Screen()

yertle = Turtle(visible=False)
yertle.speed('fastest')  # because I have no patience

draw_square(yertle, 25, 20)

screen.exitonclick()

This code is inefficient drawing-wise as the same lines get redrawn which is something to be avoided. My personal favorite solution to this problem is my Tholian Web approach using generators:

from turtle import Turtle, Screen

UNIT_SIZE, GRID_SQUARES = 25, 20

GRID_SIZE = GRID_SQUARES * UNIT_SIZE

def half_grid(turtle):
    speed = turtle.speed()

    for brick in range(GRID_SQUARES):
        direction = [turtle.right, turtle.left][brick % 2 == 1]

        for _ in range(0, GRID_SIZE, speed):
            turtle.forward(speed)
            yield(0)

        direction(90)

        for _ in range(0, UNIT_SIZE, speed):
            turtle.forward(speed)
            yield(0)

        direction(90)

    for _ in range(0, GRID_SIZE, speed):
        turtle.forward(speed)
        yield(0)

heckle = Turtle(shape='arrow')
heckle.speed(5)  # speed needs to be a factor of UNIT_SIZE
heckle.penup()
heckle.goto(-GRID_SIZE / 2, -GRID_SIZE / 2)
heckle.pendown()
heckle.left(90)

jeckle = Turtle(shape='arrow')
jeckle.speed(5)
jeckle.penup()
jeckle.goto(GRID_SIZE / 2, -GRID_SIZE / 2)
jeckle.pendown()
jeckle.left(180)

generator1, generator2 = half_grid(heckle), half_grid(jeckle)

while (next(generator1, 1) + next(generator2, 1) < 2):
    pass

heckle.hideturtle()
jeckle.hideturtle()

screen = Screen()
screen.exitonclick()

enter image description here

But that's probably overkill for your purposes...