파이썬/파이썬(python) 중급

[20-1 파이썬] 뱀 게임 만들기 1(터틀 명령어 재밌게 공부하기) bgcolor(), title(),shape(), xcor(), ycor(),set(x), set(y), goto(x,y), penup(), pendown(), forward(), backward(), tracer(), update()

Olivia-BlackCherry 2022. 8. 28. 12:46

<최종화면>

 

1. 배경색깔, 제목 만들기
2. 뱀 모양(긴 직사각형), 색깔, 시작 위치 지정하기
bgcolor(색깔)

배경 색깔을 지정한다.

 

title(제목)

화면 창의 제목을 지정한다.

<코드>

from turtle import Turtle, Screen

screen = Screen()
screen.setup(height=600, width=600)
screen.bgcolor("black")
screen.title("Snake Game")

screen.exitonclick()

<실행화면>

 

shape(모양)

객체를 생성할 때, 클래스의 argument로 적어주면 

모양이 적용되어 생성된다.

 

color(색깔)

두 종류의 색깔이 지정된다. 

펜색깔와, 채우기색깔

for i in range(3):
    snake = Turtle(shape="square") 
    snake.color(random.choice(color_list))

 

xcor()
ycor()

현재 x좌표, y좌표 알려준다.

print(snake_list[1].xcor())
print(snake_list[1].ycor())

 

set(x) 
set(y)

x좌표, y좌표를 설정한다.

set(x)는

거북이의 첫 번째 좌표를 x로 설정하고, 두 번째 좌표는 변경하지 않습니다.

set(y)는

거북이의 첫 번째 좌표를 y로 설정하고, 두 번째 좌표는 변경하지 않습니다.

snake_list = []
for i in range(3):
    snake = Turtle(shape="square")
    snake.color(random.choice(color_list))
    snake.penup()
    x_pos = snake.xcor() -20*i
    snake.setx(x_pos)
    snake_list.append(snake)

 

goto(x,y)

x,y 좌표로 이동한다.

snake_start = Turtle(shape="square")
snake_start.color("white")

snake_middle = Turtle(shape="square")
snake_middle.color("white")
snake_middle.goto(-20,0)

snake_end = Turtle(shape="square")
snake_end.color("white")
snake_end.goto(-40,0)

또는 

for문으로 묶어서

positions =[(0,0), (-20,0), (-40,0)]
for position in positions:
    snake_end = Turtle(shape="square")
    snake_end.color("white")
    snake_end.goto(position)

 

 

3. 뱀 움직일 때 펜 자국 남지 않도록 만들기
4. 뱀 앞으로 움직이기
5. 애니메이션 구현하기(tracer, update 메소드 활용)
penup()
pendown()

 

펜을 올리면 선이 그어지지 않고

펜을 내리면 선이 그어진다.

snkaes =[]
positions =[(0,0), (-20,0), (-40,0)]
for position in positions:
    snake = Turtle(shape="square")
    snake.color("white")
    snake.penup()
    snake.goto(position)
    snakes.append(snake)

 

 

forward()
backward()
snake.forward(20)

앞으로 가고, 뒤로 가는 메서드이다.

for문을 활용해 

스네일이 계속해서 앞으로 가게 한다.

 

비록 스네일을 start, middle, end로 분리해 만들긴 했지만,

3개가 하나의 스네이크처럼 움직이는 것처럼 보이게

만들고 싶다.

 

그런데 실제로 실행시켜보면

애벌레처럼 따로 분절되어 움직여 아쉽다.

for snake in snakes:
    snake.forward(30)

 

tracer()
update()

먼저

애니메이션이 작동하는 원리에 대해 생각해보자. 

여러 장의 그림을 빠른 속도로 넘기면

그림 속 장면이 움직이는 것처럼 보인다. 

 

그런데 엄청나게 빠른 속도가 아니라면,

방금 전 스네이크가 애벌레처럼 보이듯이

동작이 자연스러워 보이지 않는다.

끊어져서 보인다.

 

대상이 움직이는 모습을

자연스럽게 연결되어 보이게 하고 싶을 때

tracer()와 update()를 사용해보자.

 

tracer()는 입력 값으로 숫자를 넣어서

애니메이션을 켜고, 끌 수 있다.

 

tracer로 애니메이션을 끈 후에,

update() 메소드를 사용해서 프로그램 화면을 보이게 한다.

 

그러면 스네이크 1,2,3가 각각 움직이는 과정은 보이지 않고,

스네이크 1,2,3이 하나로 합쳐진 후 움직이는 화면만 나오게 된다.

그래서 화면이 매우 자연스러워 진다.

 

코드로 구현해보자.

먼저 트레이서를 끈다. 0을 넣으면 꺼진다.

screen.tracer(0)

 

까만 화면만 보인다.

 

원하는 곳에 update() 메소드를 호출해서 화면을 갱신하자.

from turtle import Turtle, Screen
import time

color_list = ["yellow", "red", "blue"]
screen = Screen()
screen.setup(height=600, width=600)
screen.bgcolor("black")
screen.title("Snake Game")

# tracer 끄기
screen.tracer(0)

snakes = []
positions =[(0,0), (-20,0), (-40,0)]
for position in positions:
    snake = Turtle(shape="square")
    snake.color("white")
    snake.penup()
    snake.goto(position)
    snakes.append(snake)

# 5번 앞으로 가기
for i in range(5):
    for snake in snakes:
        snake.forward(30)
        # time.sleep(1)
    # 화면 갱신하기
screen.update()

 

이제 스네이크1,2,3이 한 마리의 뱀이 되어 움직이는 것처럼 보인다.

 

※ 참고. time.sleep

import time

time.sleep(1)​

키워드를 활용하여 뱀이 움직이는 흔적이 보이게 한다.

 

 

 

7. 방향을 바꿔도 스네이크2,3이 스네이크1을 따라오게 만들기

스네이크3 위치가 스네이크2로, 스네이크2 위치가 스네이크1으로 바뀌기

keep_going =True
while keep_going:
    screen.update()
    time.sleep(0.1)
    # 위치 이동
    for index in range(len(snakes)-1, 0, -1): #start=2,stop=1, step=-1
        x = snakes[index-1].xcor()
        y = snakes[index-1].ycor()
        snakes[index].goto(x, y)
    snakes[0].forward(20)

 

index에 따른 좌표 값은 아래와 같이 바뀐다.

# index2 ---> index 1 ----(-20, 0)
# index1 ---> index 0 ----(0, 0)
# index0 앞으로 20 ---->(20,0)

# index2 ---> index1 ----(0,0)
# index1 ---> index0 ----(20,0)
# index0 앞으로 20 ----> (40, 0)

 

 

<최종코드>

from turtle import Turtle, Screen
import time

color_list = ["yellow", "red", "blue"]
screen = Screen()
screen.setup(height=600, width=600)
screen.bgcolor("black")
screen.title("Snake Game")

# tracer 끄기
screen.tracer(0)

snakes = []
positions =[(0,0), (-20,0), (-40,0)]
for position in positions:
    snake = Turtle(shape="square")
    snake.color("white")
    snake.penup()
    snake.goto(position)
    snakes.append(snake)

keep_going =True
while keep_going:
    screen.update()
    time.sleep(0.1)
    # 위치 이동
    for index in range(len(snakes)-1, 0, -1): #start=2,stop=1, step=-1
        x = snakes[index-1].xcor()
        y = snakes[index-1].ycor()
        snakes[index].goto(x, y)
    snakes[0].forward(20)