'프랙탈'에 해당되는 글 1건

  1. 2023.09.15 [Python] 프랙탈 나무 만들기
Coding/Python 삽질기2023. 9. 15. 00:48

오래 전, 라떼 시절 만들었던 파이썬 코드를  Chat GPT를 이용하여 개선해 보았다.

Python 2.X 시절 만든 코드를 3.X로 바꾸면서 저장 기능 까지 추가 하였다.

[원본 코드]

https://chobocho.tistory.com/2460823

 

Fractal Tree

#-*- coding: cp949 -*- from Tkinter import * import math import random RADIAN = math.pi / 180 aColor = [ "brown", "red", "blue", "green", "orange", "black" ] def DrawTree( startX, startY, angle, length, depth ): if depth == 0: return rand=random.random; en

chobocho.tistory.com

 

[개선 코드]

 

from tkinter import *
import math
import random
from PIL import Image, ImageDraw

RADIAN = math.pi / 180


def random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return r, g, b


def draw_tree(start_x, start_y, angle, length, depth, image_draw=None):
    if depth == 0:
        return

    scale = int(depth/12) + 1
    end_x = start_x + length * scale * math.cos(angle * RADIAN)
    end_y = start_y - length * scale * math.sin(angle * RADIAN)

    image_draw.line([start_x, start_y, end_x, end_y], width=depth, fill=random_color())

    draw_tree(end_x, end_y, angle + random.randint(10, 30), length * random.uniform(0.8, 0.9), depth - 1, image_draw)
    draw_tree(end_x, end_y, angle - random.randint(10, 30), length * random.uniform(0.8, 0.9), depth - 1, image_draw)


def draw_new_tree():
    myCanvas.delete("all")  # Clear the canvas

    image = Image.new("RGB", (800, 600), "white")
    image_draw = ImageDraw.Draw(image)
    draw_tree(400, 550, 90, 70, 12, image_draw)
    image.save("fractal_tree.png", "PNG")  # Save the image as PNG

    photo = PhotoImage(file="fractal_tree.png")
    myCanvas.create_image(0, 0, image=photo, anchor=NW)
    myCanvas.photo = photo


if __name__ == "__main__":
    root = Tk()
    root.title("프랙탈 나무")
    root.geometry("800x600")

    myCanvas = Canvas(width=800, height=600)

    draw_button = Button(text="새로운 나무 그리기", command=draw_new_tree)
    draw_button.pack()

    myCanvas.pack()
    root.mainloop()

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] PNG to ICO 변환 하기  (0) 2024.01.04
[Python] Python 소스 코드 빌드 해보기  (1) 2023.09.06
HTTP Protocol  (0) 2023.08.18
Posted by chobocho