The task is to do what a turtle library would do but without the library.
This is the drawing that I obtain
It needs to do a trace a path with a for loop but it should not arrive on the same place it started because the angle of rotation should make the turtle land on different spots on each time. BTW derecha(right), izquierda(left), arriba(up) abajo(down)
from graphics import*
import math
ancho = 500
alto = 500
a=alto/2
b=ancho/2
win = GraphWin ("Estrella",ancho,alto)
origen=Point(ancho/2, alto/2)
dirTort="derecha"
def T(dir,dist,ang):
global dirTort,a,b
ang=ang*math.pi/180
for i in range (40):
if dir == "derecha":
if dirTort == "derecha":
dirTort = "abajo"
valx = math.cos(ang)
valy = math.sin(ang)
elif dirTort == "izquierda":
dirTort = "arriba"
valx = -math.cos(ang)
valy = -math.sin(ang)
elif dirTort == "arriba":
dirTort = "derecha"
valx = math.sin(ang)
valy = -math.cos(ang)
elif dirTort == "abajo":
dirTort = "izquierda"
valx = -math.sin(ang)
valy = math.cos(ang)
elif dir == "izquierda":
if dirTort == "derecha":
dirTort = "abajo"
valx = -math.cos(ang)
valy = -math.sin(ang)
elif dirTort == "izquierda":
dirTort = "arriba"
valx = -math.cos(ang)
valy = math.sin(ang)
elif dirTort == "arriba":
dirTort = "derecha"
valx = -math.sin(ang)
valy = -math.cos(ang)
elif dirTort == "abajo":
dirTort = "derecha"
valx = math.sin(ang)
valy = math.cos(ang)
p1 = Point(a, b)
coordx=a+dist*valx
coordy=b+dist*valy
p2=Point(coordx, coordy)
linea=Line(p1,p2)
linea.setFill("red")
linea.draw(win)
a=coordx
b=coordy
print(coordx,coordy)
T("derecha",200,10)
print(dirTort)
message = Text(Point(win.getWidth()/2,win.getHeight()/15),"Click para salir")
message.draw(win)
win.getMouse()
My belief is you're not managing your angle correctly. Since you're basically drawing a square over and over, rotating a little each time, your angle is 90, or -90 degrees. This is tilted slightly between squares by the small rotation angle passed into the function. Here's a highly simplified version of your code that draws the desired target:
from graphics import *
from math import pi, sin as sine, cos as cosine, radians
WIDTH, HEIGHT = 500, 500
win = GraphWin("Star", WIDTH, HEIGHT)
origin = Point(WIDTH/2, HEIGHT/2)
def star(distance, angle):
theta = 0
angle_in_radians = radians(angle)
p1 = origin.clone()
for _ in range(360 // angle):
for _ in range(4): # draw a square
theta += pi / 2
p2 = p1.clone()
p2.move(distance * cosine(theta), distance * sine(theta))
line = Line(p1, p2)
line.setFill("red")
line.draw(win)
p1 = p2
theta += angle_in_radians # tilt our starting point slightly
star(175, 9)
message = Text(Point(WIDTH/2, HEIGHT/15), "Click to exit")
message.draw(win)
win.getMouse()
Hopefully it will help you get your code back on track.