Test/Python(20220101~)

Dats23. Turtle crossing 게임 4

kiostory 2022. 3. 5. 20:42

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.gogoup, "Up")
screen.onkeypress(player.gogodown, "Down")
game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.create_car()
    car_manager.move_cars()
    # Detect collision with cars
    for car in car_manager.all_cars:
        if car.distance(player) < 20:
            game_is_on = False
    # Detect successful crossing
    if player.reach_the_goalline():
        player.go_to_start()
        car_manager.level_up()
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=[]
        self.car_speed = STARTING_MOVE_DISTANCE
    def create_car(self):
        if random.randint(1, 5) == 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(self.car_speed)
    def level_up(self):
        self.car_speed += MOVE_INCREMENT

 

*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.go_to_start()
        self.setheading(90)
    def gogoup(self):
        self.fd(MOVE_DISTANCE)
    def gogodown(self):
        self.bk(MOVE_DISTANCE)
    def go_to_start(self):
        self.setpos(STARTING_POSITION)
    def reach_the_goalline(self):
        if self.ycor() > FINISH_LINE_Y:
            return True
        else:
            return False