Draw Random Hearts
Welcome to Random Hearts
In this lab, you will use a random number generator to scatter heart shapes across your OLED display. Let's build something amazing!
This program uses the MicroPython urandom library to pick random X and Y positions on the display. It then draws a small heart icon at each random position using a grid of 1s (white pixels) and 0s (black pixels).
How the Heart Icon Works
The heart is stored as a 9-by-9 grid of numbers. A 1 means the pixel is on (white). A 0 means the pixel is off (black). The program loops through every row and column of the grid and turns on the right pixels.
This is how many video game sprites (small images) are stored in code.
Key Idea
An image stored as a grid of 1s and 0s is called a bitmap. The heart icon is a 9x9 bitmap. You can draw any small picture this way by replacing 1s and 0s on graph paper.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
What each line does:
HEART = [...]— defines the 9x9 heart bitmap. Each row is a list of 1s and 0s.draw_heart(x_offset, y_offset)— draws the heart by looping through every pixel in the grid.x + x_offsetshifts the heart to the right.y + y_offsetshifts it down.enumerate(HEART)— gives you both the row index (y) and the row data at the same time.urandom.getrandbits(7)— picks a random number with 7 bits. 7 bits can hold values from 0 to 127, which matches the screen width.urandom.getrandbits(6)— picks a random number with 6 bits. 6 bits hold values from 0 to 63, which matches the screen height.for n in range(10)— repeats the process 10 times to draw 10 hearts.oled.show()— sends all 10 hearts to the screen at once.
Monty's Tip
Try changing the number in range(10) to draw more hearts. Try range(50) for a very full screen! Also try calling oled.fill(0) and oled.show() inside the loop to watch hearts appear one at a time.
Watch Out!
Hearts drawn near the right or bottom edge may be clipped. The heart is 9 pixels wide, so drawing at x_offset = 125 would put some pixels off screen. The oled.pixel() function silently ignores pixels outside the screen boundary.
You Can Do This!
Want to make a different shape? Try editing the HEART grid. Replace 1s with 0s and 0s with 1s to invert the shape. Or draw a star or smiley face on graph paper first, then copy the pattern!
Great Work!
You drew random pixel-art icons using a bitmap grid and a random number generator! Next, you will create repeating geometric patterns using math equations.