[Python] turtle 모듈로 그림 그리기

heering·2022년 2월 20일
0

파이썬

목록 보기
1/1

🐥 우와 신입생이다!

이번 겨울방학 때 2주간 대학교 신입생들을 위한 기초 SW 교육 학부생 조교를 했었다. 파이썬 숙제를 위한 코드를 작성했었는데, 한 번만 쓰고 버리기는 아까워서 여기에 올려보려고 한다. (많이.. 간단하지만 필요한 사람은 분명 있을 거니까)

🐢 거북이 모듈로 그림 그리기 코드

import turtle #거북이 모듈
import math #sqrt() 루트

screen = turtle.Screen()
t = turtle.Turtle()
t.shape('turtle')

def right():
   if not (t.heading() == 0):
       t.setheading(0)
       t.forward(50)
   else:
       t.forward(50)

def up():
   if not (t.heading() == 90):
       t.setheading(90)
       t.forward(50)
   else:
       t.forward(50)

def left():
   if not (t.heading() == 180):
       t.setheading(180)
       t.forward(50)
   else:
       t.forward(50)

def down():
   if not (t.heading() == 270):
       t.setheading(270)
       t.forward(50)
   else:
       t.forward(50)

def upLeft():
   t.setheading(135)
   t.forward(math.sqrt(2) * 50)

def upRight():
   t.setheading(45)
   t.forward(math.sqrt(2) * 50)

def downLeft():
   t.setheading(-135)
   t.forward(math.sqrt(2) * 50)

def downRight():
   t.setheading(-45)
   t.forward(math.sqrt(2) * 50)

def penUp():
   t.penup()

def penDown():
   t.pendown()

def black():
   t.color('black')

def red():
   t.color('red')

def green():
   t.color('green')

def undo_button():
   t.undo() #Esc키

def drawing():
   t.screen.onkeypress(up, 'Up')
   t.screen.onkeypress(down, 'Down')
   t.screen.onkeypress(right, 'Right')
   t.screen.onkeypress(left, 'Left')

   t.screen.onkeypress(undo_button, 'Escape')

   t.screen.onkeypress(upLeft, 'q')
   t.screen.onkeypress(upRight, 'e')
   t.screen.onkeypress(downLeft, 'z')
   t.screen.onkeypress(downRight, 'c')

   t.screen.onkeypress(penUp, '0')
   t.screen.onkeypress(penDown, '9')

   t.screen.onkeypress(black, '1')
   t.screen.onkeypress(red, '2')
   t.screen.onkeypress(green, '3')
   t.screen.listen()

#시작

drawing()

t.screen.title('"0": penUP, "9": penDOWN, #1: black, #2: red, #3: green, ESC: return')
t.screen.mainloop()

마음대로 그려본 결과물은 대강 이렇게 ㅎㅎ 😆

🙄 설명해주세요

실행창 제목에 내가 만들어둔 키가 헷갈려서 적어두었다.

펜을 up하면 거북이를 움직여도 그림을 그리지 않는다. → t.penup()
펜을 down하면 거북이를 움직이면 그림을 그린다. → t.pendown()

거북이를 움직이기 위해 키를 지정해줬다. → t.screen.onkeypress(함수명, '키보드의 키')

이 프로그램에서 거북이는 총 8가지 방향으로 움직일 수 있다.
이를 위해서는 거북이의 머리 방향과, 거북이가 한 번에 얼마나 전진하는지를 지정해줘야 한다.
: 머리 방향 → t.setheading(각도)
: 얼마만큼 전진 → t.forward(길이)

0개의 댓글