################################################################################
#                         TP 23 d'informatique - MPSI                          #
#                      Fractales en Tkinter - 23/06/2026                       #
#                                  Correction                                  #
################################################################################

import tkinter as tk
import math
import random

def open_window(W, H, title):
    """open_window(title: str) -> canevas"""
    win = tk.Tk()
    win.focus_force()
    win.protocol("WM_DELETE_WINDOW", win.destroy)
    win.title(title)        # title = nom de la fenêtre
    can = tk.Canvas(win, width=W,  height=H,
                    highlightthickness=0, bd = 0)
    can.pack()
    can.config(bg = "white")
    return can

###

def afficher_pixel(can, p, fill):
    """afficher_pixel( can: canevas, p: (int,int), fill: str)"""
    x,y = p
    can.create_line((x,y), (x+1,y), fill=fill)

################
### Question 3
################

def couleur(c):
    z = 0
    for _ in range(100):
        if abs(z) > 2:
            return "white"
        z = z*z + c
    return "black"

################
### Question 4
################

def affixe(W, H):
    G = [[None for x in range(W)] for y in range(H)]
    for y in range(len(G)):
        for x in range(len(G[y])):
            a = 4/(W-1)*x - 2
            b = 4/(1-H)*y + 2
            G[y][x] = a + 1j * b
    return G

################
### Question 5
################

def mandelbrot(W, H):
    can = open_window(W, H, "Mandelbrot")
    G = affixe(W, H)
    for y in range(H):
        for x in range(W):
            c = G[y][x]
            c = couleur(c)
            afficher_pixel(can, (x,y), c)
    can.mainloop()

### Tests:

# mandelbrot(500, 500)