-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstate_machine.py
62 lines (52 loc) · 1.61 KB
/
state_machine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import turtle # Tess becomes a traffic light.
turtle.setup(400,500)
wn = turtle.Screen()
wn.title("Tess becomes a traffic light!")
wn.bgcolor("lightblue")
tess = turtle.Turtle()
def draw_housing():
""" Draw a nice housing to hold the traffic lights """
tess.pensize(3)
tess.color("black", "darkgrey")
tess.begin_fill()
tess.forward(80)
tess.left(90)
tess.forward(200)
tess.circle(40, 180)
tess.forward(200)
tess.left(90)
tess.end_fill()
draw_housing()
tess.penup()
# # Position tess onto the place where the green light should be
tess.forward(40)
tess.left(90)
tess.forward(50)
# # Turn tess into a big green circle
tess.shape("circle")
tess.shapesize(3)
tess.fillcolor("green")
# A traffic light is a kind of state machine with three states,
# Green, Orange, Red. We number these states 0, 1, 2
# When the machine changes state, we change tess’ position and
# her fillcolor.
# This variable holds the current state of the machine
state_num = 0
def advance_state_machine():
global state_num
if state_num == 0: # Transition from state 0 to state 1
tess.forward(70)
tess.fillcolor("orange")
state_num = 1
elif state_num == 1: # Transition from state 1 to state 2
tess.forward(70)
tess.fillcolor("red")
state_num = 2
else: # Transition from state 2 to state 0
tess.back(140)
tess.fillcolor("green")
state_num = 0
# Bind the event handler to the space key.
wn.onkey(advance_state_machine, "space")
wn.listen() # Listen for events
wn.mainloop()