Question

I have a program that is suppose to create a triangle at an x,y with a set height and a set width. This is the code I have but the triangle that it is creating is messed up sometimes if the width is really small. How do I make a perfect triangle with whatever numbers I want as the width and height?

import turtle

def triangleBuild(width,height):
    turtle.forward(width)
    turtle.left(120)
    turtle.forward(height)
    turtle.left(120)
    turtle.forward(height)

def xYPostion(x,y,width,height):

turtle.penup()
turtle.goto(x,y)
turtle.pendown()

triangleBuild(width,height)
Était-ce utile?

La solution

The height in your case is the distance from the top vertex to the base. And what you are doing is that you are drawing a triangle with 2 sides of the same length (height) You may want to use some math to compute the correct sides length (that may not be equal to the height)

Edit

If you want to draw a triangle just from the width and height, you may want to get the angle of the triangle, then with some math:

Math situation

import turtle
import math

def triangleBuild(width,height):
    l = ( height**2 + (width/2.0)**2)**0.5
    alfa = math.atan2(height, width/2.0) # To compute alfa
    alfa = math.degrees(alfa)
    alfa = 180.0 - alfa 
    turtle.forward(width)
    turtle.left(alfa)
    turtle.forward(l)
    turtle.left(2*(180-alfa))
    turtle.forward(l)

turtle.penup()
turtle.goto(10,20)
turtle.pendown()

width = 200
height = 100
triangleBuild(width,height)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top