Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main


Python


C++
JAVA
PHP
SQL
Assignments

Turtle


036_WobblyLines.py

import math
import random
import os
from palettes import randomPalette
from util import getTurtleAndScreen
# Wobbly Lines
# CAC, 4/12/2023
MIN_DIST = 10
FORWARD_LENGTH = 20
MAX_ANGLE = 20
def dist(x,y,x2,y2):
    return math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2))

def drawWobblyLine(turtle, x, y, x2, y2):
    turtle.penup()
    turtle.goto(x,y)
    turtle.pendown()

    xn,yn=turtle.pos()
    while dist(xn,yn,x2,y2) > MIN_DIST:
        angle = turtle.towards(x2,y2)
        angle = angle + random.uniform(-MAX_ANGLE,MAX_ANGLE)
        turtle.setheading(angle)
        length = random.uniform(FORWARD_LENGTH/2,FORWARD_LENGTH)
        turtle.forward(length)
        xn,yn=turtle.pos()
    turtle.goto(x2,y2)

def Draw():
    width = 800
    height = 600
    title = "Wobbly Lines"
    filename = os.path.basename(__file__)[0:-3]
    turtle, screen = getTurtleAndScreen(title,width,height,filename,moveWorld=True)

    colors = randomPalette()
    bg = random.choice(colors)
    colors.remove(bg)
    screen.bgcolor(bg)
    turtle.pensize(2)

    for i in range(40):
        x = random.randint(0,width)
        y = random.randint(0,height)
        x2 = random.randint(0,width)
        y2 = random.randint(0,height)
        turtle.color(random.choice(colors))
        drawWobblyLine(turtle,x,y,x2,y2)

    screen.mainloop()
# ----------------------------------------------------------------
if __name__ == '__main__':
   Draw()