Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Python 3.6 Stoplight Class Demo using the Turtle Module
- # by TokyoEdTech
- # www.christianthompson.com
- # Import the turtle module
- # Set up the screen
- import turtle
- wn = turtle.Screen()
- wn.title("Stoplights by @TokyoEdTech")
- wn.bgcolor("black")
- # Create the Stoplight class
- class Stoplight():
- def __init__(self, x, y):
- self.red_light = turtle.Turtle()
- self.yellow_light = turtle.Turtle()
- self.green_light = turtle.Turtle()
- self.red_light.speed(0)
- self.yellow_light.speed(0)
- self.green_light.speed(0)
- self.red_light.color("grey")
- self.yellow_light.color("grey")
- self.green_light.color("grey")
- self.red_light.shape("circle")
- self.yellow_light.shape("circle")
- self.green_light.shape("circle")
- self.red_light.penup()
- self.yellow_light.penup()
- self.green_light.penup()
- self.red_light.goto(x, y + 40)
- self.yellow_light.goto(x, y)
- self.green_light.goto(x, y - 40)
- self.color = ""
- self.pen = turtle.Turtle()
- self.pen.penup()
- self.pen.width(3)
- self.pen.hideturtle()
- self.pen.speed(0)
- self.pen.color("yellow")
- self.pen.goto(x - 30, y + 60)
- self.pen.down()
- self.pen.fd(60)
- self.pen.rt(90)
- self.pen.fd(120)
- self.pen.rt(90)
- self.pen.fd(60)
- self.pen.rt(90)
- self.pen.fd(120)
- # Set the color of the stoplight
- def set_color(self, color):
- self.red_light.color("grey")
- self.yellow_light.color("grey")
- self.green_light.color("grey")
- if color == "red":
- self.red_light.color("red")
- self.color = "red"
- elif color == "yellow":
- self.yellow_light.color("yellow")
- self.color = "yellow"
- elif color == "green":
- self.green_light.color("green")
- self.color = "green"
- else:
- print("Error: Unknown Color")
- # Use a timer to change the stoplight
- def timer(self):
- if self.color == "red":
- self.set_color("green")
- wn.ontimer(self.timer, 2000)
- elif self.color == "yellow":
- self.set_color("red")
- wn.ontimer(self.timer, 2000)
- elif self.color == "green":
- self.set_color("yellow")
- wn.ontimer(self.timer, 1000)
- # Create the first stoplight instance
- stoplight = Stoplight(0, 0)
- stoplight.set_color("red")
- stoplight.timer()
- # Create the second stoplight instance
- stoplight2 = Stoplight(-100, 0)
- stoplight2.set_color("yellow")
- stoplight2.timer()
- # Create the third stoplight instance
- stoplight3 = Stoplight(100, 0)
- stoplight3.set_color("green")
- stoplight3.timer()
- # Start the main events loop
- wn.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement