In this Python challenge we will write a script to randomly draw confetti on a canvas while ensuring that none of the confetti overlap with each other!
In this challenge we will need to solve the following problems:
- How to draw confetti on screen?
- How to randomly position a confetti on screen?
- How detect if a confetti is overlapping with another confetti?
- How to detect an overlap with any of the confetti already positioned on screen?
- How to randomise the colour of a confetti?
|How to draw confetti on screen?||Using the Python Turtle library we can easily draw circles on the screen.|
|How to randomly position a confetti on screen?||By generating two random numbers representing the x and y coordinates of the confetti. These coordinates will be used in Python Turtle to draw a circle on screen at the right (x,y) location.|
|How detect if a confetti is overlapping with another confetti?||Using Pythagoras formula we can calculate the distance between two confetti.
If this distance is lower than 2*radius of a confetti, then the two confetti are overlapping.
|How to detect an overlap with any of the confetti already positioned on screen?||When a confetti is placed on screen its coordinates will be appended to a list. Each time a new set of coordinates is generated we will iterate through the list of confetti one at a time (using a for loop) to check if an overlap is detected. If so, we will generate a new set of random (x,y) coordinates and repeat this process until no overlap is detected. We will then append this final set of coordinates to the list of confetti.|
|How to randomise the colour of a confetti?||We want all confetti to have a purple shade. To do so we will randomise their colour code using the RGB codes with a random Red value (between 50 and 255), a Green value set to 0, a random Blue value (between 50 and 255).|
Check the Python code for this challenge:
Your Python Challenge
Generate confetti of random sizes (random radius between 10 and 30 pixels).
Adapt your algorithm to make sure these confetti still don’t overlap.
Solution...The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area