import network
import time
from machine import Pin
from umqtt.simple import MQTTClient
MQTT_CLIENT_ID = "sea_chess_board"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_MOVE_TOPIC = "sea_chess/move"
ROWS = 3
COLS = 3
rgb_pins = [[26], [27]]
current_player = "Player1"
players = ["Player1", "Player2"]
def connect_to_wifi():
print("Connecting to Wi-Fi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
def connect_to_mqtt_broker():
connect_to_wifi()
print("Connecting to MQTT server... ", end="")
client.connect()
print("Connected!")
client.subscribe(MQTT_MOVE_TOPIC)
print("Subscribed to {}".format(MQTT_MOVE_TOPIC))
def process_move(player, move):
print("Received move from {}: {}".format(player, move))
row, col = map(int, move.split(','))
for i in range(ROWS):
for j in range(COLS):
if i == row and j == col:
for pin in rgb_pins[i]:
Pin(pin, Pin.OUT, value=1)
else:
for pin in rgb_pins[i]:
Pin(pin, Pin.OUT, value=0)
def play_turn():
global current_player
current_player = players[1] if current_player == players[0] else players[0]
print("It's {}'s turn.".format(current_player))
client.publish(MQTT_MOVE_TOPIC, "{}, your turn!".format(current_player))
def move_callback(topic, message):
topic = topic.decode("utf-8")
message = message.decode("utf-8")
player, move = message.split(',')
if player == current_player:
process_move(player, move)
play_turn()
else:
print("Not {}'s turn yet.".format(player))
for row in rgb_pins:
for pin in row:
Pin(pin, Pin.OUT, value=0)
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(move_callback)
connect_to_mqtt_broker()
try:
while True:
client.wait_msg()
finally:
client.disconnect()