파이썬 Turtle Crossing 게임 만들기

2022. 12. 21. 18:54Trip to Python

내년 부터는 아마 부트캠프를 병행할 계획인데 12월 안에 좀 기초를 끝내고 싶었는데 생각만큼 진도가 나가지 않아서 참 어렵다. 예전 유튜브에서 초보 개발자가 가지지 말아야할 몇 가지를 소개했는데 그 중에 조급함이었다. 그 말을 되새기면서 오늘 배운 내용을 잘 소화해야겠다. 오늘은 Turtle Crossing 게임인데 말 그대로 찻길에 거북이가 잘 지나갈 수 있도록 게임을 만드는 것이다. 지난 배운 내용을 확실하게 복습 시키기위해 반복학습을 하고 있다. 그래서 그런지 조금은 쉬워졌다는 생각이 들었다.

 

1. 화면 세팅

 

from turtle import Screen, Turtle

screen = Screen()
screen.setup(width = 600, height = 600)
screen.tracer(0)


game_is_on = True

while game_is_on:
  time.sleep(0.1)
  screen.update()
    
screen.exitonclick()

- main 파일에 기본 화면 구성을 설정한다.  tracer를 통해서 애니메이션을 끈다.

 

2. 거북이를 만들고, 앞으로 움직이게 만든다. 

 

from turtle import Turtle
STARTING_POINT = (0, -280)
MOVING_DISTANCE = 15

class Player(Turtle):
  
  def __init__():
    super().__init__()
      self.shape("turtle")
      self.penup()
      self.goto(STARTING_POINT)
      
  def move():
  	self.fd(MOVING_DISTANCE)

- player 파일을 파서 거북이에 대한 속성과 앞으로 가는 함수를 작성해준다.

 

from player import Player
from turtle import Turtle, Screen

screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.listen()
player = Player()
screen.onkey(player.move, "Up")

game_is_on = True

while game_is_on:
    time.sleep(0.1)
    screen.update()
    
screen.exitonclick()

- 메인으로 돌아와서 키 설정을 해준다.

 

3. 거북이를 가로막아줄 차를 만들어준다. 차는 화면 우측에서 좌측으로 랜덤으로 발생한다.

 

from turtle import Turtle
import random

COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
FINISH_LINE_Y = 280

class CarManager:

    def __init__(self):
        self.all_cars = []
        
    def create_car(self):
    	new_car = Turtle()
    	new_car.shape("square")
        new_car.color(random.choice(COLORS))
        new_car.shapesize(stretch_wid=1, stretch_len=2)
        new_car.penup()
        random_y = random.randint(-250, 250)
        new_car.goto(300, random_y)
        all_cars.append(new_car)
        
   def  move_cars(self):
   		for car in all_cars:
        	car.backward(10)

- car_manager 파일을 새로 파서 차가 움직이도록 만들어준다. 내가 생각하지 못했던 것은 하나를 만들고 그 것들을 따로 모아서 차를 만드는 것이다. 이 논리를 잘 기억해두어야겠다. 메인 파일에 개체만 만들어주면 차가 생성된다. 이후에는, 거북이와 차가 부딫혔을 때 게임을 종료하고 그 기준을 설정하는 것이다.

 

3. 게임 규칙 설정

 

from turtle import Turtle, Screen
import time
from my_player import Player
from my_car_manager import CarManager
from my_scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.listen()

player = Player()
screen.onkey(player.move, "Up")
car_manager = CarManager()
scoreboard = Scoreboard()

game_is_on = True

while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.create_car()
    car_manager.move_cars()

    for car in car_manager.all_cars:
        if car.distance(player) < 20:
            game_is_on = False

- 맨처음에 생각할 때는 차가 가로로 길기 때문에 x 축 거리하고 y 축으로 부딫치는 거리가 다르니까 따로해야하는 것이 아닌가 생각이 들었는데 그냥 강사님은 일괄적으로 20으로 처리하였다. 조금 더 배우면 이런 미세한 차이까지 잡아내고 싶다.

 

 4. 스코어 보드 만들기

 

from turtle import Turtle
FONT = ("Courier", 10, "normal")


class Scoreboard(Turtle):
    def __init__(self):
        super(Scoreboard, self).__init__()
        self.level = 1
        self.penup()
        self.hideturtle()
        self.goto(-200, 260)
        self.write(f"Level: {self.level}", align="center", font=FONT)

    def level_up(self):
        self.level += 1

    def game_over(self):
        self.goto(0, 0)
        self.write("GAME OVER", align="center", font=FONT)

- 특별할 것이 없다. 귀찮아서 game over도 미리 써두었다.

 

5. 다음 레벨 설정 및 차 속도를 높여 난이도 높이기

 

from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280

class Player(Turtle):

    def __init__(self):
        super().__init__()
        self.penup()
        self.color("black")
        self.shape("turtle")
        self.setheading(90)
        self.go_to_start()

    def go_to_start(self):
        self.goto(STARTING_POSITION)

    def move(self):
        self.fd(MOVE_DISTANCE)

    def is_at_finish_line(self):
        if self.ycor() > FINISH_LINE_Y:
            return True
        else:
            return False

 

- 통과의 기준은 y좌표를 통해서 화면 맨 위로 도착시 다음 레벨로 간다. 다음 레벨로 간다는 것을 레벨의 숫자가 하나 오르고 거북이는 다시 원위치로 가고 차의 속도를 높이는 것이다. player에서는 도착했다는 기준을 설정해주고 시작 지점으로 보내는 함수를 설정한다.

 

from turtle import Turtle
import random

COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
FINISH_LINE_Y = 280

class CarManager:

    def __init__(self):
        self.all_cars = []
        self.car_speed = STARTING_MOVE_DISTANCE

    def create_car(self):
        random_chance = random.randint(1, 6)
        if random_chance == 1:
            new_car = Turtle("square")
            new_car.shapesize(stretch_wid=1, stretch_len=2)
            new_car.color(random.choice(COLORS))
            new_car.penup()
            random_y = random.randint(-250, 250)
            new_car.goto(300, random_y)
            self.all_cars.append(new_car)

    def move_cars(self):
        for car in self.all_cars:
            car.backward(self.car_speed)

    def move_faster(self):
        self.car_speed += MOVE_INCREMENT

    def game_over(self):
        self.car_speed = 0

 

- 속도를 늘려주는 함수를 설정하고 귀찮아서 게임 오버 시 정지하는 함수도 설정하였다. main에서 조건을 달아주고 각 클래스에서 함수를 끌어다 쓰면된다.

 

from turtle import Turtle, Screen
import time
from my_player import Player
from my_car_manager import CarManager
from my_scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
screen.listen()

player = Player()
screen.onkey(player.move, "Up")
car_manager = CarManager()
scoreboard = Scoreboard()

game_is_on = True

while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.create_car()
    car_manager.move_cars()

    for car in car_manager.all_cars:
        if car.distance(player) < 20:
            scoreboard.game_over()
            car_manager.game_over()
            game_is_on = False

    if player.is_at_finish_line():
        player.go_to_start()
        car_manager.move_faster()
        scoreboard.level_up()

screen.exitonclick()

 

- 차를 생성하는 것 빼고는 해볼만 한 프로그램 작성이었다. 좀 할만한 거보니 좀더 어려운 것을 해보고 싶다는 생각이 들었다. 좋은 징조다.