package morpion;

import java.net.*;
import java.util.Scanner;

public class MorpionClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        InetAddress IPAddress = InetAddress.getByName("localhost");
        Scanner sc = new Scanner(System.in);

        System.out.println("--- JEU DU MORPION ---");
        while (true) {
            System.out.print("Entrez un index (0-8) : ");
            String coup = sc.nextLine();
            byte[] sendData = coup.getBytes();
            socket.send(new DatagramPacket(sendData, sendData.length, IPAddress, 5000));

            byte[] receiveData = new byte[256];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            socket.receive(receivePacket);

            String raw = new String(receivePacket.getData(), 0, receivePacket.getLength());
            String[] parts = raw.split("\\|");
            String plateau = parts[0];
            String status = parts[1];

            afficherGrille(plateau);

            if (!status.equals("CONTINUE")) {
                System.out.println("FIN : " + status);
                break; // Ou recommencer
            }
        }
        socket.close();
    }

    private static void afficherGrille(String p) {
        System.out.println("\n " + p.charAt(0) + " | " + p.charAt(1) + " | " + p.charAt(2));
        System.out.println("-----------");
        System.out.println(" " + p.charAt(3) + " | " + p.charAt(4) + " | " + p.charAt(5));
        System.out.println("-----------");
        System.out.println(" " + p.charAt(6) + " | " + p.charAt(7) + " | " + p.charAt(8) + "\n");
    }
}
