Test/Python(20220101~)

Days23. Turtle crossing 게임 2

kiostory 2022. 3. 5. 19:49

1. Move the turtle with keypress

2. Create and move the cars

3. Detect collision with car

4. Detect when turtle reachs the other side

5. Create a scoreboard

 

 

*main.py

import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
car_manager = CarManager()
screen.listen()
screen.onkeypress(player.gogogo, "Up")
game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.create_car()
    car_manager.move_cars()
screen.exitonclick()

 

*car_manager.py

from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager(Turtle):
    def __init__(self):
        self.all_cars=[]
    def create_car(self):
        if random.randint(1, 6) == 1:
            new_car = Turtle("square")
            new_car.shapesize(stretch_wid=1, stretch_len=2)
            new_car.color(random.choice(COLORS))
            new_car.pu()
            random_y = random.randint(-250, 280)
            new_car.setpos(x=300, y=random_y)
            self.all_cars.append(new_car)
    def move_cars(self):
        for car in self.all_cars:
            car.backward(STARTING_MOVE_DISTANCE)

 

*player.py

from turtle import Turtle
STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
class Player(Turtle):
    def __init__(self):
        super().__init__()
        self.color("black")
        self.shape("turtle")
        self.pu()
        self.setpos(STARTING_POSITION)
        self.setheading(90)
    def gogogo(self):
        self.fd(MOVE_DISTANCE)

 

[결과]