Wednesday, April 20, 2022

Python - Project - Turtle Crossing Game (Day 23)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Project - Turtle Crossing Game





Rule



1. A turtle moves forwards when you press the "Up" key. It can only move forwards, not back, left or right.
2. Cars are randomly generated along the y-axis and will move from the right edge of the screen to the left edge.
3. When the turtle hits the top edge of the screen, it moves back to the original position and the player levels up. On the next level, the car speed increases.
4. When the turtle collides with a car, it's game over and everything stops.


Break down



    1. Move the turtle with keypress
    2. Create and move the cars
    3. Detect the collisions
    4. Detect when turtle reaches the other side
    5. Create a scoreboard


Turtle Crossing Game



player.py
from turtle import Turtle

STARTING_POSITION = (0, -280)
MOVE_DISTANCE = 10
FINISH_LINE_Y = 280
UP = 90


class Player(Turtle):

    def __init__(self):
        """Constructor"""
        super().__init__()

        self.shape("turtle")
        self.penup()
        self.setheading(UP)
        self.go_to_starting_position()

    def go_to_starting_position(self):
        """Reset player's position to its starting position"""
        self.setpos(STARTING_POSITION)

    def go_up(self):
        """Move forward with defined moving distance with its
current heading"""
        self.forward(MOVE_DISTANCE)

    def is_at_finish_line(self):
        """Determine if the player reaches the finish line"""
        if self.ycor() > FINISH_LINE_Y:
            return True

        return False

scoreboard.py
from turtle import Turtle

FONT = ("Courier", 24, "normal")


class Scoreboard(Turtle):

    def __init__(self):
        """Constructor"""
        super().__init__()

        # Attributes
        self.level = 1

        self.hideturtle()
        self.penup()
        self.setpos(-200, 250)
        self.refresh_scoreboard()

    def refresh_scoreboard(self):
        """Show the latest score"""
        self.clear()
        self.write(f"Level: {self.level}", False, align="center",
font=FONT)

    def level_up(self):
        """Increase level and update the display message"""
        self.level += 1
        self.refresh_scoreboard()

    def game_over(self):
        """Show Game Over message"""
        # Move turtle to the center first
        self.setpos(0, 0)
        self.write("Game Over", False, align="center", font=FONT)
       

car_manager.py
import random
from turtle import Turtle


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


class CarManager:

    def __init__(self):
        """Constructor"""

        # Setup Attributes
        self.cars = []
        self.car_speed = STARTING_MOVE_DISTANCE

    def generate_car(self):
        """Generate a car and put it inside cars list"""
        tim = Turtle()
        tim.shape("square")
        tim.shapesize(stretch_len=2)
        tim.penup()
        tim.color(random.choice(COLORS))
        tim.setheading(LEFT)
        tim.setpos(300, random.randint(-250, 250))

        self.cars.append(tim)

    def move(self):
        """Make all cars moving with defined speed"""
        for car in self.cars:
            car.forward(self.car_speed)

    def has_collisions(self, player):
        """Determien if there is a collision between cars and player"""
        for car in self.cars:
            if car.distance(player) < 20:
                return True

        return False

    def level_up(self):
        """Increase car speed"""
        self.car_speed += MOVE_INCREMENT

main.py
import time
import random
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard

# Init Screen
screen = Screen()
screen.setup(width=600, height=600)
# Turn turtle animation on/off and set delay for update drawings.
screen.tracer(0)

player = Player()
carManager = CarManager()
scoreboard = Scoreboard()

# Listen key Up event from screen
screen.onkey(player.go_up, "Up")
screen.listen()

game_is_on = True
while game_is_on:
    time.sleep(0.1)

    # Generate a car by random chance
    if random.randint(1, 6) == 1:
        carManager.generate_car()

    # Move all cars
    carManager.move()

    # If there are collisions
    if carManager.has_collisions(player):
        # Show Game Over message
        scoreboard.game_over()
        # Terminate the game
        game_is_on = False

    # If player reaches to the finish line
    if player.is_at_finish_line():
        # Reset the player's position
        player.go_to_starting_position()

        # Increase car speed
        carManager.level_up()

        # Refresh the scoreboard
        scoreboard.level_up()

    # Perform a TurtleScreen update
    screen.update()

screen.exitonclick()

No comments:

Post a Comment