프로그램

[파이썬] 문제 : 터틀(turtle) H 형태로 그리기

오디세이99 2023. 5. 17. 15:38
728x90
반응형

import turtle

# turtle.colormode(255)       # 색을 RGB로 하도록 지정
turtle.bgcolor('blue')
t = turtle.Turtle()           # 터틀
t.shape('classic')
t.hideturtle()
t.speed(10)                  # 속도 빠르게

def draw_H(x, y, length, depth):    # 그리는 함수. x,y 좌표. length=선의 길이, 몇번쨰까지 그릴 것인지
    # print(x, y, length, depth)
    pos = []                        # H 에서 각 꼭지점의 x,y 위치
    if depth == 3:                  # depth=3 이면 종료
        return 0

    t.penup()
    t.goto(x, y)
    t.pendown()
    
    t.pencolor('skyblue')   # 색 지정
    t.width(4)              # 선 두께
    
    t.setheading(0)         # 방향 초기화. 좌상
    t.left(180)
    t.forward(length)       # 선 그리기
    t.right(90)
    t.forward(length)       # 선 그리기   
    pos.append([t.xcor(), t.ycor()])     # 현재 위치 저장
    
    t.left(180)                          # 좌하
    t.forward(length*2)
    pos.append([t.xcor(), t.ycor()])
    
    t.penup()                            # 가운데로 이동
    t.goto(x, y)
    t.pendown()
    
    t.setheading(0)                       # 우상
    t.forward(length)
    t.left(90)
    t.forward(length)
    pos.append([t.xcor(), t.ycor()])
    
    t.left(180)                           # 우하
    t.forward(length*2)
    pos.append([t.xcor(), t.ycor()])

    for xy in pos:                       # 4개의 꼭지점 마다 그리기 함수 자기 자신 실행
        draw_H(xy[0], xy[1], int(length/2), depth+1)   # length의 절반씩 줄여감. deppth는 +1 씩 늘려감
    
length = 100              # 원 반지름 지정
depth = 0
x = 0
y = 0
draw_H(x, y, length, depth)

turtle.done()

try:
    turtle.bye()
except:
    print("bye")

728x90
반응형