TIL: Python Basics Day 23 - Turtle Crossing Game

이다연·2021년 1월 4일
0

Udemy Python Course

목록 보기
23/64
post-thumbnail

Turtle Crossing Game

class, inheritance, using turtle graphics.

I struggled with
step2. generating cars
step3. speeding up cars when levelup

1. Why car manager is not inheriting directly from turtle.

-> car manager class itself doesn't need turtle's methods.

-it has create_car(inherited from turtle), move_cars, speed_up(level_up) methods
-speed_up(): screen updates every 0.1 sec, turtle moves a certain distance with goto() or forward(), to move farther in a same time, it should move faster. -> thats how we creates 'speed'. / goto(original coordinate + additional distance), forward(distance) needs
-carmanager class creates one car at a time and add it on to the all_cars list. Use for loop to loop through all the items in the list with move()
-init holds empty list(class's attribute = variable) 'all_cars' as a starting value self.all_cars = []
(Attribute: variable that's associated with an object.)


2. why speed control is different from pong game's ball case.

How to add speed on a ball at Pong game:

new_x = xcor() + additional distance(self.x_move = 10 -> set variable on init)
new_y = ycor() + additional distance
goto(new_x, new_y)

How to add speed on a car at Turtle Crossing game:

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

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

-> Difference btw goto() and forward()

  • forward: Move the turtle forward by the specified distance, in the direction the turtle is headed
    -it can be used with setheading(angle) to change the direction.
    (wherever within the radius)
  • goto: Move turtle to an absolute position. If the pen is down, draw line. Do not change the turtle’s orientation
    -used to set its first coordinate.(fixed position)

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()
scoreboard = ScoreBoard()

screen.listen()
screen.onkey(player.move_up, "Up")

game_is_on = True
while game_is_on:
    time.sleep(0.1)
    screen.update()
    car_manager.create_car()
    car_manager.move_cars()
    
    # Detect player collision with car
    for car in car_manager.all_cars:
        if player.distance(car) <25:
            scoreboard.game_over()
            game_is_on = False
            screen.exitonclick()

	#safely reached to a finish line
    if player.finishline():
        player.go_to_start()
        car_manager.speed_up()
        scoreboard.score_up()

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.shape("turtle")
        self.setheading(90)
        self.penup()
        self.goto(STARTING_POSITION)


    def move_up(self):
        new_y = self.ycor() + MOVE_DISTANCE
        self.goto(self.xcor(), new_y)

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

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

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:
    def __init__(self):
        self.all_cars = []   #cant' understand
        self.car_speed = STARTING_MOVE_DISTANCE

    def create_car(self):
        random_chance = random.randint(1, 6)  #probability 1 out of 6
        if random_chance == 1:
            new_car = Turtle("square")
            new_car.color(random.choice(COLORS))
            new_car.penup()
            new_car.turtlesize(stretch_wid=1, stretch_len=2)
            random_y = random.randint(-250, 250)
            new_car.goto(300, random_y)
            self.all_cars.append(new_car)  # can't understand

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

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

scoreboard.py

from turtle import Turtle
FONT = ("Courier", 24, "normal")
OVER_FONT = ("Courier", 60, "bold")


class ScoreBoard(Turtle):
    def __init__(self):
        super().__init__()
        self.color("black")
        self.penup()
        self.hideturtle()
        self.score = 1
        self.update_scoreboard()

    def update_scoreboard(self):
        self.clear()
        self.goto(0, 260)
        self.write(f"Level: {self.score}", align="center", font=FONT)

    def score_up(self):
        self.score += 1
        self.update_scoreboard()

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

profile
Dayeon Lee | Django & Python Web Developer

5개의 댓글

comment-user-thumbnail
2022년 7월 13일

I can't call myself a fan of computer games. If I choose any game, then I try to find something that will also benefit me. For example, online casinos and gambling. If you also want to try online casinos, then I recommend to you to click for tips here. It seems to me that when you start gambling, then advice can always be very helpful.

답글 달기
comment-user-thumbnail
2023년 11월 30일

In the Turtle Crossing Game, the decision to not directly inherit from the Turtle class for the CarManager aligns with the principle of separation of concerns. The CarManager doesn't need the full range of Turtle's methods; it focuses on managing cars. By implementing create_car, move_cars, and speed_up methods, it maintains a clear, specific purpose separate from the broader functionalities of the Turtle class.

Regarding speeding up cars during level-up, the logic lies in updating their movement parameters. As the game progresses, adjusting the speed by altering the distance covered per time interval amplifies the challenge.

In the realm of gaming, if you're looking for a unique experience, consider trying Golden Tee Golf on your PC. It offers a captivating virtual golfing experience that might pique your interest!
https://www.emulatorpc.com/onmyoji-arena/

답글 달기
comment-user-thumbnail
2024년 1월 12일

On Python Basics Day 23, enthusiasts dove into the exhilarating world of game development with the creation of a Turtle Crossing Game. Participants honed their skills in Python programming, utilizing the Turtle graphics library to craft a dynamic and engaging gaming experience. As they navigated the complexities of coding, the term 총판장 resonated as a symbol of collaboration and shared knowledge among the gaming community, adding an extra layer of excitement to the learning process.

답글 달기
comment-user-thumbnail
2024년 4월 8일

The Turtle Crossing Game is a delightful adventure where players guide turtles safely across treacherous terrain. With stunning graphics and engaging gameplay, it's a hit among all ages. But what truly sets it apart is its commitment to fairness and trustworthiness. Partnering with reputable developers, the game ensures a secure environment for all players. It's a testament to the dedication of its creators to uphold integrity and provide an enjoyable experience. In a world where trust is paramount, this game stands out as a beacon of reliability. Indeed, it's a prime example of nhà cái uy tín a reputable gaming platform.

답글 달기
comment-user-thumbnail
2024년 4월 17일

If you have difficulties with any game, such as Helldivers 2, which I've been hearing a lot about lately, you can always use paid but still completely legal and safe services like helldivers 2 power leveling services. Here https://leprestore.com/helldivers-2/services/powerleveling/ has more information about professional player services and on top of that 24/7 tech support that will answer all questions and even offer unique solutions.

답글 달기