Saturday, January 30, 2021

Python - Higher Order Functions, Instances and States (Day 19)

This is a 100 Days challenge to learn a new language (Python). 100 Days of Code - The Complete Python Pro Bootcamp 

I will post some notes to motivate myself to finish this challenge.


Higher Order Functions



Can a function be passed to another function as an input?

A function is called Higher Order Function if it contains other functions as a parameter or returns a function as an output i.e, the functions that operate with another function are known as Higher Order Functions. Reference

Ex:
# Normal Function
def add(num_1, num_2):
    """add"""
    return num_1 + num_2

# Normal Function
def subtract(num_1, num_2):
    """subtract"""
    return num_1 - num_2

# This is a Higher Order Function
def calculator(num_1, num_2, func):
    """calculator"""
    return func(num_1, num_2)


# Call calculator func and pass add func as an input
# Notice that there is no () after 'add'
result = calculator(1, 2, add)
print(result)



Event Listener in Turtle Graphics 



Using Event Listener of Turtle Graphics to practice how to pass a function as an input.

Ex: Make turtle can move forward and back, and turn left and right
# Import Turtle and Screen Class from turtle module
from turtle import Turtle, Screen


def move_up():
    my_turtle.setheading(90)
    my_turtle.forward(50)


def move_down():
    my_turtle.setheading(270)
    my_turtle.forward(50)


def move_right():
    my_turtle.setheading(0)
    my_turtle.forward(50)


def move_left():
    my_turtle.setheading(180)
    my_turtle.forward(50)


# Get Screen Instance
screen = Screen()
# Bind each functions to key-release event
# of 'Up', 'Down', 'Right' and 'Left' key
screen.onkey(move_up, "Up")
screen.onkey(move_down, "Down")
screen.onkey(move_right, "Right")
screen.onkey(move_left, "Left")
# Set focus on TurtleScreen (in order to collect key-events)
screen.listen()

# Get turtle object
my_turtle = Turtle()

# Bind bye() method to mouse clicks on the Screen.
screen.exitonclick()



Instances and States



Since 'Turtle' class is a blueprint, we can build lots of turtle objects.

                object class
(instance 1)  my_turtle_1 = Turtle()
  (instance 2)  my_turtle_2 = Turtle()


Then in programming, we call my_turtle_1 and my_turtule_2 are separated instance.
Also, each instance (created by the same blueprint) maintains its own state.

my_turtle_1.shape('turtle')
my_turtle_2.shape('arrow')



Challenge - Race Game



Build a turtle race game, and allow users to guess which turtle will win the race?

import random
from turtle import Turtle, Screen

# Get Screen Instance
screen = Screen()

# Pop up a dialog window for input of a number
user_guess = screen.textinput(
    "Guess",
    "Which Turtle will win this race? input color
(red, orange, yellow, green and blue):",
)

turtles = []
colors = ["red", "orange", "yellow", "green", "blue"]
y_positions = [-100, -50, 0, 50, 100]

# Init all turtles
for index in range(0, 5):
    my_turtle = Turtle()
    my_turtle.shape("turtle")
    my_turtle.speed("fastest")
    my_turtle.color(colors[index])
    my_turtle.penup()
    my_turtle.setpos(-250, y_positions[index])
    turtles.append(my_turtle)


game_end = False

while not game_end:
    # make all turtles run randomly
    for index in range(0, 5):
        turtles[index].forward(random.randint(10, 50))

    # terminate race game if at lease one turtle reach finished line
    for index in range(0, 5):
        if turtles[index].xcor() > 250:
            game_end = True

# Custom sorting function to determine the sorting criteria
def my_sort(item):
    """my_sort"""
    return item.xcor()


# Sorting turtles list based on a custom function
# The fastest turtle will be the first element in this list after sorting
turtles.sort(reverse=True, key=my_sort)

# Checking the guess result
if user_guess == turtles[0].pencolor():
    print("You win")
else:
    print(f"You lose, the winner is the {turtles[0].pencolor()} turtle")

# Bind bye() method to mouse clicks on the Screen.
screen.exitonclick()

No comments:

Post a Comment