Skip to content

Instantly share code, notes, and snippets.

@descartez

descartez/master.py

Last active Feb 28, 2019
Embed
What would you like to do?
tic tac toe with microbits
# Add your Python code here. E.g.
from microbit import *
import radio
nodes = ["00","01","02","10","11","12","20","21","22"]
board = [
["","",""],
["","",""],
["","",""]
]
def check_victory(board):
combinations = [
# vertical
((0,0), (1,0), (2,0)),
((0,1), (1,1), (2,1)),
((0,2), (1,2), (2,2)),
# horizontal
((0,0), (0,1), (0,2)),
((1,0), (1,1), (1,2)),
((2,0), (2,1), (2,2)),
# crossed
((0,0), (1,1), (2,2)),
((2,0), (1,1), (0,2))
]
for coordinates in combinations:
letters = [board[y][x] for x,y in coordinates]
if len(set(letters)) == 1 and letters[0] != "":
return letters[0] # returns corresponding letter for winner (X/O)
return False
def clear_nodes(nodes):
for node in nodes:
radio.send(str(node))
radio.on()
clear_nodes(nodes)
while True:
incoming = radio.receive()
if incoming:
x = int(str(incoming)[0])
y = int(str(incoming)[1])
marker = str(incoming)[2]
board[x][y] = marker
display.show(marker)
win = check_victory(board)
if win:
display.scroll("Winner is:" + win)
sleep(100)
display.scroll("Winner is:" + win)
clear_nodes(nodes)
board = [["","",""],["","",""],["","",""]]
radio.send("confirmed")
sleep(100)
else:
display.show("*")
if button_a.is_pressed():
clear_nodes(nodes)
board = [["","",""],["","",""],["","",""]]
if button_b.is_pressed():
clear_nodes(nodes)
board = [["","",""],["","",""],["","",""]]
sleep(100)
# Add your Python code here. E.g.
from microbit import *
import radio
radio.on()
# adjust these per node
coord_x = 0
coord_y = 0
chosen = ""
while True:
incoming = radio.receive()
if incoming == "confirmed":
display.show("-")
sleep(100)
elif incoming == str(coord_x) + str(coord_y):
chosen = ""
display.clear()
if button_a.is_pressed():
chosen = "x"
display.show(chosen)
radio.send(str(coord_x) + str(coord_y) + chosen)
elif button_b.is_pressed():
chosen = "o"
display.show(chosen)
radio.send(str(coord_x) + str(coord_y) + chosen)
display.show(chosen)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment