#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: penglaixy
#
# Created: 11/08/2013
# Copyright: (c) penglaixy 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import turtle
state_num = 0
def main():
wn = turtle.Screen()
wn.title("Tess becomes a traffice light!")
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
wn.setup(600,500)
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 whith three states,
#green, orange, red. we number these states 0,1,2
#when the machine changes state, we change tess's position and
#her fillcolor.
#This variable holds the current state of the machine
def bye_bye():
wn.bye()
def advanced_state_machine():
global state_num
if state_num == 0:
tess.forward(70)
tess.fillcolor("orange")
state_num = 1
elif state_num == 1:
tess.forward(70)
tess.fillcolor("red")
state_num = 2
else:
tess.back(140)
tess.fillcolor("green")
state_num = 0
wn.ontimer(advanced_state_machine, 3000)
#bind the event handler to the space key
#wn.onkey(advanced_state_machine, "space")
advanced_state_machine()
wn.onkey(bye_bye, 'q')
wn.listen()
turtle.mainloop()
if __name__ == '__main__':
main()
How to think like a Computer Scientist: 课后习题第九章 第2题
最新推荐文章于 2013-09-18 19:54:43 发布