100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 23 (The Turtle Crossing Capstone Project)
Mike Kameta
Posted on June 15, 2022
- main.py
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
import time
# Screen setup
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("white")
screen.title("Turtle Crossing")
screen.tracer(0)
# Class
player = Player()
car = CarManager()
score = Scoreboard()
# Screen settings
screen.listen()
screen.onkeypress(player.go_up, "Up")
# Game logic
game_is_on = True
while game_is_on:
screen.update()
time.sleep(0.1)
car.create_cars()
car.move_cars()
# (Turtle)Detect wall contact at y_axis (top of the screen), reset to start position
if player.ycor() > 280:
player.reset_position()
score.point()
car.level_up()
# Detect collision with car
for vehicle in car.all_cars:
if vehicle.distance(player) < 20:
game_is_on = False
score.game_over()
screen.exitonclick()
- 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.showturtle()
self.shape("turtle")
self.setheading(90)
self.penup()
self.goto(STARTING_POSITION)
def go_up(self):
new_y = self.ycor() + 20
self.penup()
self.goto(self.xcor(), new_y)
def reset_position(self):
self.goto(STARTING_POSITION)
- car_manager.py
from turtle import Turtle
import random
COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
GO_TO = (280, 0)
STARTING_MOV_DISTANCE = 5
MOVE_INCREMENT = 10
class CarManager:
def __init__(self):
self.all_cars = []
self.car_speed = STARTING_MOV_DISTANCE
def create_cars(self):
random_chance = random.randint(1, 6)
if random_chance == 1:
new_car = Turtle(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)
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
- scoreboard.py
from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 24, "bold")
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.hideturtle()
self.score = 0
self.penup()
self.color("black")
self.update_scoreboard()
def update_scoreboard(self):
self.clear()
self.goto(-205, 260)
self.write(f"Level: {self.score}", align=ALIGNMENT, font=FONT)
def point(self):
self.score += 1
self.update_scoreboard()
def game_over(self):
self.goto(0, 0)
self.write("Game Over", align=ALIGNMENT, font=FONT)
💖 💪 🙅 🚩
Mike Kameta
Posted on June 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Understanding HTTP, Cookies, Email Protocols, and DNS: A Guide to Key Internet Technologies
November 30, 2024