My turtle
Using onscreenclick function
![]()
Task: Build the tree with onscreenclick
Code:
from turtle import * from random import * setup(800,600) bgcolor('light blue') title("Onclick Tree") tracer(0, 0) color("brown") left(90) minAngle = 25 maxAngle = 90 minLength = 30 maxLength = 45 minBranches = 2 maxBranches = 6 def tree(depth, branches, size, angle): # Terminate at leaf or randomly if depth < 1 or branches < 1 or random() < 0.1: color("green") right(90) circle(2) left(90) color("brown") return # Set stroke thickness width(depth) # Draw root/trunk forward(size) # Turn to leftmost branch left(0.5 * angle) for i in range(branches): # Turn to branch angle if branches > 1: right(i * angle / (branches - 1)) # Draw next depth tree tree(depth - 1, randint(minBranches, maxBranches), randrange(minLength, maxLength), randrange(minAngle, maxAngle)) # Turn back to centre angle if branches > 1: left(i * angle / (branches - 1)) # Turn back to center right(0.5 * angle) # Return to start of root backward(size) def move(x,y): penup() goto(x,y) pendown() def f(x,y): move(x,y) color('brown') tree(6, randint(minBranches, maxBranches), randrange(minLength, maxLength), randrange(minAngle, maxAngle)) update() def ground(wid, high): fillcolor('light green') goto(-wid, -high/2) begin_fill() setheading(0) forward(wid*2) setheading(90) forward(high/2) setheading(180) forward(wid*2) setheading(270) forward(high/2) end_fill() def sun (sx, sy): move(sx, sy) color("yellow") rd =50 ang = 0 for i in range(50): dis = randint(10, 100) ang = ang + 15 pensize(2) setheading(ang) forward(dis) backward(dis) dot(rd) setheading(90) penup() goto(-400, -300) ground(800, 600) setheading(90) onscreenclick(f,1) onscreenclick(sun,3) done()
2026-07-10 08:48:22
Comments
No comments yet. Be the first to leave one!
Leave a Comment