Friday, April 22, 2022

Python - Files, Directories and Paths (Day 24)

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.


Open a File



Use the built-in function open()

Ex:
# Use open function to get the file object
f = open("my_file.txt", encoding="utf-8")

# By default the read() method returns the whole text
print(f.read())

# It is a good practice to always close the file
# when you are done with it.
f.close()


Open Mode



r          read only (default)
w        write(override)
a         write(append)
x         create
t          text mode (default)
b         binary mode (return contents as bytes objects without any decoding)


Read



Ex: 'r' is the default mode
# Use open function to get the file object
f = open("my_file.txt", encoding="utf-8")

# readline() will return a line of a file
# When reading input from the stream, if newline parameter is None
# (default), universal newlines mode is enabled.
# Lines in the input can end in '\n', '\r', or '\r\n',
# and these are translated into '\n' before being returned to the caller.
# Then the output for the following line will be 'Hello World!\n'
# We can use end="" parameter for the print function to
# avoid two newline character
print(f.readline(), end="")

# read 2 characters
print(f.read(2))

# read the rest of the current line
print(f.readline(), end="")

# Use for-loop to go through all lines
for line in f:
    print(line, end="")

# Close the file
f.close()


Write



Ex: Use 'a' model to append the file
# Use open function to get the file object
f = open("my_file.txt", mode="a", encoding="utf-8")

f.write("I am here\n")

# Close the file
f.close()


Close a File



From the example above, we cannot guarantee that the file will be closed successfully if there are exceptions when doing the file operations. In order to make sure we closed the file, we can add those file operations under try-finally block.

Ex: Use try-finally block
# Use open function to get the file object
file = open("my_file.txt", encoding="utf-8")

try:
    # Wrap the instructions inside try block
    print(file.read())
finally:
    # Close the file
    file.close()


Now, the code looks complicated.

Then we can use 'with' statement to make it more cleaner.

It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point (Reference).

Ex: 
# Use with statement
with open("my_file.txt", encoding="utf-8") as file:
    print(file.read())
    # NOTE: We don't need to call close() function anymore


Absolute Path V.S. Relative Path



File System:




If we tried to access my_work.txt from main.py:

* Absolute path:
    /Work/my_work.txt

* Relative path:
    ../../my_work.txt

NOTE:
* / means root folder
* ./ means the current folder
* ../ means the parent folder


Project - Refactoring our previous Snake Game



1. Adding highest score to scoreboard.py
2. Make snake game can keep going
3. Save the highest score to the file and load it when app launch


scoreboard.py
from turtle import Turtle

class Scoreboard(Turtle):

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

        # attributes
        self.score = 0
        self.highest_score = self.load_highest_score()

        # init scoreboard
        self.hideturtle()
        self.color("white")
        self.penup()
        self.setpos(0, 280)
        self.refresh_score()

    def increase_score(self):
        """Increase score"""
        self.score += 1

        self.refresh_score()

    def refresh_score(self):
        """Show the latest score on screen"""
        # Delete the turtle’s drawings from the screen.
        self.clear()
        # Write text
        self.write(
            f"Score: {self.score}, Highest Score: {self.highest_score}",
            False,
            align="center",
        )

    def reset(self):
        """Reset scores and update screen"""
        # Update highest score if needed
        if self.score > self.highest_score:
            self.highest_score = self.score
            # Save highest score to our file system
            self.save_highest_score()

        # Reset the score
        self.score = 0

        # Update Screen
        self.refresh_score()

    def load_highest_score(self):
        """Load Highest Score from file"""
        with open("data.txt", mode="r", encoding="utf-8") as file:
            return int(file.read())

    def save_highest_score(self):
        """Save Highest Score to the file"""
        with open("data.txt", mode="w", encoding="utf-8") as file:
            # Make sure to transform it to a string before writing
            file.write(str(self.highest_score))

food.py
import random
from turtle import Turtle

class Food(Turtle):

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

        # Init food
        self.shape("circle")
        self.penup()
        self.color("red")
        self.shapesize(stretch_wid=0.5, stretch_len=0.5)
        self.speed("fastest")

        # refresh food with random position
        self.refresh()

    def refresh(self):
        """Refresh food with new random position"""
        x_position = random.randint(-280, 280)
        y_position = random.randint(-280, 280)
        self.setpos(x_position, y_position)

snake.py
from turtle import Turtle

# Constants
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
OUT_POSITION = (1000, 1000)
MOVING_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0


class Snake:

    def __init__(self):
        """Constructor"""
        # Define an attribute to track snake body
        self.segments = []

        # Call func to init snake
        self.create_snake()

        # Create a attribute instead of using magic number 0
        self.head = self.segments[0]

    def create_snake(self):
        """Adding segment(turtle object) to segments list"""
        for position in STARTING_POSITIONS:
            # add segment with passing position one by one
            self.add_segment(position)

    def add_segment(self, position):
        """Add segment to the end of snake body"""
        segment = Turtle()
        segment.shape("square")
        segment.color("white")
        segment.penup()
        segment.setpos(position)

        self.segments.append(segment)

    def extend(self):
        """Extend the sanke"""
        self.add_segment(self.segments[-1].pos())

    def move(self):
        """Make sanke move with current heading"""
        # Starting from tail, make each segment move to the
# position of the previous segment
        for index in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[index - 1].xcor()
            new_y = self.segments[index - 1].ycor()
            self.segments[index].setpos(new_x, new_y)

        # Using attribute instead of magic number
        self.head.forward(MOVING_DISTANCE)

    def move_up(self):
        """move_up"""
        if self.head.heading() != DOWN:
            self.head.setheading(UP)

    def move_right(self):
        """move_right"""
        if self.head.heading() != LEFT:
            self.head.setheading(RIGHT)

    def move_left(self):
        """move_left"""
        if self.head.heading() != RIGHT:
            self.head.setheading(LEFT)

    def move_down(self):
        """move_down"""
        if self.head.heading() != UP:
            self.head.setheading(DOWN)

    def reset(self):
        """Reset snake"""
        # Move all segments of snake to out of the screen area
        for s in self.segments:
            s.setpos(OUT_POSITION)

        # Clear the tracking attribut
        self.segments.clear()

        # Create a new snake
        self.create_snake()

        # Update snake's head
        self.head = self.segments[0]

main.py
import time
from turtle import Screen
from snake import Snake
from food import Food
from scoreboard import Scoreboard

# Screen Setup
screen = Screen()
screen.setup(width=600, height=600)
screen.title("My Snake Game")
screen.bgcolor("black")
# Turn turtle animation off# Disable screen
screen.tracer(0)

# init
snake = Snake()
food = Food()
scoreboard = Scoreboard()

# Listen events
# Bind fun to key-release event of key
screen.onkey(snake.move_up, "Up")
screen.onkey(snake.move_down, "Down")
screen.onkey(snake.move_right, "Right")
screen.onkey(snake.move_left, "Left")
# Set focus on TurtleScreen (in order to collect key-events)
screen.listen()

game_is_on = True

while game_is_on:
    # Perform a TurtleScreen update# Update Screen
    screen.update()

    # Give some delay for this while loop
    time.sleep(0.1)

    # Keep moving
    snake.move()

    # Check if there is a collision for food
    if snake.head.distance(food) < 15:
        # Increase score
        scoreboard.increase_score()

        # Make snake longer
        snake.extend()

        # Update food position
        food.refresh()

    # Check if there is a collision for wall
    if (
        snake.head.xcor() >= 285
        or snake.head.xcor() <= -285
        or snake.head.ycor() >= 285
        or snake.head.ycor() <= -285
    ):
        # Reset scoreboard
        scoreboard.reset()

        # Reset snake
        snake.reset()

    for segment in snake.segments[1:]:
        if snake.head.distance(segment) <= 15:
            # Reset scoreboard
            scoreboard.reset()

            # Reset snake
            snake.reset()

# Bind bye() method to mouse clicks on the Screen.
screen.exitonclick()


Challenge - Mail Merge



* Generate letters which are ready to send with the correct content, and make them located into Output/ReadyToSend folder.
* The letter content can be found by a template letter template_letter.txt with a placeholder [name].
* Loop through the list of names from invited_names.txt to replace the letter content placeholder.



template_letter.txt
Dear [name],
How are you? Frank

invited_names.txt
Sean Jake Joey Nini

main.py
names = []
letter_with_placeholder = ""

# Read invited_names.txt and append each name to a list
with open("./Input/Names/invited_names.txt") as file:
    for line in file:
        # Use strip() to remove both the leading and the trailing
# characters
        names.append(line.strip())

# Read template_letter.txt
with open("./Input/Letters/template_letter.txt") as file:
    letter_with_placeholder = file.read()

# Loop through all names
for name in names:
    # Use name to replace the placeholder
    letter_with_name = letter_with_placeholder.replace("[name]", name)
    # Use x model to create a new file with the correct content
    with open(
        f"./Output/ReadyToSend/letter_for_{name}.txt",
mode="x"
    ) as file:
        file.write(letter_with_name)

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()

Tuesday, April 19, 2022

Python - Project - Pong Game (Day 22)

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 - Pong Game







Break down the problem:

    1. Create the screen
    2. Create and move a paddle
    3. Create another paddle
    4. Create the ball and make it move
    5. Detect collision with wall and bounce
    6. Detect collision with paddle
    7. Detect when paddle misses
    8. Keep Scores


Design



1. One class for the divider in the middle screen
2. One class for scoreboard for both left and right team
3. One class for paddle for both left and right team
4. One class for ball


Pong Game



divider.py
from turtle import Turtle

DOWN = 270


class Divider(Turtle): 
    def __init__(self, screen_y_range):
        """Constructor"""
        super().__init__()

        self.hideturtle()
        self.color("white")
        self.penup()
        self.setheading(DOWN)
        self.setpos(0, screen_y_range)

        keep_drawing = True
        while keep_drawing:
            self.pendown()
            self.forward(10)
            self.penup()
            self.forward(10)

            if self.ycor() <= screen_y_range * -1:
                keep_drawing = False

scoreboard.py
from turtle import Turtle


class Scoreboard(Turtle):

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

        # Define attributes
        self.team_a_score = 0
        self.team_b_score = 0

        self.hideturtle()
        self.color("white")
        self.penup()
        # Move it down a bit
        self.setpos(0, screen_y_range - 100)
        self.refresh_scoreboard()

    def refresh_scoreboard(self):
        """refresh_scoreboard"""

        self.clear()
        self.write(
            f"{self.team_a_score}    {self.team_b_score}",
            False,
            align="center",
            font=("Arial", 60, "normal"),
        )

    def increase_score_by_team(self, team):
        """Increase team's score and refresh the scoreboard"""
        if team == "a":
            self.team_a_score += 1
        else:
            self.team_b_score += 1

        self.refresh_scoreboard()

    def game_over(self):
        """Show Game Over message"""
        # Move turtle to center first
        self.setpos(0, 0)

        self.write(
            "Game Over",
            False,
            align="center",
            font=("Arial", 60, "normal"),
        )


paddle.py
from turtle import Turtle

# Constants
MOVING_DISTANCE = 50
UP = 90
DOWN = 270


class Paddle(Turtle):

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

        self.shape("square")
        self.shapesize(1.0, 5, 1)
        self.color("white")
        self.penup()
        self.setheading(UP)
        self.setpos(position)

    def move_up(self):
        """Make Paddel mvoe UP"""
        self.setheading(UP)
        self.forward(MOVING_DISTANCE)

    def move_down(self):
        """Make Paddel mvoe DOWN"""
        self.setheading(DOWN)
        self.forward(MOVING_DISTANCE)


ball.py
import random
from turtle import Turtle

STARTING_POSITION = (0, 0)
UP = 90
LEFT = 180
DOWN = 270
RIGHT = 0


class Ball(Turtle):

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

        # Attributes
        self.ball_speed = 0.1

        self.penup()
        self.color("white")
        self.shape("circle")
        self.reset()

    def move(self, move_distance):
        """make ball move forward with current heading"""
        self.forward(move_distance)

    def change_direction(self, heading):
        """change ball's heading"""
        self.setheading(heading)

    def reset(self):
        """reset ball including speed, position and heading"""
        self.ball_speed = 0.1
        self.setpos(STARTING_POSITION)
        new_heading = self.get_random_heading()
        self.change_direction(new_heading)

    def get_random_heading(self):
        """generate an random heading"""
        new_heading = random.randint(0, 360)

        # Avoid weird heading
        while (
            abs(new_heading - UP) <= 10
            or abs(new_heading - LEFT) <= 10
            or abs(new_heading - DOWN) <= 10
            or abs(new_heading - RIGHT) <= 10
        ):
            new_heading = random.randint(0, 360)

        return new_heading

    def bounce(self):
        """bounce from top or bottom wall"""
        current_heading = self.heading()
        new_heading = 360 - current_heading

        self.change_direction(new_heading)

    def pong(self):
        """pong from paddle"""
        current_heading = self.heading()
        new_heading = 540 - current_heading

        self.change_direction(new_heading)

    def speed_up(self):
        """increase ball's speed"""
        self.ball_speed *= 0.8

main.py
import time
from turtle import Screen
from divider import Divider
from scoreboard import Scoreboard
from paddle import Paddle
from ball import Ball

# Constants
MOVE_DISTANCE = 20
OFFSET = 20
SCREEN_X_RANGE = 500
SCREEN_Y_RANGE = 300
POINTS_TO_WIN = 10
TEAM_A_PADDLE_X = SCREEN_X_RANGE * -1 + 100
TEAM_B_PADDLE_X = SCREEN_X_RANGE - 100

# Setup Screen
screen = Screen()
screen.setup(SCREEN_X_RANGE * 2, SCREEN_Y_RANGE * 2)
screen.bgcolor("black")
# Turn turtle animation off
screen.tracer(0)

divier = Divider(SCREEN_Y_RANGE)
scoreboard = Scoreboard(SCREEN_Y_RANGE)
ball = Ball()
paddle_a = Paddle((TEAM_A_PADDLE_X, 0))
paddle_b = Paddle((TEAM_B_PADDLE_X, 0))

# Listen key events on Screen
screen.onkey(paddle_a.move_up, "w")
screen.onkey(paddle_a.move_down, "s")
screen.onkey(paddle_b.move_up, "Up")
screen.onkey(paddle_b.move_down, "Down")
screen.listen()

# Refresh Screen
# Perform a TurtleScreen update. To be used when tracer is turned off.
screen.update()

is_game_on = True

while is_game_on:
    # Give some delay
    time.sleep(ball.ball_speed)

    # Make ball move
    ball.move(MOVE_DISTANCE)

    # Check if the ball touch the wall behind the paddle
    if (
        ball.xcor() + OFFSET >= SCREEN_X_RANGE
        or ball.xcor() - OFFSET <= SCREEN_X_RANGE * -1
    ):
        # Update Scoreboard
        if ball.xcor() + OFFSET >= SCREEN_X_RANGE:
            scoreboard.increase_score_by_team("a")
        else:
            scoreboard.increase_score_by_team("b")

        # Determine if it is game over or not
        if (
            scoreboard.team_a_score == POINTS_TO_WIN
            or scoreboard.team_b_score == POINTS_TO_WIN
        ):
            scoreboard.game_over()
            is_game_on = False
        else:
            # Reset ball
            ball.reset()

            # Add some delay for the new turn
            time.sleep(0.5)

    # Check if the ball touch the paddle
    elif (
        ball.xcor() + OFFSET >=
TEAM_B_PADDLE_X and paddle_b.distance(ball) <= 40
    ) or (ball.xcor() - OFFSET <=
TEAM_A_PADDLE_X and paddle_a.distance(ball) <= 40):
        ball.pong()
        ball.speed_up()

    # Check if the ball touch the top and bottom wall
    elif (
        ball.ycor() + OFFSET >= SCREEN_Y_RANGE
        or ball.ycor() - OFFSET <= SCREEN_Y_RANGE * -1
    ):
        ball.bounce()

    # Refresh Screen
    # Perform a TurtleScreen update.
# To be used when tracer is turned off.
    screen.update()

screen.exitonclick()


Highlight



1. Instead of adding multiple turtle and link together as a paddle, using 'shapesize' of api