Random Background Generator

artillery-gameIn this challenge we will use a Python script (using Python Turtle) to generate a random background for a 2D video game.

artillery-game-background

To create a mountain range skyline we will use two different approaches:

  1. Using a polynomial function
  2. Using a composite sine wave function

Using a Polynomial Function

Polynomial Function of Degree 2

Polynomial Function of Degree 2

Polynomial Function of Degree 3

Polynomial Function of Degree 3

Polynomial Function of Degree 4

Polynomial Function of Degree 4

Polynomial Function of Degree 5

Polynomial Function of Degree 5

Polynomial Function of Degree 6

Polynomial Function of Degree 6

Polynomial Function of Degree 7

Polynomial Function of Degree 7

 

In our example (see trinket below) we will use a polynomial function of degree 3:

y = a*x3 + b*x2 + c*x + d

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.

Python Code


Your Challenge


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)

Extension Task


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:

Did you like this challenge?

Click on a star to rate it!

Average rating 4.2 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: ,