Пример #1
0
        private void btnFinalizarTurno_Click(object sender, EventArgs e)
        {
            int nextPlayer = jugadorLocal.getID() + 1;

            if (jugadorLocal.getID() == board.getPlayers().Length - 1)
            {
                nextPlayer = 0;
            }

            byte   nextJugadorLocalId        = Convert.ToByte(nextPlayer);
            string nextJugadorLocalIdStrByte = Instruccion.ByteToString(nextJugadorLocalId);
            string nextJugadorLocalIdStr     = nextJugadorLocalIdStrByte.Substring(6, 2);

            Trace.WriteLine("Siguiente jugador: " + nextJugadorLocalIdStr);

            this.btnRollDices.Enabled      = false;
            this.btnFinalizarTurno.Enabled = false;
            lbxHistoria.Items.Add("Siguiente jugador: " + nextJugadorLocalIdStr);
            lbxHistoria.Items.Add("     Trama: " + Instruccion.ByteToString(Instruccion.FormarPrimerByte(jugadorLocal.GetIdAsString(), nextJugadorLocalIdStr, Instruccion.PrimerByte.TIRAR_DADOS)));
            // Mandamos 01 y 01 en los dados pero realmente este valor no afecta, solo importa que sea != 0
            this.comPort.Write(Instruccion.FormarTrama(
                                   Instruccion.FormarPrimerByte(jugadorLocal.GetIdAsString(), nextJugadorLocalIdStr, Instruccion.PrimerByte.TIRAR_DADOS),
                                   Instruccion.FormarSegundoByteDados("01", "01")
                                   ), 0, 4);
        }
 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);
 }
Пример #3
0
        private void btnRollDices_Click(object sender, EventArgs e)
        {
            this.btnRollDices.Enabled = false;
            Random randDado = new Random();

            numeroDado1 = randDado.Next(1, 7);
            numeroDado2 = randDado.Next(1, 7);
            dice1.Image = (Image)Properties.Resources.ResourceManager.GetObject("dado" + numeroDado1);
            dice2.Image = (Image)Properties.Resources.ResourceManager.GetObject("dado" + numeroDado2);

            string numeroDado1Byte = Instruccion.ByteToString(Convert.ToByte(numeroDado1));
            string numeroDado1Str  = numeroDado1Byte.Substring(5);
            string numeroDado2Byte = Instruccion.ByteToString(Convert.ToByte(numeroDado2));
            string numeroDado2Str  = numeroDado2Byte.Substring(5);

            this.btnFinalizarTurno.Enabled = true;
            lbxHistoria.Items.Add("Lanzar dados: " + Instruccion.ByteToString(Instruccion.FormarPrimerByte(jugadorLocal.GetIdAsString(), jugadorLocal.GetIdAsString(), Instruccion.PrimerByte.TIRAR_DADOS)));
            this.comPort.Write(Instruccion.FormarTrama(
                                   Instruccion.FormarPrimerByte(jugadorLocal.GetIdAsString(), jugadorLocal.GetIdAsString(), Instruccion.PrimerByte.TIRAR_DADOS),
                                   Instruccion.FormarSegundoByteDados(numeroDado1Str, numeroDado2Str)
                                   ), 0, 4);

            Square currentSquare = board.movePlayer(jugadorLocal, numeroDado1, numeroDado2);

            Trace.WriteLine("Current Position: " + jugadorLocal.getCurrentPosition());

            jugadorLocal.SetPoisitionX(currentSquare.GetPositionX());
            jugadorLocal.SetPoisitionY(currentSquare.GetPositionY());
            tablero.Invalidate();

            int resultado = currentSquare.doAction(jugadorLocal, board);

            Trace.WriteLine("New player money: " + jugadorLocal.getMoney().getMoney());
            // Esto estaba así en el board, no se si haga falta porque tal vez podamos validarlo dentro del doAction
            if (jugadorLocal.getMoney().isBrokeOut())
            {
                Trace.WriteLine(jugadorLocal, jugadorLocal.getName() + " has been broke out!");
                jugadorLocal.setBrokeOut(true);
            }
            actualizarDatosJugadorLocal();

            // Aquí empieza lo bueno
            if (resultado == 1)
            {
                Trace.WriteLine("Debería enviar el mensaje");
                this.comPort.Write(Instruccion.FormarTrama(
                                       Instruccion.FormarPrimerByte(jugadorLocal.GetIdAsString(), jugadorLocal.GetIdAsString(), Instruccion.PrimerByte.PROPIEDADES),
                                       Convert.ToByte("000" + board.GetHouseBits(jugadorLocal.getCurrentPosition()), 2)
                                       ), 0, 4);
            }
        }
Пример #4
0
        /*
         *  Aqui deberiamos procesar los datos recibidos y realizar las acciones
         *  necesarias sobre nuestros objetos locales.
         */
        private void OnDatosRecebidos(object sender, SerialDataReceivedEventArgs e)
        {
            if (comPort.BytesToRead < 4)
            {
                return;
            }

            byte[] receivedBytes = new byte[4];
            comPort.Read(receivedBytes, 0, 4);
            string primerByte = Instruccion.ByteToString(receivedBytes[1]);

            this.BeginInvoke((MethodInvoker) delegate()
            {
                lbxHistoria.Items.Add("Trama recibida: " + primerByte);
            });
            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);

            Trace.WriteLine(String.Format("Origen: {0}\nDestino: {1}", origen, destino));

            if (primerByte.Substring(4, 4) == Instruccion.PrimerByte.TIRAR_DADOS)
            {
                leerTramaTirarDados(origen, destino, segundoByte);
            }
            else if (primerByte.Substring(4, 4) == Instruccion.PrimerByte.PROPIEDADES)
            {
                leerTramaPropiedades(origen, destino, segundoByte);
            }

            InputData = comPort.ReadExisting();
            Console.WriteLine();
            if (InputData != String.Empty)
            {
                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
            }
        }
        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 });
            }
        }