In: Computer Science
How to make a python program that imports only turtle and math library where I can click once on the screen to set the center of the square, move the mouse to define the edge-length of the square; click a second time to draw the square with the defined edge-length and center point?
Comment if you have any issues or changes to be made.
Code:
import turtle
def get_mouse_click_coor(x, y):
global centerClick,centerCoordinates
if centerClick == 0:
centerCoordinates = (x,y)
centerClick = 1
else:
edgeCoordinates = (x,y)
centerClick = 0
drawSquare(centerCoordinates, edgeCoordinates)
def drawSquare(center, edge):
#calculate difference
x = abs(center[0] - edge[0])
y = abs(center[1] - edge[1])
#set edge length
if y > x:
sideLength = y * 2
else:
sideLength = x * 2
#create turtle
square = turtle.Turtle()
square.penup()
#go to center coordinates
square.goto(center)
for i in range(2):
square.forward(sideLength/2)
square.right(90)
#draw square
square.pendown()
for i in range(4):
square.forward(sideLength)
square.right(90)
#start program
wn = turtle.Screen()
# wn.bgcolor("light blue")
centerClick = 0
wn.onscreenclick(get_mouse_click_coor)
turtle.done()
Code Screenshots:
Output