Kodewick
Commencer à apprendre →

Sapin de Noël avec Python Turtle

Trois étages de feuilles, des guirlandes, une étoile au sommet et de la neige tout autour. Changez les nombres et emportez-le.

Sapin de Noël avec Python Turtle
Le code complet (69 lignes)
import turtle
import random

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


def triangle(bottom, width, color):
    # un étage de feuilles : sa base à la hauteur `bottom`, large de `width`
    t.penup()
    t.goto(-width / 2, bottom)
    t.pendown()
    t.color(color)
    t.begin_fill()
    t.goto(width / 2, bottom)
    t.goto(0, bottom + width * 0.6)
    t.goto(-width / 2, bottom)
    t.end_fill()


# le tronc
t.penup()
t.goto(-22, -210)
t.color("saddlebrown")
t.begin_fill()
for side in [44, 60, 44, 60]:
    t.forward(side)
    t.left(90)
t.end_fill()

# trois étages, chacun plus petit que celui du dessous
layers = 3
for i in range(layers):
    triangle(-150 + i * 95, 340 - i * 85, "forestgreen")

# les guirlandes : accrochées dans chaque étage
colors = ["red", "gold", "deepskyblue", "orange", "violet"]
for i in range(layers):
    bottom = -150 + i * 95
    width = 340 - i * 85
    for k in range(8):
        h = random.uniform(10, width * 0.6 - 12)
        half = width / 2 * (1 - h / (width * 0.6))
        t.penup()
        t.goto(random.uniform(-half + 8, half - 8), bottom + h)
        t.dot(12, random.choice(colors))

# l'étoile au sommet
top = -150 + (layers - 1) * 95 + (340 - (layers - 1) * 85) * 0.6
t.goto(-18, top - 6)
t.setheading(0)
t.color("gold")
t.begin_fill()
for i in range(5):
    t.forward(36)
    t.right(144)
t.end_fill()

# la neige
for i in range(80):
    t.goto(random.randint(-300, 300), random.randint(-280, 280))
    t.dot(random.randint(3, 6), "white")

t.goto(0, -275)
t.color("white")
t.write("Joyeux Noël !", align="center", font=("Arial", 28, "bold"))

Comment c'est dessiné

Chaque étage est un triangle plein : triangle(base, largeur, couleur) parcourt ses trois côtés entre begin_fill() et end_fill().

Une boucle for dessine les étages : chacun 95 plus haut et 85 plus étroit.

Les guirlandes sont dans le triangle : on tire une hauteur h, on calcule la largeur du triangle à cette hauteur (half) et on pose un point dans cette largeur.

t.write("Joyeux Noël !", align="center", font=("Arial", 28, "bold")) écrit les vœux centrés sur la tortue.

Questions

Comment changer les vœux ou ajouter un prénom ?

Touchez Modifier, changez le texte dans write(...) dans l'éditeur et relancez.

Pourquoi le milieu de l'étoile est-il vide ?

turtle (Tk) remplit avec la règle pair-impair : le milieu de l'étoile est entouré deux fois et reste vide. Python fait pareil, et cette page aussi.

Essayez-en un autre