import turtle
import random
## 전역 변수 선언 부분 ##
swidth, sheight, pSize, exitCount = 300, 300, 3, 0
# swidth, sheight : 윈도창의 폭과 높이, pSize : 펜의 두께 준비
# exitCount : 윈도창 밖으로 빠져나간 횟수를 위해서 준비
r, g, b, angle, dist, curX, curY = [0]*7
# r, g, b : 색상, angle과 dist : 임의로 이동할 각도와 거리(몇 칸 갈 건지)
# curX, curY : 현재 거북이의 위치를 지정하는 변수
# [0]*7 : 7개 변수가 모두 0으로 초기화됨
## 메인 코드 부분 ##
turtle.title('거북이가 맘대로 다니기') # 창의 제목
turtle.shape('turtle') # 거북이 모양
turtle.pensize(pSize) # 펜 두께 (3)
turtle.setup(width = swidth + 30, height = sheight + 30) #윈도창 크기(330, 330)
turtle.screensize(swidth, sheight) #안쪽 화면 크기 지정 (300, 300)
while True : # 여기서부터 break행까지 while True : 문장으로 무한 반복
r = random.random()
g = random.random()
b = random.random()
turtle.pencolor((r, g, b)) # 임의의 색상 설정
# rgb값 0에서 1 사이의 랜덤한 값이 들어감
angle = random.randrange(0, 360) # 각도(angle): 0~360 범위에서
dist = random.randrange(1, 100) # 거리(dist)는 1~100 범위에서 임의 추출
turtle.left(angle) # 거북이의 각도 설정 후
turtle.forward(dist) # 거리만큼 이동
curX = turtle.xcor() # x좌표값 (거북이의 현재 위치 구함)
curY = turtle.ycor() # y좌표값
if (-swidth / 2 <= curX and curX <= swidth / 2)
and (-sheight / 2 <= curY and curY <= sheight / 2) :
# 거북이의 현재 위치가 화면 안인지 체크, 터틀 그래픽의 좌표는 중앙이 (0, 0)
pass # pass 실행해서 if문을 그냥 종료하고 다시 while문 수행.
# 이 범위를 벗어난다면 else문 실행
else :
turtle.penup() # 펜 사용하지 않음
turtle.goto(0, 0) # 화면의 중앙으로 이동
turtle.pendown() # 다시 펜 사용
exitCount += 1 # 거북이가 바깥으로 나간 횟수를 하나 증가
if exitCount >= 5 : # 5회 이상 밖으로 나갔다면 break문으로 while문을 빠져나간 후 프로그램 종료
break
turtle.done()