Introduction

Ever wanted the power to change traffic lights to red when you want to cross the road? Well now you can! Well, in the MineCraft world at least..

The Challenge

The aim of this challenge is for you to build a working traffic light on a pole. You should program the lights to turn from green through to red, and then back again, with appropriate time delays in between.

Extensions

  • Build a second traffic light and program it to change at the same time as the first light.
  • Build a road in between the traffic lights.
  • Program the traffic lights to turn to red when your player stands next to the lights.
  • Add a car that moves along the road and stops when the lights are on red….

Step1. Create an empty space for your traffic light

First clear a nice big flat area for your lights, so use the setBlocks function with AIR to create a big open space.

Step2. Create your traffic light

Now create a traffic light pole made out of 5 blocks of wool, in the middle of the flat area.

Step3. Create procedures to turn set the lights on/off

First create a function to turn your lights on/off.

def  turnRedOn():
	mc.setBlock(20,5,20,block.WOOL.id,14)
def turnRedOff():
	mc.setBlock(20,5,20,block.WOOL.id,15)

Now write the rest of the procedures for the other lights?
Can you think of a way of using parameters to improve your code by combining all the above functions in to one function?

def  setLight(colour, state):
	# your function code here...

Step4. Create procedures to create the light transitions.

Now create some more procedures to do the light transitions.

def lightsGo(): # Turns the lights to go.

turnYellowOn()

Wait 2 seconds

turnYellowOff()

turnredOff()

turnGreenOn()

Step 5.  set up a loop to automate your lights

While True:

lightsGo()

Wait 5 seconds

lightsStop()

Wait 5 seconds

Challenge Solution

import minecraft as minecraft
import block
import time

mc = minecraft.Minecraft.create()
mc.setBlocks(0,0,0,100,100,100,block.AIR) # create a nice open space in our world
mc.setBlocks(20,0,20,20,5,20,block.WOOL.id,15) # Create the traffic light pole

def setLight(light,state): #Set individual lights on/off
	if light == "red":
		y = 5
		colour = 14
	elif light == "yellow":
		y = 4
		colour = 4
	elif light == "green":
		y = 3
		colour = 13
	if state == "off":
		colour = 15
	mc.setBlock(20,y,20,block.WOOL.id,colour) #set the block

def lightsGo(): # Change the lights to go
	setLight("red","on")
	setLight("yellow","on")
	time.sleep(2)
	setLight("green","on")
	setLight("yellow","off")
	setLight("red","off")

def lightsStop(): #Change the lights to stop
	setLight("green","off")
	setLight("yellow","on")
	time.sleep(2)
	setLight("red","on")
	setLight("yellow","off")

while True:
	lightsGo()
	time.sleep(5)
	lightsStop()
	time.sleep(5)

 

 

Recommended reading