Skip to content
Snippets Groups Projects
main.py 2.38 KiB
id = [0,0]
matsize = [0, 0]
 
def display_id():
	afficher_texte("{}, {}".format(id[0], id[1]), speed=0.01)
 
def msg_to_str(msg):
	return str(msg)[2:-1]
 
def send_passthrough(msg, x, y):
	x = int(x)
	y = int(y)

	if x > id[0]:
		d = E
	elif x < id[0]:
		d = O
	elif y > id[1]:
		d = N
	else:
		d = S

	envoyer_msg(d, "PT;{},{};{}".format(x, y, msg))

def send_xy(x, y, msg):
	send_passthrough(msg, x, y)

def send_text_xy(x, y, text, color=ROUGE, speed=0.1):
	send_xy(x, y, "TEXT;{};{};{}".format(color, speed, text))

def send_moving_xy(x, y, text, color=ROUGE, speed=0.1):
	send_xy(x, y, "MOVING;{};{};{}".format(color, speed, text))


def check_presence(d):
	envoyer_msg(d, "PING")

	for x in range(10):
		time.sleep(0.1)
		ret = recevoir_msg(d)

		if ret == b"PONG": return True

	return False


def update_id(new_id):
	global id

	id[0] = int(new_id[0])
	id[1] = int(new_id[1])
	envoyer_msg(N, "SET_ID:{},{}".format(id[0], id[1] + 1))
	envoyer_msg(E, "SET_ID:{},{}".format(id[0] + 1, id[1]))

	if not check_presence(N) and not check_presence(E):
		send_xy(0, 0, "MATSIZE:{},{}".format(id[0], id[1]))

	display_id()


def handle_receive(msg, d):
 
	print("Received from {} : {}".format(d, msg))

	if msg.startswith("SET_ID"):
		tmp_id = msg[7:].split(",")
		update_id(tmp_id)
 
	elif msg == "PING":
		envoyer_msg(d, "PONG")
 
	elif msg == "DISP_ID":
		display_id()

	elif msg.startswith("PT;"):
		msgs = msg.split(";")
		m = msgs[2:]
		m = ";".join(m)
		x, y = msgs[1].split(",")

		x = int(x)
		y = int(y)

		if x == id[0] and y == id[1]:
			handle_receive(m, d)
			return
		
		send_passthrough(m, x, y)
 
	elif msg.startswith("MATSIZE"):
		x, y = msg.split(":")[-1].split(",")
		print("Matsize : {} {}".format(x, y))
		matsize = [int(x), int(y)]

	elif msg.startswith("TEXT"):
		msgs = msg.split(";")
		color = int(msgs[1])
		speed = float(msgs[2])
		afficher_texte(msgs[3], color, speed)

	elif msg.startswith("MOVING"):
		msgs 	= msg.split(";")
		color 	= int(msgs[1])
		speed 	= float(msgs[2])
		text 	= msgs[3]

		time.sleep(speed * 11)
		send_moving_xy(id[0] - 1, id[1], text, color=color, speed=speed)
		afficher_texte(text, color, speed)


# send_text_xy(1,0,text,speed=speed);time.sleep(speed*13);afficher_texte(text,speed=speed)



# Main
afficher_texte("Ready", VERT, speed=0.01)

while True:

	for d in [N, S, E, O]:
		msg = recevoir_msg(d)

		if msg == b"": continue

		msg = msg_to_str(msg)
		handle_receive(msg, d)