Test/Python(20220101~)
Days21. 클래스 상속(Class Inheritance), 뱀게임3-먹이 랜덤출력
kiostory
2022. 3. 1. 14:55
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)