Day 024

AWESOMee·2022년 2월 18일
0

Udemy Python Bootcamp

목록 보기
24/64
post-thumbnail

Udemy Python Bootcamp Day 024

Snake Game2.0

Add a High Score to the Snake Game
scoreboard.py

from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0


class Snake:

    def __init__(self):
        self.segments = []
        self.create_snake()
        self.head = self.segments[0]

    def create_snake(self):
        for position in STARTING_POSITIONS:
            self.add_segment(position)

    def add_segment(self, position):
        new_segment = Turtle("square")
        new_segment.color("white")
        new_segment.penup()
        new_segment.goto(position)
        self.segments.append(new_segment)

    def reset(self):
        for seg in self.segments:
            seg.goto(1000, 1000)
        self.segments.clear()
        self.create_snake()
        self.head = self.segments[0]

    def extend(self):
        self.add_segment(self.segments[-1].position())

    def move(self):
        for seg_num in range(len(self.segments) - 1, 0, -1):
            new_x = self.segments[seg_num - 1].xcor()
            new_y = self.segments[seg_num - 1].ycor()
            self.segments[seg_num].goto(new_x, new_y)
        self.head.forward(MOVE_DISTANCE)

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

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

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

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

snake.py

from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 24, "normal")


class Scoreboard(Turtle):

    def __init__(self):
        super().__init__()
        self.score = 0
        self.high_score = 0
        self.color("white")
        self.penup()
        self.goto(0, 270)
        self.hideturtle()
        self.update_scoreboard()

    def update_scoreboard(self):
        self.clear()
        self.write(f"Score: {self.score} High Score: {self.high_score}", align=ALIGNMENT, font=FONT)

    def reset(self):
        if self.score > self.high_score:
            self.high_score = self.score
        self.score = 0
        self.update_scoreboard()

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

main.py

from turtle import Screen, Turtle
from snake import Snake
from food import Food
from scoreboard import Scoreboard
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("My Snake Game")
screen.tracer(0)

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

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.move()

    # Detect collision with food.
    if snake.head.distance(food) < 15:
        food.refresh()
        snake.extend()
        scoreboard.increase_score()

    # Detect collision with wall.
    if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280:
        scoreboard.reset()
        snake.reset()

    # Detect collision with tail.
    for segment in snake.segments[1:]:
        if segment == snake.head:
            pass
        elif snake.head.distance(segment) < 10:
            scoreboard.reset()
            snake.reset()


screen.exitonclick()

Files

file = open("my_file.txt")
contents = file.read()
print(contents)
file.close()

#output
Hello, my name is AWESOMee


The reason need to close the file
Once Python opens up that file, it basically takes up some of the resources of our computer.
And at some point later on, it might decide to close it and free up those resources, but we don't know when that's going to happen and if it will happen.
So, instead, we're going to tell it to close down the file manually using file.close()

with
Instead, what many Python developers opt for is a defferent way of opening the file.
We can use a with keyword. And with we can open the file and then we can open it as whatever it is we decide to name.

with open("my_file.txt") as file:
    contents = file.read()
    print(contents)

No longer have to remember to close our file just by adding some keyword with.
with keyword is going to manage that file directly.

with open("my_file.txt", mode="a") as file:
    file.write("\nNew text.")

my_file.txt
Hello, my name is AWESOMee
New text.

Reand and Write the High Score to a File in Snake
data.txt
0
scoreboard.py

from turtle import Turtle
ALIGNMENT = "center"
FONT = ("Courier", 24, "normal")


class Scoreboard(Turtle):

    def __init__(self):
        super().__init__()
        self.score = 0
        with open("data.txt") as data:
            self.high_score = int(data.read())
        self.color("white")
        self.penup()
        self.goto(0, 270)
        self.hideturtle()
        self.update_scoreboard()

    def update_scoreboard(self):
        self.clear()
        self.write(f"Score: {self.score} High Score: {self.high_score}", align=ALIGNMENT, font=FONT)

    def reset(self):
        if self.score > self.high_score:
            self.high_score = self.score
            with open("data.txt", mode="w") as data:
                data.write(f"{self.high_score}")
        self.score = 0
        self.update_scoreboard()

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

Absolute File Path & Relative File Path

The absolute file path is basically a path that starts from the orgin, the route of the computer storage system.

The main defference between an absolute file path and a relative file path is the absolute file path is always relative to the root of my computer.
The relative file path is relative to my current working directory. So, it depends on where i am and where i am trying to get to.
Depending on the situation and where taht file i am interested in is located, i might decide to use the absolute file path or the relative file path.

.readlines()

f = open("demofile.txt", "r")
print(f.readlines())

#output
['Hello! Welcome to demofile.txt\n', 'This file is for testing purposes.\n', 'Good Luck!']

.replace()

txt = "one one was a race horse, two two was one too."
x = txt.replace("one", "three")
print(x)

#output
three three was a race horse, two two was three too.

.strip()

txt = "     banana     "
x = txt.strip()
print("of all fruits", x, "is my favorite")

#output
of all fruits banana is my favorite


Mail Merge Project

TODO: Create a letter using starting_letter.txt

  • for each name in invited_names.txt
  • Replace the [name] placeholder with the actual name.
  • Save the letters in the folder "ReadyToSend".

PLACEHOLDER = "[name]"

with open("./Input/Names/invited_names.txt") as names_file:
    names = names_file.readlines()

with open("./Input/Letters/starting_letter.txt") as letter_file:
    letter_contents = letter_file.read()
    for name in names:
        stripped_name = name.strip()
        new_letter = letter_contents.replace(PLACEHOLDER, stripped_name)
        with open(f"./Output/ReadyToSend/letter_for_{stripped_name}.txt", mode="w") as completed_letter:
            completed_letter.write(new_letter)

아무리 눈을 씻고 찾아봐도 샘이랑 다른게 없는데 왜 나는 파일 생성이 안되냐고,,,,

엥 근데 완성 파일열려고 하니까 열기전에 갑자기 파일 생성됨... 파이썬 변덕 어떡할거야...? 왜 나랑 밀당하는데...

profile
개발을 배우는 듯 하면서도

0개의 댓글