Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop of python graphics

I am working on optimizing my code for a school project I have. I am attempting to draw a grid using the Python graphics library. When I run the loop, it continues to add rows, but the x1 and x2 values do not go back to their original values like I need them to. It extends the next row at the (x2, y2) point of the last square of the row. Any insight into how I could fix this would be greatly appreciated!

import random, graphics
from graphics import *

x1 = 5
x2 = 65
y1 = 5
y2 = 65

def make_square(x1, x2, y1, y2):

    location = graphics.Rectangle(graphics.Point(x1, y1), graphics.Point(x2, y2))
    location.draw(win)
    
win = graphics.GraphWin("Minesweeper", 545, 570)
win.setBackground(color_rgb(250, 249, 246))

for i in range(9):
    for j in range(9):
        make_square(x1, x2, y1, y2)
        x1 = x1 + 60
        x2 = x2 + 60
    y1 = y1 + 60
    y2 = y2 + 60
     
win.getMouse() # Pause to view result, click on window to close it
win.close() # Close window when done 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, at the start of drawing a new row, you want to reset x1 and x2, which makes sense, because the next row would start at the same x position as the previous row. Did you try adding your x1 = 5 and x2 = 65 to the start of the outer for loop, instead of defining them outside the loop?

Look at it this way: you define y outside the outer loop, because it loops over rows, you define x outside the inner loop, because it loops over columns:

import random, graphics
from graphics import *


def make_square(x1, x2, y1, y2):

    location = graphics.Rectangle(graphics.Point(x1, y1), graphics.Point(x2, y2))
    location.draw(win)
    

win = graphics.GraphWin("Minesweeper", 545, 570)
win.setBackground(color_rgb(250, 249, 246))

y1 = 5
y2 = 65
for i in range(9):
    x1 = 5
    x2 = 65
    for j in range(9):
        make_square(x1, x2, y1, y2)
        x1 = x1 + 60
        x2 = x2 + 60
    y1 = y1 + 60
    y2 = y2 + 60
     
win.getMouse() # Pause to view result, click on window to close it
win.close() # Close window when done 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading