Intermediate - Instances, State and Higher Order Function
Goal: what we will make by the end of the day
1. we’re going to look at the event listeners, higher order functions, state and multiple instances of an object
2. Sketch game
3. Turtle races game
Python Higher Order Functions & Event Listeners
Challenge: Make an Etch-A-Sketch App
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()
#key-event trigger
screen.listen()
#Key press
screen.onkey(move_forwards, "Up")
screen.onkey(move_backwards, "Down")
screen.onkey(turn_left, "Left")
screen.onkey(turn_right, "Right")
screen.onkey(clear, "c")
#Key-event trigger exit screen
screen.exitonclick()
Object State and Instances
#For example:
timmy (Object) = Turtle() (Class)
tommy(Object) = Turtle() (Class)
#we can create lots of objects from class which created of object called Instance that life cycle is alive until Object to be destroyed
#they can have different attributes and different methods at any time
#State
timmy.color = green
tommy.color = purple
Understanding the Turtle Coordinate System
from turtle import Turtler, Screen
tim= Turtle()
screen= Screen()
#use object to invoke its function that better way is to
#specify variable name and its value for more easy read
screen.setup(width=500, hieght=400)
user_bet= screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")"
turtle - Turtle graphics - Python 3.10.3 documentation