티스토리 뷰

Class 'Fish'는 'Animal'을 상속받는다. super는 상위 class 'Animal'을 가리키며, 상위 class가 'Fish' 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()         # 상위 class의 method는 그대로 계승하면서
        print("doing this underwater.")         # 프린트하는 별개 기능을 추가할 수 있음
    def swim(self):
        print("moving in water.")
nemo = Fish()
nemo.breathe()    
nemo.swim()

[ 실행 결과 ]

Inhale, exhale.                             --> 상속받은 부분
doing this underwater.                  --> 추가한 부분
moving in water.                         --> 신규 method swim

 

 

-------------------------------------- 먹이 랜덤 출력까지 완성한 뱀게임 ---------------------------------------

* main.py

from turtle import Screen, Turtle
from snake import Snake
from food import Food
import time
screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.tracer(0)
screen.title("kio's snake game - ver.20220223(e first one)")
snake = Snake()
food = Food()
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) < 20:
        food.refresh()
screen.exitonclick()

 

* snake.py

from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
COLOR = ["red", "orange", "yellow", "green", "blue", "navy", "purple"]
MOVING_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake:
    def __init__(self):
        self.turtles = []
        self.create_snake()
        self.head = self.turtles[0]
    def create_snake(self):
        color_index = 0
        for pos in STARTING_POSITIONS:
            new_turtle = Turtle(shape="square")
            new_turtle.color(COLOR[color_index])
            new_turtle.pu()
            new_turtle.setpos(pos)
            color_index += 1
            self.turtles.append(new_turtle)
    def move(self):
        for tut_num in range(len(self.turtles)-1, 0, -1):          #(start=2, stop=0, step=-1)
            new_x = self.turtles[tut_num - 1].xcor()
            new_y = self.turtles[tut_num - 1].ycor()
            self.turtles[tut_num].goto(new_x,new_y)
        self.head.fd(MOVING_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)

 

* food.py

from turtle import Turtle
import random
class Food(Turtle):
    def __init__(self):
        super().__init__()
        self.shape("circle")
        self.pu()
        self.shapesize(stretch_wid=0.5, stretch_len=0.5)  #default 20by20에서 0.5를 입력하였으니, 10by10 크기가 됨
        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)
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함