import dht
import time
import ujson
import network
import neopixel
from machine import Pin
from umqtt.simple import MQTTClient
# NeoPixel LED strip parameters
LED_PIN = 4
NUM_LEDS = 9
# Initialize NeoPixel LED strip
np = neopixel.NeoPixel(Pin(LED_PIN), NUM_LEDS)
def update_led_strip(matrix):
for i in range(NUM_LEDS):
if matrix[i // 3][2-(i % 3)] == "X":
np[i] = (255, 0, 0) # Red for "X"
elif matrix[i // 3][2-(i % 3)] == "O":
np[i] = (0, 0, 255) # Blue for "O"
else:
np[i] = (0, 0, 0) # Turn off for "*"
np.write()
# ...
# MQTT Server Parameters
MQTT_CLIENT_ID = "wokwi-tictactoe"
MQTT_BROKER = "broker.mqttdashboard.com"
sensor = dht.DHT22(Pin(15))
print("Connecting to WiFi", 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!")
# create a 3 x 3 matrix of *
matrix = [["*" for i in range(3)] for j in range(3)]
current_player = "X"
game_over = False # Variable to track the game status
def callback(topic, msg):
global current_player, matrix, client, game_over
if game_over:
return # Ignore new moves if the game is already over
topic = topic.decode("utf-8")
msg = msg.decode("utf-8")
print(topic, msg)
if topic == f"user_moves/{current_player}":
try:
coordinates = tuple(map(int, msg.strip('()').split(',')))
if matrix[coordinates[0]][coordinates[1]] == "*":
matrix[coordinates[0]][coordinates[1]] = current_player
print(f"{current_player} made a move")
current_player = "O" if current_player == "X" else "X"
else:
print("Invalid move: Cell is already taken")
except Exception as e:
print("Invalid move:", e)
update_led_strip(matrix)
for i in range(3):
if matrix[i][0] == matrix[i][1] == matrix[i][2] != "*":
print(f"{matrix[i][0]} won!")
client.publish(f"victory/{matrix[i][0]}", b"Congratulations!")
game_over = True
return
for i in range(3):
if matrix[0][i] == matrix[1][i] == matrix[2][i] != "*":
print(f"{matrix[0][i]} won!")
client.publish(f"victory/{matrix[0][i]}", b"Congratulations!")
game_over = True
return
if matrix[0][0] == matrix[1][1] == matrix[2][2] != "*":
print(f"{matrix[0][0]} won!")
client.publish(f"victory/{matrix[0][0]}", b"Congratulations!")
game_over = True
return
if matrix[0][2] == matrix[1][1] == matrix[2][0] != "*":
print(f"{matrix[0][2]} won!")
client.publish(f"victory/{matrix[0][2]}", b"Congratulations!")
game_over = True
return
if all([cell != "*" for row in matrix for cell in row]):
print("It's a tie!")
client.publish("victory/tie", b"It's a tie!")
game_over = True
return
client.publish(f"requests/{current_player}", b"It is your turn")
print("Connecting to MQTT server... ", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
client.set_callback(callback)
client.connect()
client.subscribe("user_moves/X")
client.subscribe("user_moves/O")
print("Connected!")
client.publish(f"requests/{current_player}", b"It is your turn")
while True:
try:
client.check_msg()
except OSError as e:
print("Failed to check message or publish:", e)
print("Reconnecting to MQTT broker...")
client.connect()