user2553807
user2553807

Reputation: 329

Python Turtle draw centered square

I need to draw a square given a center point using the turtle module.

def drawCentSq(t,center,side):
    xPt=center[0]
    yPt=center[1]
    xPt-=int(side/side)
    yPt+=int(side/side)
    t.up()
    t.goto(xPt,yPt)
    t.down()
    for i in range(4):
        t.forward(side)
        t.right(90)

def main():

import turtle        
mad=turtle.Turtle()
wn=mad.getscreen()
print(drawCentSq(mad,(0,0),50))
main()

I'm having a hard time making my turtle go to the right starting point.

Upvotes: 1

Views: 5920

Answers (2)

cdlane
cdlane

Reputation: 41925

I need to draw a square given a center point using the turtle module.

As @seth notes, you can do this by fixing the center calculation in your code:

from turtle import Turtle, Screen

def drawCentSq(turtle, center, side):

    """ A square is a series of perpendicular sides """

    xPt, yPt = center

    xPt -= side / 2
    yPt += side / 2

    turtle.up()
    turtle.goto(xPt, yPt)
    turtle.down()

    for _ in range(4):
        turtle.forward(side)
        turtle.right(90)

yertle = Turtle()

drawCentSq(yertle, (0, 0), 50)

screen = Screen()
screen.exitonclick()

But let's step back and consider how else we can draw a square at a given point of a given size. Here's a completely different solution:

def drawCentSq(turtle, center, side):

    """ A square is a circle drawn at a rough approximation """

    xPt, yPt = center

    xPt -= side / 2
    yPt -= side / 2

    turtle.up()
    turtle.goto(xPt, yPt)
    turtle.right(45)
    turtle.down()

    turtle.circle(2**0.5 * side / 2, steps=4)

    turtle.left(45)  # return cursor to original orientation

And here's yet another:

STAMP_UNIT = 20

def drawCentSq(turtle, center, side):

    """ A square can be stamped directly from a square cursor """

    mock = turtle.clone()  # clone turtle to avoid cleaning up changes
    mock.hideturtle()
    mock.shape("square")
    mock.fillcolor("white")
    mock.shapesize(side / STAMP_UNIT)

    mock.up()
    mock.goto(center)

    return mock.stamp()

Note that this solution returns a stamp ID that you can pass to yertle's clearstamp() method to remove the square from the screen if/when you wish.

Upvotes: 1

seth
seth

Reputation: 1788

You need:

xPt-=int(side/2.0)
yPt+=int(side/2.0)

As it was you were just += and -= 1.

Upvotes: 1

Related Questions