인스턴스, 상태 및 고차함수

JOOYEUN SEO·2024년 8월 27일

100 Days of Python

목록 보기
19/76
post-thumbnail

❖ 고차함수&이벤트 리스너

고차함수(Higher Order Functions

  • 다른 함수와 함께 작동하는 함수(다른 함수를 입력으로 받아들이는 함수)
  • 파이썬에서 자주 사용됨
def function_a(something):
	#Do this with something
    #Then do this
    #Finally do this
    
    
def function_b():
    #Do this
    
    
# function_b를 function_a에 입력으로 전달
function_a(function_b)
def add(n1, n2):
    return n1 + n2
def sub(n1, n2):
    return n1 - n2
def mul(n1, n2):
    return n1 * n2
def div(n1, n2):
    return n1 / n2

# 고차함수
def calculator(n1, n2, func):	# 함수 이름만 전달
    return func(n1, n2)			# 함수 실행

result = calculator(2, 3, add)
print(result)
5

함수를 다른 함수의 입력으로 전달할 경우, 끝에 괄호를 붙이지 않고 이름만 전달
(괄호를 사용하면 함수가 바로 실행되는데, 이 경우에는 calculator 안에 들어가서 실행해야 되기 때문)

Turtle Event Listeners
사용자가 키보드 특정 키를 누르는 등의 이벤트가 발생하면 동작할 수 있게 하는 코드

# 사용자가 스페이스 바를 누를 때마다 터틀이 앞으로 10걸음씩 전진
from turtle import Turtle, Screen

tim = Turtle()
screen = Screen()


def move_forward():
    tim.forward(10)

# screen 객체를 통해 이벤트를 듣기 시작
screen.listen()

screen.onkey(key="space", fun=move_forward)
screen.exitonclick()

특정 이벤트 발생 시 특정 함수를 실행시켜야 하는 경우, 고차함수가 유용하게 사용됨

🐢 터틀 과제: 에치 어 스케치 앱

터틀을 위/아래 방향으로 움직이고, 시계/반시계 방향으로 돌리며 그림을 그리는 게임

🔍 유의 사항

  • 키 설정
    • W = Forwards
    • S = Backwards
    • A = Counter-Clockwise
    • D = Clockwise
    • C = Clear Drawing
  • clear() : 터틀이 지금까지 그렸던 것들만 지우고, 터틀의 상태에는 영향 없음
  • reset() : 터틀이 지금까지 그렸던 것들을 지우고, 터틀도 처음 시작 상태로 리셋

⌨️ main.py

from turtle import Turtle, Screen

tim = Turtle()
screen = Screen()


def move_forwards():
    tim.forward(10)

def move_backwards():
    tim.backward(10)

def counter_clockwise():
    tim.left(10)

def clockwise():
    tim.right(10)

def clear_screen():
    tim.reset()


screen.listen()
screen.onkey(key="w", fun=move_forwards)
screen.onkey(key="s", fun=move_backwards)
screen.onkey(key="a", fun=counter_clockwise)
screen.onkey(key="d", fun=clockwise)
screen.onkey(key="c", fun=clear_screen)
screen.exitonclick()

🖍️ 답안

from turtle import Turtle, Screen

tim = Turtle()
screen = Screen()


def move_forwards():
    tim.forward(10)

def move_backwards():
    tim.backward(10)

def turn_left():
    new_heading = tim.heading() + 10
    tim.setheading(new_heading)

def turn_right():
    new_heading = tim.heading() - 10
    tim.setheading(new_heading)

def clear():
    tim.clear()
    tim.penup()
    tim.home()
    tim.pendown()

screen.listen()
screen.onkey(move_forwards, "Up")
screen.onkey(move_backwards, "Down")
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")
screen.onkey(clear, "c")

screen.exitonclick()

❖ 객체 상태 및 인스턴스

인스턴스(instance)

🐢 timmy = Turtle() → 하나의 독립적인 인스턴스
🐢 tommy = Turtle() → 하나의 독립적인 인스턴스

같은 클래스로 만들어낸 객체들은 서로 완전히 독립적으로 기능 = 별개의 인스턴스
(timmy 또는 tommy는 모두 터틀 객체의 예시가 됨)

객체의 상태(state)
여러 개체가 같은 순간에 서로 다른 속성을 지니고, 서로 다른 메소드를 수행하는 것

🗂️ Day19 프로젝트: 터틀레이스 게임

가장 먼저 결승선에 도착할 터틀의 색깔을 두고 내기를 하는 게임

◇ 터틀 좌표계 이해하기

🔍 유의 사항

  • 터틀을 화면에서 가장 왼쪽으로 이동시켜야 함
  • 좌표 이해하기
    1. 터틀은 중앙인 좌표(0, 0)에서 시작
    2. 화면 가로 길이의 절반 = xx좌표의 가장 큰 값
      화면 세로 길이의 절반 = yy좌표의 가장 큰 값
      (나머지 절반은 음수)
    3. 터틀의 xx좌표는 '- 화면 가로 길이의 절반 보다 살짝 오른쪽'
      (너무 딱 맞게 끝까지 가면 터틀이 화면에서 벗어나서 안 보임)
      터틀의 yy좌표는 각 터틀의 위치에 따라 달라짐

⌨️ main.py

from turtle import Turtle, Screen

screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make yout bet!",
                            prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
x_position = -230
y_position = 110

for i in range(6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[i])
    new_turtle.penup()
    new_turtle.goto(x_position, y_position)
    turtles.append(new_turtle)
    y_position -= 40

screen.exitonclick()

◇ 레이싱 시작

🔍 유의 사항

  • 각 터틀은 매 턴마다 0에서 10 사이의 숫자 중 임의의 숫자만큼 앞으로 걸어감
  • 경주는 임의의 터틀이 화면 맨 오른쪽에 도달했을 경우 종료
  • 터틀 객체는 40x40 크기
    • 단순히 화면 가로 길이의 절반 지점 xx좌표를 결승선으로 하면 터틀이 화면을 넘어가버림
    • '전체 화면 가로 길이 - 터틀 객체 폭의 절반' 이 결승선 지점이 됨
  • turtle.color() : pencolor()fillcolor()를 반환
    (터틀의 몸통 색상 = 펜 섹상)

⌨️ main.py

from turtle import Turtle, Screen
import random

is_race_on = False
screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make yout bet!",
                            prompt="Which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
x_position = -230
y_position = 110

for i in range(6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[i])
    new_turtle.penup()
    new_turtle.goto(x_position, y_position)
    y_position -= 40
    turtles.append(new_turtle)

if user_bet:
    is_race_on = True

while is_race_on:
    for turtle in turtles:
        if turtle.xcor() > 230:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print(f"You've won! The {winning_color} turtle is the winner!")
            else:
                print(f"You've lost! The {winning_color} turtle is the winner!")
        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

screen.exitonclick()
You've lost! The yellow turtle is the winner!




▷ Angela Yu, [Python 부트캠프 : 100개의 프로젝트로 Python 개발 완전 정복], Udemy, https://www.udemy.com/course/best-100-days-python/?couponCode=ST3MT72524

0개의 댓글