private void AnunciarJugadores(string origen, string destino, string numeroFaltante)
 {
     byte[] toSend = Instruccion.FormarTrama(
         Instruccion.FormarPrimerByte(origen, destino, Instruccion.PrimerByte.INICIAR_PARTIDA),
         Instruccion.FormarSegundoByte(
             Instruccion.SegundoByte.CONFIGURAR_PARTIDA + Instruccion.SegundoByte.ANUNCIAR,
             numeroFaltante));
     foreach (byte b in toSend)
     {
         Trace.WriteLine(Instruccion.ByteToString(b));
     }
     comPort.Write(toSend, 0, 4);
 }
 private void btnCrearPartida_Click(object sender, EventArgs e)
 {
     // Enviar trama de inicio de partida
     this.jugadorLocal = new Player(0, "Creador de partida");
     this.SetJugador(jugadorLocal);
     Trace.WriteLine("Creando partida");
     try
     {
         comPort.Write(Instruccion.FormarTrama(
                           Instruccion.FormarPrimerByte(jugadorLocal.GetIdAsString(), jugadorLocal.GetIdAsString(), Instruccion.PrimerByte.INICIAR_PARTIDA),
                           Instruccion.FormarSegundoByte(
                               Instruccion.SegundoByte.CONFIGURAR_PARTIDA + Instruccion.SegundoByte.CONTAR,
                               jugadorLocal.GetIdAsString())),
                       0, 4);
     } catch (InvalidOperationException ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
        private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {
            if (comPort.BytesToRead < 4)
            {
                return;
            }
            Trace.WriteLine("Recibiendo");
            byte[] receivedBytes = new byte[4];
            comPort.Read(receivedBytes, 0, 4);
            string primerByte  = Instruccion.ByteToString(receivedBytes[1]);
            string segundoByte = Instruccion.ByteToString(receivedBytes[2]);

            Trace.WriteLine("Primer byte: " + primerByte);
            Trace.WriteLine("Segundo byte: " + segundoByte);

            string origen        = primerByte.Substring(0, 2);
            string destino       = primerByte.Substring(2, 2);
            string currentPlayer = "Sin asignar";

            if (jugadorLocal != null)
            {
                currentPlayer = jugadorLocal.GetIdAsString();
            }

            if (primerByte.Substring(4, 4) == Instruccion.PrimerByte.INICIAR_PARTIDA)
            {
                if (segundoByte.Substring(0, 5) == Instruccion.SegundoByte.CONFIGURAR_PARTIDA)
                {
                    Trace.WriteLine("Anunciar o crear: " + segundoByte.Substring(5, 1));
                    if (segundoByte.Substring(5, 1) == Instruccion.SegundoByte.ANUNCIAR)
                    {
                        // Obtenemos los dos ultimos bits del segundo byte que representan el numero de
                        // jugadores y lo convertimos a una variable de tipo int para poder sumarle
                        var binaryJugadoresPorAgregar = segundoByte.Substring(6, 2);
                        var jugadoresPorAgregar       = Convert.ToInt32(segundoByte.Substring(6, 2), 2);
                        Trace.WriteLine("Numero de jugadores que debemos crear localmente: " + jugadoresPorAgregar);
                        // Como solo son dos bits, el maximo valor que se puede representar es 3,
                        // pero el 11 representa 4 jugadores.
                        var jugadoresTotales = jugadoresPorAgregar + 1;
                        var listaJugadores   = new List <Player>();
                        listaJugadores.Add(jugadorLocal);
                        Trace.WriteLine("Local id: " + jugadorLocal.getID());
                        //Creamos los jugadores faltantes
                        for (int i = 0; i <= jugadoresPorAgregar; i++)
                        {
                            if (i != jugadorLocal.getID())
                            {
                                listaJugadores.Add(new Player(i, i.ToString()));
                            }
                        }
                        BOARD.SetPlayers(listaJugadores.ToArray());
                        // Boleteo temporal para cambiarle el texto al label desde otro thread
                        this.lbNumeroJugadores.BeginInvoke((MethodInvoker) delegate() {
                            this.lbNumeroJugadores.Text = "Numero de jugadores: " + BOARD.getPlayers().Length;;
                        });

                        if (jugadorLocal.GetIdAsString() != destino)
                        {
                            AnunciarJugadores(origen, destino, binaryJugadoresPorAgregar);
                        }
                        else
                        {
                            // Ya terminamos de configurar la partida, ahora se deberia
                            // mostrar el tablero con las opciones para continuar el juego
                            Trace.WriteLine("Ya todas las maquinas recibieron y manejaron el anuncio de jugadores");
                        }
                    }
                    else
                    {
                        // Como estamos configurando una partida, esto pasara en las maquinas que
                        // todavia no han recibido la trama de creacion de partida
                        if (jugadorLocal == null)
                        {
                            Trace.WriteLine("Uniendose a partida");
                            var nJugador = Convert.ToInt32(segundoByte.Substring(6, 2), 2);
                            Trace.WriteLine("Numero de jugador recibido: " + nJugador);
                            nJugador = nJugador + 1;
                            var strNumeroJugador = Convert.ToString(nJugador, 2).PadLeft(2, '0');
                            Trace.WriteLine("Nuevo numero de jugador: " + strNumeroJugador);
                            Player newPlayer = new Player(nJugador, strNumeroJugador);
                            this.BeginInvoke(new SetJugadorCallback(SetJugador), new object[] { newPlayer });

                            Trace.WriteLine("Emitiendo mensaje de crear partida");
                            comPort.Write(Instruccion.FormarTrama(
                                              Instruccion.FormarPrimerByte(origen, destino, Instruccion.PrimerByte.INICIAR_PARTIDA),
                                              Instruccion.FormarSegundoByte(
                                                  Instruccion.SegundoByte.CONFIGURAR_PARTIDA + Instruccion.SegundoByte.CONTAR,
                                                  newPlayer.GetIdAsString())),
                                          0, 4);
                        }
                        else
                        {
                            Trace.WriteLine("Mensaje llego al destino");
                            var binaryJugadoresPorAgregar = segundoByte.Substring(6, 2);
                            // Anunciamos la cantidad de jugadores, y cuando el mensaje vuelva a llegar
                            // a la maquina creadora, esta actualiza su lista de jugadores
                            AnunciarJugadores(origen, destino, binaryJugadoresPorAgregar);
                        }
                    }
                    this.btnContinue.BeginInvoke((MethodInvoker) delegate()
                    {
                        this.btnContinue.Enabled = true;
                    });
                }
            }
            else
            {
                Trace.WriteLine("Fuckit");
            }

            InputData = BitConverter.ToString(receivedBytes);
            Trace.WriteLine(InputData);
            if (InputData != String.Empty)
            {
                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
            }
        }