TIL: Python Basics Day 21 - Class Inheritance

이다연·2021년 1월 1일
0

Udemy Python Course

목록 보기
21/64

Class Inheritance

inheriting from existing class: attribute, method

  • it allows us to take existing class to build on top of it, without having to redefine everything in that class.
class Animal:
	def __init__(self):
    	self.num_eyes = 2
    def breathe(self):
    	print("inhale, exhale")

class Fish(Animal):
	def __init__(self):
    	super().__init__()
        
    def breathe(self):
    	super().breathe()  # inherited  
        print("doing this underwater.")  # and modified
    
    def swim(self):
    	print("Moving in water.")
        
 nemo = Fish()
 nemo.swim()  #Moving in water.
 nemo.breathe() # inhale, exhale/ doing this underwater.
 print(nemo.num_eyes) # 2

Fish is inheriting from Animal class, in order to inherit from Animal, it needs super(), which refers to superclass, Animal

Slicing

num = ["a","b","c","d","e","f","g"]
num[2:5] -> c,d,e (position 2~4)
num[:5] up to position 4 -> abcde
num[2:5:2] last one is increment -> c,e
num[::2] from beginning to end, every 2nd item -> aceg
num[::-1] opposite -> gfedcba

Project: Snake Game (4 steps)

I created a colourful snake.
I've learnt a great deal from playing around with it.

Detect collision with food

Create a scoreboard

Detect collision with wall

Detect collision with tatil

main.py

from turtle import Screen, Turtle
import time
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
import random
from text import Text

LIST_COLOR = ["red", "yellow", "green", "blue", "purple"]
COLOR = random.choice(LIST_COLOR)

text = Text()
screen = Screen()
screen.setup(width= 600, height=600)
screen.bgcolor("black")
screen.title("Snaky Game")
screen.tracer(0)

snake = Snake()
food = Food()
score_board = ScoreBoard()
score_board.write("")



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

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

    #collision with food
    if snake.head.distance(food) < 25:
        food.refresh()
        snake.extend()
        score_board.increase_score()


    #detect collision with wall
    if snake.head.xcor() > 290 or snake.head.xcor() < -290 or snake.head.ycor() > 290 or snake.head.ycor() < -290:
        game_is_on = False
        score_board.game_over()

    #snake collided with its tail
        #trigger gameover
    for segment in snake.segments[1:]:

        if snake.head.distance(segment) < 10:
            game_is_on = False
            score_board.game_over()


screen.exitonclick()

scoreboard.py

from turtle import Turtle
ALIGNMENT = "center"
FONT = ('Courier', 20, 'bold')

class ScoreBoard(Turtle):


    def __init__(self):
        super().__init__()
        self.score = 0
        self.setposition(0, 270)
        self.pencolor("white")
        self.penup()
        self.hideturtle()
        self.update_scoreboard()

    def update_scoreboard(self):
        self.write(arg=f"Score: {self.score} ", move=False, align=ALIGNMENT, font=FONT)

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

    def game_over(self):
        self.goto(0,0)
        self.write(arg=f"GAME OVER", move=False, align=ALIGNMENT, font=FONT)

snake.py

from turtle import Turtle
import random
STARTING_POSTION = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT =0
LIST_COLOR = ["red", "orange", "yellow", "blue", "green", "purple"]

class Snake:
    def __init__(self):
        self.segments = []
        self.create_snake()
        self.head = self.segments[0]
        self.head.color(random.choice(LIST_COLOR))

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


    def add_segment(self, position):
        new_segment = Turtle(shape="square")
        new_segment.color(random.choice(LIST_COLOR))
        new_segment.penup()
        new_segment.goto(position)
        self.segments.append(new_segment)

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

        # 2. move the snake
    def move(self):

            # snake move its body overlaping itself(2nd part's postion becomes 3rd part's new position)
            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)

# 3. Control the snake

    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)

food.py

from turtle import Turtle
import random

class Food(Turtle):
    def __init__(self):
        super().__init__()
        self.shape("circle")
        self.penup()
        self.shapesize(stretch_len=0.5, stretch_wid=0.5)
        self.color("white")
        self.speed("fastest")
        self.refresh()


    def refresh(self):
        random_x = random.randint(-280, 280)
        random_y = random.randint(-280, 280)
        self.goto(random_x, random_y)

profile
Dayeon Lee | Django & Python Web Developer

1개의 댓글

comment-user-thumbnail
2024년 3월 10일

Elevate your well-being at Changwon Thai Massage, where privacy is respected. Our proficient female managers ensure ethical practices. Opt for our business trip massage for a hygienically safe experience, targeting stress reduction and improved sleep. Book now for the ultimate relaxation. 창원출장마사지

답글 달기