Skip to content

Instantly share code, notes, and snippets.

@darrylsloan
Created February 15, 2019 09:00
Show Gist options
  • Save darrylsloan/b69111ad02c097ddef962009f7ff3760 to your computer and use it in GitHub Desktop.
Save darrylsloan/b69111ad02c097ddef962009f7ff3760 to your computer and use it in GitHub Desktop.
Chess clock for the BBC micro:bit, user-programmable for games of 1 to 25 mins per player.
# CHESS CLOCK by Darryl Sloan, 11 February 2019
# Press A repeatedly to choose the desired play time (1 LED = 1 min).
# Press B to start the clock.
# White player presses A after each move.
# Black player presses B after each move.
# Optional extra: if a speaker is attached, a tone sounds when time is up.
from microbit import *
import music
# Function to display time (1 LED = 1 min; brightness of final LED indicates seconds remaining)
def show_timer(secs):
# Display full minutes
x, y = 0, 0
for i in range(0, int(secs/60)):
display.set_pixel(x, y, 9)
x += 1
if x == 5:
x = 0
y += 1
# Display remaining seconds in current minute as brightness level
remainder = secs
while remainder >= 60:
remainder -= 60
if remainder > 0:
display.set_pixel(x, y, int(remainder/6))
# Player selects time
display.scroll("SET TIMER")
timer = 60
while True:
show_timer(timer)
if button_a.was_pressed():
timer += 60
if timer == 26*60:
timer = 60
display.clear()
if button_b.was_pressed():
break
# Reset variables
player_time = [0, 0]
time_marker = [timer, timer]
current_player = 0
while True:
# Start of current move, mark the time
now = running_time()
# Arrow points to current player
if current_player == 0:
display.show(Image.ARROW_E)
sleep(100)
display.show(Image.ARROW_SE)
sleep(100)
display.show(Image.ARROW_S)
sleep(100)
display.show(Image.ARROW_SW)
sleep(100)
display.show(Image.ARROW_W)
else:
display.show(Image.ARROW_W)
sleep(100)
display.show(Image.ARROW_NW)
sleep(100)
display.show(Image.ARROW_N)
sleep(100)
display.show(Image.ARROW_NE)
sleep(100)
display.show(Image.ARROW_E)
sleep(1000)
display.clear()
while True:
# Keep track of current player's time
player_time[current_player] = time_marker[current_player]-int((running_time()-now)/1000)
# If time out, arrow flashes at loser
if player_time[current_player] <= 0:
while True:
if current_player == 0:
display.show(Image.ARROW_W)
else:
display.show(Image.ARROW_E)
music.play("c4:4")
display.clear()
music.play("r:4")
# Display current player's remaining time
show_timer(player_time[current_player])
# Button press changes player
if current_player == 0 and button_a.is_pressed():
time_marker[0] = player_time[0]
current_player = 1
break
if current_player == 1 and button_b.is_pressed():
time_marker[1] = player_time[1]
current_player = 0
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment