Exemplo n.º 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);
        }
Exemplo n.º 2
0
        private void leerTramaPropiedades(String origen, String destino, String segundoByte)
        {
            string propiedadComprada = segundoByte.Substring(3, 5);
            int    posicionPropiedad = board.GetHousePositionFromBits(propiedadComprada);

            if (jugadorLocal.GetIdAsString() != destino)
            {
                byte origenByte   = Convert.ToByte(origen);
                int  origenNumber = Convert.ToInt32(origenByte);

                HouseSquare propiedad = (HouseSquare)board.GetSquares()[posicionPropiedad];
                Trace.WriteLine("Owner: " + origenNumber);
                Trace.WriteLine("Player: " + board.getPlayer(origenNumber).getID());
                propiedad.setOwner(origenNumber);

                this.BeginInvoke((MethodInvoker) delegate()
                {
                    lbxHistoria.Items.Add("Jugador " + origen + " compró la propiedad " + board.GetSquares()[posicionPropiedad].getName());
                });

                this.comPort.Write(Instruccion.FormarTrama(
                                       Instruccion.FormarPrimerByte(origen, destino, Instruccion.PrimerByte.PROPIEDADES),
                                       Convert.ToByte("000" + propiedadComprada, 2)
                                       ), 0, 4);
            }
            else
            {
                this.BeginInvoke((MethodInvoker) delegate()
                {
                    lbxPropiedades.Items.Add(posicionPropiedad + " " + board.GetSquares()[posicionPropiedad].getName());
                    lbxHistoria.Items.Add("Compré la propiedad " + board.GetSquares()[posicionPropiedad].getName());
                });
            }
        }
 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);
 }
Exemplo n.º 4
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);
            }
        }
 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 });
            }
        }
Exemplo n.º 7
0
        private void leerTramaTirarDados(String origen, String destino, String segundoByte)
        {
            string dado1Str = segundoByte.Substring(2, 3);
            string dado2Str = segundoByte.Substring(5, 3);

            int dado1 = Convert.ToInt32(dado1Str, 2);

            Trace.WriteLine("Dado 1: " + dado1);
            int dado2 = Convert.ToInt32(dado2Str, 2);

            Trace.WriteLine("Dado 2: " + dado2);

            if (jugadorLocal.GetIdAsString() != destino)
            {
                this.BeginInvoke((MethodInvoker) delegate()
                {
                    this.btnRollDices.Enabled      = false;
                    this.btnFinalizarTurno.Enabled = false;
                    lbxHistoria.Items.Add("Jugador que le toca: " + origen);
                });
                dice1.Image = (Image)Properties.Resources.ResourceManager.GetObject("dado" + dado1);
                dice2.Image = (Image)Properties.Resources.ResourceManager.GetObject("dado" + dado2);
                // Actualizamos la posicion del jugador que se esta moviendo
                var jugadorMoviendose = board.getPlayer(Convert.ToInt32(origen, 2));
                Trace.WriteLine("Actualizando posicion del jugador que se movio. Id: " + jugadorMoviendose.getID());

                if ((ultimoOrigen == origen) && (dado1 == dado2))
                {
                    dobles++;
                    if (dobles == 3)
                    {
                        dobles = 0;
                        jugadorMoviendose.SetPoisitionX(9);
                        jugadorMoviendose.SetPoisitionY(360);
                        jugadorMoviendose.setIsInJail(true);
                    }
                }
                else
                {
                    dobles = 0;
                    int newPosition = Board.normalizePosition(jugadorMoviendose.getCurrentPosition() + dado1 + dado2);
                    if (jugadorMoviendose.getCurrentPosition() > newPosition)
                    {
                        jugadorMoviendose.getMoney().addMoney(200);
                    }
                    jugadorMoviendose.setPosition(newPosition);
                    Square pos = board.GetSquares()[newPosition];
                    jugadorMoviendose.SetPoisitionX(pos.GetPositionX());
                    jugadorMoviendose.SetPoisitionY(pos.GetPositionY());
                    if (pos.GetType() == typeof(HouseSquare))
                    {
                        HouseSquare posHouse = (HouseSquare)pos;
                        pos = (HouseSquare)pos;
                        if ((posHouse.getOwner() != jugadorMoviendose.getID()) && (posHouse.getOwner() >= 0))
                        {
                            Trace.WriteLine(jugadorMoviendose, jugadorMoviendose.getName() + " lost " + posHouse.getRent() + " money to " + board.getPlayer(posHouse.getOwner()).getName());
                            jugadorMoviendose.getMoney().substractMoney(posHouse.getRent());
                            board.getPlayer(posHouse.getOwner()).getMoney().addMoney(posHouse.getRent());
                            Trace.WriteLine("Owner money: " + board.getPlayer(posHouse.getOwner()).getMoney().getMoney());
                            actualizarDatosJugadorLocal();
                        }
                    }
                    Trace.WriteLine(String.Format("Posicion del jugador {0}: {1}, {2} (Casilla: {3})",
                                                  jugadorMoviendose.getID(),
                                                  jugadorMoviendose.GetPositionX(),
                                                  jugadorMoviendose.GetPositionY(),
                                                  newPosition));
                }
                tablero.Invalidate();


                this.comPort.Write(Instruccion.FormarTrama(
                                       Instruccion.FormarPrimerByte(origen, destino, Instruccion.PrimerByte.TIRAR_DADOS),
                                       Instruccion.FormarSegundoByteDados(dado1Str, dado2Str)
                                       ), 0, 4);
            }
            else if (jugadorLocal.GetIdAsString() == origen)
            {
                if (jugadorLocal.getIsInJail())
                {
                    this.BeginInvoke((MethodInvoker) delegate()
                    {
                        this.btnRollDices.Enabled      = false;
                        this.btnFinalizarTurno.Enabled = true;
                        lbxHistoria.Items.Add("Carcel");
                    });
                }
                else
                {
                    if (dado1 != dado2)
                    {
                        // Aqui deberiamos hacer las acciones que si de comprar, etc
                        this.BeginInvoke((MethodInvoker) delegate()
                        {
                            this.btnFinalizarTurno.Enabled = true;
                        });
                    }

                    else if (dado1 == dado2)
                    {
                        this.BeginInvoke((MethodInvoker) delegate()
                        {
                            this.btnRollDices.Enabled      = true;
                            this.btnFinalizarTurno.Enabled = false;
                            lbxHistoria.Items.Add("Dobles");
                        });
                    }
                }
            }
            else if (jugadorLocal.GetIdAsString() == destino)
            {
                Trace.WriteLine(String.Format("Jugador local: {0}  Destino: {1}", jugadorLocal.GetIdAsString(), destino));
                this.BeginInvoke((MethodInvoker) delegate()
                {
                    this.btnRollDices.Enabled = true;
                    lbxHistoria.Items.Add("SOY YO: " + jugadorLocal.GetIdAsString());
                });
            }
            else // Creo que nunca llegara hasta aqui
            {
                Trace.WriteLine("No creo que pase");
            }
        }