r/learnpython • u/L_Y_H_ • 30m ago
How come randomly placed drawing don't go to the side of my canva?
Long story short, my assignement is to create a "forest". I already created many functions to draw the trees and a window with a button that allows the user to choose how many trees will be drawn in it. My biggest problem is that I'll have points deducted if the randomly placed trees touch the border. I thought just making sure that my trees coordinates where withing the range that would make them not touch the canva but fr some reason they are always a bit to much to the side and I don't know what to do, because everything I try makes them "escape" the canva. I tried to create a "formula" that'll subtract the width and height of the trees to the x and y coordinates to make sure they don't touch the border but with no success. I thank you guys for any help or advice you might be able to bring!
Here's the relevant code:
from random import*
from turtle import*
from tkinter import*
from math import*
#Screen
screen = Screen()
screen.setup(900,600)
colormode(255)
screen.bgcolor(0, 46, 122)
screen.tracer(0)
hideturtle()
master= screen.getcanvas().master
#Functions needed to make the tree
def triangle(x,y,cote):
penup()
goto(x,y)
pendown()
begin_fill()
colormode(255)
color(25, 87, 5)
for i in range(3):
forward(cote)
left(120)
end_fill()
penup()
def tronc(cote2):
colormode(255)
color(66, 33, 1)
begin_fill()
for i in range(2):
forward(cote2)
right(90)
forward(cote2*1.5)
right(90)
end_fill()
penup()
def sapin():
cote= randint(10,100)
cote_tronc= cote*0.3
#What might be the problem
x=randint(-abs(425-cote),425-cote)#The abs() is there to make sure it stays within
y=randint(-abs(225-ceil(cote*1.1)),225-ceil(cote*1.1))
#The coordinates are purposefully in a range smaller than the canva in an attempt
#to have them not "escape" it.
x2 = x+cote*0.375
penup()
goto(x2,y)
tronc(cote_tronc)
deplacementX= cote*0.085
deplacementY= cote*0.3
for i in range(3):
triangle(x,y,cote)
x += deplacementX
y += deplacementY
cote *= 0.8
def foret(n):
for i in range(n):
sapin()
foret(200)
master.update()
exitonclick()
master.mainloop()