Confetti Challenge

confettiIn 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!

Problem Decomposition


In this challenge we will need to solve the following problems:

  1. How to draw confetti on screen?
  2. How to randomly position a confetti on screen?
  3. How detect if a confetti is overlapping with another confetti?
  4. How to detect an overlap with any of the confetti already positioned on screen?
  5. How to randomise the colour of a confetti?
Problem Solution
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.
confetti-pythagoraconfetti-overlap-detection
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).

Implementation


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.
confetti-overlap-radius

Share Button
Posted in Computer Science, Python - Advanced, Python Challenges Tagged with: ,

Our Latest Book

Follow this blog