[파이썬] 방향키를 이용하여 터틀 움직이기 (onkey)

터틀 그래픽에서 나오는 터틀을 키보드 방향키(turtle.onkey)를 눌렀을 때 키입력을 감지하여 터틀 움직이기를 실행할 수 있다.

Table of Contents

키보드의 방향키를 눌러 터틀 움직이기

사용하는 함수

turtle.pensize()
– 터틀이 그리는 선의 두께

스크린샷 2023 10 17 오전 11.05.00 1

turtle.setheading()
– 터틀이 바라보고 있는 각도
EAST : setheading(0)
NORTH : setheading(90)
WEST : setheading(180)
SOUTH : setheading(270)

터틀 움직이기



turtle.listen()
– 키 입력 명령어를 실행하기 위해 사용되는 함수
turtle.onscreenclick(x, y)
– 화면을 클릭 했을 때 함수를 실행한다.

turtle.onkey(x, y)
– 터틀그래픽에서 키를 인식할 수 있는 함수
turtle.stamp()
– 터틀 그래픽에서 터틀 및 도형을 도장 찍듯 화면에 표시해주는 함수

최종 스크립트

import turtle as t
import random

t.speed(0)
t.pensize(5)

colors = ['red', 'blue', 'green', 'purple', 'yellow', 'orange', 'black']


def up():
    t.setheading(90)
    t.forward(100)

def down():
    t.setheading(270)
    t.forward(100)


def left():
    t.setheading(180)
    t.forward(100)

def right():
    t.setheading(0)
    t.forward(100)

def clickleft(x, y):
    t.color(random.choice(colors))


def clickright(x,y):
    t.stamp()


t.listen()

t.onscreenclick(clickleft, 1)
t.onscreenclick(clickright, 3)

t.onkey(up, 'Up')
t.onkey(down, 'Down')
t.onkey(left, 'Left')
t.onkey(right, 'Right')


t.mainloop()


Loading

댓글 남기기