Calculating and Drawing a Triangle - Python Beginner

132 Views Asked by At

Please Please Please help :) The objective of this program is to randomly generate three side lengths of a triangle, check if those side lengths can make a triangle, calculate the angles of the triangle, and then draw the triangle with turtle.

My code runs! But I am having an issue with my logic haha. Because when I draw my triangle, the sides do not connect. I am having trouble pin pointing my problem though. Any help would be really appreciated!!!

Also- Because im randomly generating from a wide range of variables and using the law of cosines to find the angles...I am often getting a math domain error. Would absolute value solve this problem for me? I am a little fuzzy on the math on why im getting this error (a negative value I presume?). I would also like guidance on how and where in my code to fix this. (Im just learning and I dont have a teacher.)

This is my code:

# import statements
import random
import math
import turtle

# set turtle
window = turtle.Screen()
writer = turtle.Turtle()
writer.pensize(3)
writer.pencolor("pink")
writer.pendown

def checkTriangle():
  side1 = random.randint(5,100)
  side2 = random.randint(5,100)
  side3 = random.randint(5,100)

  sum1and2 = side1 + side2
  sum1and3 = side1 + side3
  sum2and3 = side2 + side3

  angle1 = angle(side1, side2, side3)
  angle2 = angle(side2, side3, side1)
  angle3 = angle(side3, side1, side2)

  if side3 <= sum1and2 and side2 <= sum1and3 and side1 <= sum2and3:
    print ("true")
    print(side1, side2, side3)
    print(angle1, angle2, angle3)
    drawTriangle(side1, side2, side3, angle1, angle2, angle3)
    
  else:
    print ("false")

def angle(side1, side2, side3):
  return math.degrees(math.acos((side3**2 - side2**2 - side1**2) /(-2.0 * side1 * side2)))

def drawTriangle(side1, side2, side3, angle1, angle2, angle3):
  writer.forward(side1)
  writer.left(angle3)
  writer.forward(side2)
  writer.left(angle1)
  writer.forward(side3)
  writer.left(angle2)
  
checkTriangle()

Thanks again.

0

There are 0 best solutions below