0

I'm trying to draw a square randomly on a 700x700 grid however on each random run the square is drawn out of the boundary. How would I make it such that the whole square remains within the main grid boundary? Only the lower left of the square remains within the grid. I have this function below that draws a square randomly.

def draw_square():
    """ Function to draw a square randomly on 700x700 grid """
    turtle.penup()
    turtle.setheading(0)  # Make the turtle face east (0 degrees)
    x = random.randint(-340, 340)
    y = random.randint(-365, 315)
    turtle.goto(x, y)
    turtle.pendown()  # Put the pen down
    turtle.pensize(3)  # Set the pen's width to 3 pixels
    for i in range(4):
        turtle.forward(100)
        turtle.left(90)
Mikey
  • 19
  • 1
  • 4

1 Answers1

0

Adjust the range on your random X and Y. Make both 350-100(or -350+100), so that it can never go beyond 350 and -350 which is your boundary

def draw_square():
    """ Function to draw a square randomly on 700x700 grid """
    turtle.penup()
    turtle.setheading(0)  # Make the turtle face east (0 degrees)
    x = random.randint(-250, 250)
    y = random.randint(-250, 250)
    turtle.goto(x, y)
    turtle.pendown()  # Put the pen down
    turtle.pensize(3)  # Set the pen's width to 3 pixels
    for i in range(4):
        turtle.forward(100)
        turtle.left(90)

draw_square()

Also make sure your screensize is actually 700x700 with

screen.screensize(canvwidth=700, canvheight=700,)
pudup
  • 121
  • 5
  • Nice answer except I would recommend `screen.setup(700, 700)` over `screensize()` as the latter sets the size of the backing store, not the window itself see [this answer](https://stackoverflow.com/a/61883613/5771269) – cdlane Apr 19 '21 at 15:46
  • Thanks for your suggestion, however it won't be able to assign x,y coordinates to say ('-335, 348). I wanted it such that all the corners of the sqare fit within the given range. For example, if the lower left of the square gets randomly assigned to (335, 310), obviously the other edges to the right will be out of range (435, 310). I think I only had to change the upper limit for both coordinates (350-100) hence x = random.randint(-350, 250) y = random.randint(-350, 250) – Mikey Apr 20 '21 at 03:18
  • Yeah I just said 250 without giving it much thought. You'd have to change whatever value to 250 based on how your square starts being drawn. If it spawns at -340x but then never goes left from there, then -340x is fine. – pudup Apr 20 '21 at 13:02
  • @cdlane Yeah, you're right. I just haven't used tkinter in forever and just pulled that answer from whatever reference I found first. – pudup Apr 20 '21 at 13:03