In this challenge we will use a Python script (using Python Turtle) to generate a random background for a 2D video game.
To create a mountain range skyline we will use two different approaches:
- Using a polynomial function
- Using a composite sine wave function
Using a Polynomial Function
In our example (see trinket below) we will use a polynomial function of degree 3:
The coefficients a,b,c,d of our polynomial function will be randomly generated. This will hence create a different background/skyline every time the program is executed.
We will then use this function to place some trees on the skyline. The x coordinate of the tree will be randomly generated whereas the polynomial equation will be used to calculate the y coordinate of each tree.
Update this code to add another set of trees. The trees could be positioned randomly anywhere on the grass area of the landscape. (Anywhere between the bottom of the screen and the skyline)
Update this code to add some clouds. The clouds should be positioned randomly anywhere in the sky. (Anywhere between the top of the screen and the skyline)
Alternative Approach… Using a composite sine wave
Instead of using a polynomial function we could use a composite sine wave function. You may find this solution either to implement especially when generating several peaks and peats.
A composite sine wave function is a combination of two simple sine waves with different frequency, phase and amplitude.
Here is the equation of a simple sine wave function:
A sine wave is too predictable/repetitive to create an interesting background. We will therefore create a composite function to generate peaks and heaps of different amplitudes.
To create a composite sine wave function we will use two functions as follows:
Here is our demo: