Python and Turtle Difficulty Level 8,math,random,recursion,Tutorial Tutorial: Drawing Random Mountain Curves with Python Turtle

Tutorial: Drawing Random Mountain Curves with Python Turtle

In this tutorial we are show you how to draw random mountain curves:

Random Mountain Curves

The general idea is to define a recursive function that draw mountain curve given two end points. Pick a random x coordinate value that lies in between two end points and decide the height y for that x coordinate value. Make (x, y) as a new point and call mountain curve function recursively from the first end point to (x, y) and then from (x, y) to the second end point. When two end points are close enough, there is no need to do recursion and draw a line between these two end points.

The question is: how to pick the height value y? The insight come from the value: slope. Assuming that a mountain has maximum slope, then y will have a limited possible ranges given two end points. Starting from the first end point we keep going right and up with the maximum slope and reaches the x-coordinate value x. The y value can’t be larger than the current height. What if we start from the second end point? Using the same argument, you can figure out the lowest possible value for y. The following is the complete code for drawing random mountain curves.

import turtle
import math
import random

screen = turtle.Screen()
screen.setup(1000,1000)
screen.title("Random Mountain Curves - PythonTurtle.Academy")

turtle.hideturtle()
turtle.speed(0)
turtle.pensize(2)
turtle.color('dark green')
MAX_SLOPE = 45
MIN_SLOPE = -45
MIN_HEIGHT = 0
def dist_squared(P1,P2):
    return (P1[0]-P2[0])**2 + (P1[1]-P2[1])**2

def mountain(P1,P2):
    if dist_squared(P1,P2) < 9:
        turtle.goto(P2)
        return
    x1,y1 = P1
    x2,y2 = P2
    x3 = random.uniform(x1,x2)
    y3_max = min((x3-x1)*math.tan(math.radians(MAX_SLOPE)) + y1, (x2-x3)*math.tan(-math.radians(MIN_SLOPE)) + y2)
    y3_min = max((x3-x1)*math.tan(math.radians(MIN_SLOPE)) + y1, (x2-x3)*math.tan(-math.radians(MAX_SLOPE)) + y2)
    y3_min = max(y3_min, MIN_HEIGHT)
    y3 = random.uniform(y3_min,y3_max)
    P3 = (x3, y3)
    mountain(P1,P3)
    mountain(P3,P2)
    return

turtle.up()

turtle.goto(-400,MIN_HEIGHT)
turtle.down()
mountain((-400,MIN_HEIGHT),(400,MIN_HEIGHT))

Try different values for MAX_SLOPE to see what shape the program creates!

Challenge:
Draw Blue Sky, Mountains, and Clouds with Python Turtle

Related Projects:
Random Cloud Generator
Random Mountain Generator
Random City Skyline Generator
Random Island Generator

Related Post