TIL: Python Basics Day 19 - Function as an input, Turtle Race

이다연·2020년 12월 28일
0

Udemy Python Course

목록 보기
19/64

Function as an input

you don't want to add parentheses when using function as a parameter
e.g. screen.onkey(function, "Up")


def add(n1, n2):
    return n1 + n2
    
def calculator(n1, n2, func):
    return func(n1, n2)
    
result = calculator(2,3,add)
print(result)

Higher Order Function: Calculator
Even listeners

Project. Turtle Race

Each coloured turtles are instances, which were created from class Turtle() in a for loop. They had different attributes such as colours and speeds. Their state was different in terms of attritubes and methods.

from turtle import Turtle, Screen, color
import random

screen = Screen()
screen.setup(width = 500, height = 480)

user_bet = screen.textinput(title="Make your bet", prompt="which turtle will win the race? Enter a color: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
all_turtles = []

is_race_on = True

for num in range(6):
    turtle = Turtle(shape="turtle") #Creating Objects 
    turtle.color(colors[num])
    turtle.penup()
    turtle.goto(x=-230, y=-150 + num*70)
    all_turtles.append(turtle)


if user_bet:
    is_race_on = True

while is_race_on:
    for turtle in all_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("you lose.")

        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

screen.exitonclick()
profile
Dayeon Lee | Django & Python Web Developer

0개의 댓글