Kodewick
Start learning →

Python Turtle Birthday Cake

Three layers, cream, lit candles and "Happy Birthday". Set the number of candles to their age and send them the picture.

Python Turtle Birthday Cake
The full code (59 lines)
import turtle
import random

screen = turtle.Screen()
screen.bgcolor("#fff4e6")
t = turtle.Turtle()
t.hideturtle()
t.speed(0)


def box(x, y, w, h, color):
    # a filled rectangle, its bottom left corner at (x, y)
    t.penup()
    t.goto(x, y)
    t.setheading(0)
    t.pendown()
    t.color(color)
    t.begin_fill()
    for side in [w, h, w, h]:
        t.forward(side)
        t.left(90)
    t.end_fill()


# the plate
box(-200, -170, 400, 12, "lightgray")

# three layers, each narrower than the one below
layers = [("#f7c6d9", 320, 90), ("#fbe3a1", 240, 75), ("#c9e8f5", 160, 60)]
y = -158
for color, w, h in layers:
    box(-w / 2, y, w, h, color)
    # cream along the top of each layer
    t.penup()
    for x in range(int(-w / 2) + 10, int(w / 2), 20):
        t.goto(x, y + h)
        t.dot(16, "white")
    y += h

# candles and flames
candles = 5
for i in range(candles):
    x = -60 + i * 120 / (candles - 1) if candles > 1 else 0
    box(x - 5, y, 10, 50, random.choice(["tomato", "deepskyblue", "gold", "orchid"]))
    t.penup()
    t.goto(x, y + 62)
    t.dot(16, "orange")
    t.goto(x, y + 64)
    t.dot(8, "yellow")

# sprinkles
t.penup()
for i in range(60):
    t.goto(random.randint(-150, 150), random.randint(-150, 60))
    t.dot(5, random.choice(["red", "green", "blue", "orange", "purple"]))

t.goto(0, 190)
t.color("#d6336c")
t.write("Happy Birthday!", align="center", font=("Arial", 36, "bold"))

How it is drawn

box(x, y, width, height, color) draws a filled rectangle: the plate, the layers and the candles all use it.

The layers are a list of (color, width, height); for color, w, h in layers draws them upwards, and y += h remembers where the next one starts.

The cream is a white dot every 20 along the top of each layer; a flame is two dots, orange outside and yellow inside.

-60 + i * 120 / (candles - 1) spaces the candles evenly, however many there are.

Questions

Twelve candles are crowded?

They share a width of 120. Click Edit and make it 140, and -60 into -70.

How do I add a name?

Click Edit and change "Happy Birthday!" in write(...) to "Happy Birthday, Sam!".

Try another