예제 #1
0
        private void InviaPacchetto(Pacchetto pkt)
        {
            if (pkt != null || pkt.Address == null)
            {
                IPEndPoint ipEP;
                IPAddress  ipAddress;
                int        port = pkt.Address == myAddress ? intUdpLocalPort : intUdpRemotePort;

                ipAddress = IPAddress.Parse(pkt.Address);

                ipEP = new IPEndPoint(ipAddress, port);
                ep   = (EndPoint)ipEP;

                try
                {
                    abytTx = Encoding.UTF8.GetBytes(pkt.Msg);

                    udpSocket.BeginSendTo(abytTx, 0, pkt.Msg.Length, SocketFlags.None, ep, new AsyncCallback(OnSend), null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Send(): eccezione Exception\n" + ex.Message);
                }
            }
        }
예제 #2
0
        /**
         * Ricevi i pacchetti inviati dalle boards, e sincronizza tutte le boards sul timestamp corrente
         */
        public List <Pacchetto> receivePackets()
        {
            List <Pacchetto> packet_list = new List <Pacchetto>();

            byte[] buffer = new byte[1024];
            writeDebugLine_("In attesa di ricevere dati");

            // ricevo #pacchetti
            receiveBytes(buffer, 4);
            int packet_number = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0));

            writeDebugLine_("Numero di pacchetti da ricevere: " + packet_number);

            // ricevo i pacchetti
            for (int i = 0; i < packet_number; i++)
            {
                Pacchetto packet = Pacchetto.RiceviPacchetto(this);
                packet_list.Add(packet);
            }
            writeDebugLine_("Pacchetti ricevuti");

            // mi sincronizzo con le altre boards
            waitForTimeSync_();

            // invio timestamp
            int epoch         = EspServer.getUnixEpoch();
            int network_epoch = IPAddress.HostToNetworkOrder(epoch);

            socket_.Send(BitConverter.GetBytes(network_epoch), 4, SocketFlags.None);

            writeDebugLine_("Timestamp inviato: " + epoch);
            return(packet_list);
        }
예제 #3
0
        //Seleziona l'elenco dei pacchetti dalla tabella 'pacchetti' del DB

        public List <Pacchetto> SelezionaPacchetti(string query)
        {
            //Creo una lista di pacchetti per memorizzare i risultati

            List <Pacchetto> lista_pacchetti = new List <Pacchetto>();

            using (MySqlConnection connessione = new MySqlConnection("Database=" + Database + ";" + "Server=" + Server + ";" + "Port=3306;" + "UID=" + Uid + ";" + "Password="******";"))
                using (MySqlCommand cmd = connessione.CreateCommand())
                {
                    try
                    {
                        connessione.Open();
                        cmd.CommandText = query;
                        using (var leggiDati = cmd.ExecuteReader())
                        {
                            while (leggiDati.Read())
                            {
                                Pacchetto pacchetto = new Pacchetto(leggiDati.GetString(1), leggiDati.GetInt32(2), leggiDati.GetString(3),
                                                                    leggiDati.GetInt32(4), leggiDati.GetString(5), leggiDati.GetInt32(6), leggiDati.GetBoolean(7));
                                lista_pacchetti.Add(pacchetto);
                            }
                            Connesso = true;
                            return(lista_pacchetti);
                        }
                    }
                    catch (MySqlException e)
                    {
                        System.Diagnostics.Debug.WriteLine("Impossibile recuperare le informazioni sui pacchetti dal database" + e.ToString());
                        Connesso = false;
                        return(null);
                    }
                }
        }
예제 #4
0
        public void Send(Pacchetto pkt)
        {
            SendBuffer[SendWrite] = pkt;

            if (SendWrite == 9999)//9999
            {
                SendWrite = 0;
                SendFull  = true;
            }
            else
            {
                SendWrite++;
            }
        }
예제 #5
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            KeyboardState keystate  = Keyboard.GetState();
            Pacchetto     pacchetto = null;

            previousState = mouseState;
            mouseState    = Mouse.GetState();

            for (int i = 0; i < players.Count; i++)
            {
                players[i].Update();
            }

            if (players.Count != 0)
            {
                if (previousState != mouseState)
                {
                    if (players.FirstOrDefault(x => x.Id == myId).Position == players.FirstOrDefault(x => x.Id == myId).LastPosition)
                    {
                        pacchetto = new Pacchetto("ang;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                    }
                }

                if (keystate.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.W))
                {
                    pacchetto = new Pacchetto("for;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                }

                if (keystate.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.S))
                {
                    pacchetto = new Pacchetto("bck;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                }

                if (previousState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released && mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                {
                    pacchetto = new Pacchetto("fire;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                }

                if (pacchetto != null)
                {
                    Send(pacchetto);
                }
            }
            base.Update(gameTime);
        }
예제 #6
0
 public void RemoveSearch()
 {
     if (selectedPhonePos.Count != 0)
     {
         String          cleanSelectedMAC = selectedMAC.Replace(":", "");
         DatiDispositivo p = selectedPhonePos.First <DatiDispositivo>();
         selectedPhonePos.Remove(p);
         if (Pacchetto.CntrlGlobal(selectedMAC))
         {
             //hiddenPhone
             hiddenPhonePos.Add(p);
         }
         else
         {
             //visiblePhone
             phonePos.Add(p);
         }
     }
 }
예제 #7
0
        private void InviaPacchetto(Pacchetto pkt, int port) // metodo da usare per la demo multihost in locale
        {
            IPEndPoint ipEP;
            IPAddress  ipAddress;

            ipAddress = IPAddress.Parse(pkt.Address);

            ipEP = new IPEndPoint(ipAddress, port);
            ep   = (EndPoint)ipEP;

            try
            {
                abytTx = Encoding.UTF8.GetBytes(pkt.Msg);

                udpSocket.BeginSendTo(abytTx, 0, pkt.Msg.Length, SocketFlags.None, ep, new AsyncCallback(OnSend), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Send(): eccezione Exception\n" + ex.Message);
            }
        }
예제 #8
0
        //Inserisci pacchetti nella tabella 'pacchetti' del DB

        public bool InserisciPacchetto(Pacchetto pacchetto)
        {
            try
            {
                string query = String.Format("INSERT INTO  pacchetti(MAC, RSSI, SSID, timestamp, hash, ID_scheda, global) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')",
                                             pacchetto.MAC_Address, pacchetto.RSSI, pacchetto.SSID, pacchetto.Timestamp, pacchetto.Checksum, pacchetto.ID_scheda, pacchetto.Global);

                using (MySqlConnection connessione = new MySqlConnection("Database=" + Database + ";" + "Server=" + Server + ";" + "Port=3306;" + "UID=" + Uid + ";" + "Password="******";"))
                    using (MySqlCommand cmd = connessione.CreateCommand())
                    {
                        connessione.Open();
                        cmd.CommandText = query;
                        cmd.ExecuteNonQuery();
                    }
                Connesso = true;
                return(true);
            }
            catch (MySqlException e)
            {
                System.Diagnostics.Debug.WriteLine("Impossibile inserire i pacchetti nel database" + e.ToString());
                Connesso = false;
                return(false);
            }
        }
예제 #9
0
        public void SearchMac(string selected)
        {
            String cleanSelectedMAC = selected.Replace(":", "");

            if (selected != "")
            {
                selectedMAC = selected;

                if (Pacchetto.CntrlGlobal(selectedMAC))
                {
                    //hiddenPhone
                    foreach (DatiDispositivo p in scatterChart.Series[2].Values)
                    {
                        if (p.MAC_Address.CompareTo(cleanSelectedMAC) == 0)
                        {
                            hiddenPhonePos.Remove(p);
                            selectedPhonePos.Add(p);
                            break;
                        }
                    }
                }
                else
                {
                    //visiblePhone
                    foreach (DatiDispositivo p in scatterChart.Series[1].Values)
                    {
                        if (p.MAC_Address.CompareTo(cleanSelectedMAC) == 0)
                        {
                            phonePos.Remove(p);
                            selectedPhonePos.Add(p);
                            break;
                        }
                    }
                }
            }
        }
예제 #10
0
        private void OnReceive(IAsyncResult ar)
        {
            string     strReceived;
            int        idx;
            IPEndPoint ipEPRx;

            string[] astr;
            int      a = 0;

            try
            {
                if (udpSocket == null)
                {
                    return;
                }


                ipEPRx = new IPEndPoint(IPAddress.Any, 0);

                ep = (EndPoint)ipEPRx;

                udpSocket.EndReceiveFrom(ar, ref ep);

                astr = ep.ToString().Split(':');

                strReceived = Encoding.UTF8.GetString(abytRx);
                idx         = strReceived.IndexOf((char)0);

                if (idx > -1)
                {
                    strReceived = strReceived.Substring(0, idx);
                }

                if (serverStatus)
                {
                    buffer[write] = new Pacchetto(strReceived, astr[0]);

                    if (write == 9999)    //9999
                    {
                        write       = 0;
                        buffer_full = true;
                    }
                    else
                    {
                        write++;
                    }
                }
                else
                {
                    Analisi(new Pacchetto(strReceived, astr[0]));
                }

                //ep = (EndPoint)new IPEndPoint(IPAddress.Any, intUdpLocalPort); // o 0
                abytRx = new byte[abytRx.Length];
                udpSocket.BeginReceiveFrom(abytRx, 0, abytRx.Length, SocketFlags.None, ref ep, new AsyncCallback(OnReceive), ep);
            }
            catch (ObjectDisposedException ex)
            {
                MessageBox.Show("OnReceive(): Eccezione ObjectDisposedException\n" + ex.Message);

                /*udpSocket = null;
                 * Bind();*/
            }
            catch (Exception ex)
            {
                MessageBox.Show("OnReceive(): Eccezione Exception\n" + ex.Message + a);

                /* udpSocket = null;
                 * Bind();*/
            }
        }
예제 #11
0
        private void Analisi(Pacchetto pkt)
        {
            GameObject   app;
            BulletObject blt;

            var ann = new String[1];

            ann[0] = pkt.Msg;

            if (pkt.Msg.Contains(';'))
            {
                ann = pkt.Msg.Split(';');
            }

            switch (ann[0])
            {
            case "l":
                if (serverStatus)
                {
                    Send(new Pacchetto("srv;" + myAddress, pkt.Address));
                }

                break;

            case "srv":     //messaggi dal server
                switch (ann[1])
                {
                case "acc":                                //gaming true o comunque sono in partita
                    initMyPlayer(Convert.ToInt32(ann[2])); //CHECK
                    larghezzaSchermoServer = Convert.ToInt32(ann[3]);
                    altezzaSchermoServer   = Convert.ToInt32(ann[4]);
                    FunzioneDiMarco();
                    messages.Add(new Messaggio("Ti sei unito alla partita", Color.Blue));
                    break;

                case "ref":
                    //rimango nel menu, gli spazi sono pieni oppure sono gia all'interno
                    break;

                case "dct":
                    app = players.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[2]));
                    players.Remove(app);         //rimuovo il giocatore che era server
                    MessageBox.Show("Server disconnesso");
                    //il server è disconnesso, torno al menu
                    break;

                case "str":
                    //gaming = true;
                    break;

                default:
                    lTimer.Stop();
                    serverAddress = pkt.Address;
                    //operazione che eseguo solo adesso in testing
                    if (serverTick != 0)
                    {
                        Send(new Pacchetto("r;" + username, serverAddress));
                    }

                    serverTick = 0;
                    break;
                }
                break;

            case "r":
                if (serverStatus)
                {
                    if (players.Count < postiMax && (players.FirstOrDefault(x => x.Username == ann[1] && x.Address == pkt.Address)) == null)     //ann[1] username
                    {
                        app = new GameObject();
                        players.Add(app);
                        app.InitEnemy(PosizioneInizialeCarri(), Content.Load <Texture2D>("tankEnemy"), Content.Load <Texture2D>("bulletMin"), ann[1], pkt.Address, players.IndexOf(app));
                        messages.Add(new Messaggio(ann[1] + " si e' unito", Color.Blue));
                        Send(new Pacchetto("srv;acc;" + app.Id + ";" + 1600 + ";" + 900 + ";", pkt.Address));
                        Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), pkt.Address));
                        SendPlayersInformation(app);
                        SendPlayerInformation(app);
                    }
                    else
                    {
                        Send(new Pacchetto("srv;ref", pkt.Address));
                    }
                }

                break;

            case "ang":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        app.Angle = (float)Convert.ToDouble(ann[1]);
                        foreach (GameObject tnk in players)
                        {
                            Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), tnk.Address));
                        }
                    }
                }

                break;

            case "for":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        app.Angle = (float)Convert.ToDouble(ann[1]);

                        if (!ControlloCollisioni(app.PosizioneFutura("f")))
                        {
                            app.moveForward();
                            //e a tutti quelli all'interno della lobby
                            foreach (GameObject tnk in players)
                            {
                                Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), tnk.Address));
                            }
                        }
                    }
                }
                break;

            case "bck":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        app.Angle = (float)Convert.ToDouble(ann[1]);

                        if (!ControlloCollisioni(app.PosizioneFutura("b")))
                        {
                            app.moveBack();
                            foreach (GameObject tnk in players)
                            {
                                Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), tnk.Address));
                            }
                        }
                    }
                }

                break;

            case "dct":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        players.Remove(app);
                        messages.Add(new Messaggio(app.Username + " esce dalla partita", Color.Blue));

                        foreach (GameObject tnk in players.Where(x => x.Id != myId))
                        {
                            Send(new Pacchetto(app.Id + ";dct", tnk.Address));
                        }
                    }
                }

                break;

            case "fire":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        int id = bullets.Count == 0 ? 0 : bullets[bullets.Count - 1].Id + 1;

                        blt = initBullet(app, ann, id);

                        foreach (GameObject tnk in players.Where(x => x.Id != myId))
                        {
                            Send(new Pacchetto("blt;" + blt.Id + ";crt;" + blt.ToString(), tnk.Address));
                        }
                    }
                }

                break;

            case "user":
                app = new GameObject();
                players.Add(app);
                app.InitEnemy(new Vector2(100, 400), Content.Load <Texture2D>("tankEnemy"), Content.Load <Texture2D>("bulletMin"), ann[2], pkt.Address, Convert.ToInt32(ann[1]));
                messages.Add(new Messaggio(ann[2] + " si unisce alla partita", Color.Blue));
                break;

            case "blt":
                blt = bullets.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[1]));

                if (blt != null)
                {
                    if (ann[2] == "wtr")
                    {
                        bullets.Remove(blt);
                        messages.Add(new Messaggio("Colpo a vuoto", Color.Coral));
                    }
                    else
                    {
                        app        = players.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[2]));
                        app.Health = Convert.ToInt32(ann[3]);
                        bullets.Remove(blt);
                        messages.Add(new Messaggio(app.Username + " colpito", Color.Red));
                    }
                }
                else
                {
                    if (ann[2] == "crt")
                    {
                        initBullet(ann);
                    }
                }

                break;

            default:
                int num;

                if (Int32.TryParse(ann[0], out num))
                {
                    app = players.FirstOrDefault(x => x.Id == num);
                    if (players.Contains(app))
                    {
                        if (ann[1] == "pos")
                        {
                            app.Position = new Vector2(Convert.ToInt32(Convert.ToInt32(ann[2]) * rapportoLarghezzaClientServer), Convert.ToInt32(Convert.ToInt32(ann[3]) * rapportoLarghezzaClientServer));
                            app.Angle    = (float)Convert.ToDouble(ann[4]);
                        }
                        else
                        {
                            if (ann[1] == "dct")
                            {
                                messages.Add(new Messaggio(app.Username + " esce dalla partita", Color.Blue));
                                players.Remove(app);
                            }
                            else
                            {
                                if (ann[1] == "win")
                                {
                                    //vittoria del giocatore ID
                                }
                            }
                        }
                    }
                }

                break;
            }
        }
예제 #12
0
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        ///
        protected override void Update(GameTime gameTime)
        {
            KeyboardState keystate  = Keyboard.GetState();
            Pacchetto     pacchetto = null;

            previousState = mouseState;
            mouseState    = Mouse.GetState();

            foreach (GameObject g in players)
            {
                g.Update();
            }

            if (serverStatus)
            {
                foreach (BulletObject b in bullets)
                {
                    b.Update();

                    int    life;
                    int    result = BulletsCollision(b, out life);
                    string msg    = "";

                    if (result != -2)
                    {
                        if (result == -1)
                        {
                            msg = "blt;" + b.Id + ";wtr";
                        }
                        else
                        {
                            msg = "blt;" + b.Id + ";" + result + ";" + life;
                        }

                        foreach (GameObject tnk in players)
                        {
                            Send(new Pacchetto(msg, tnk.Address));
                        }
                    }
                }
            }
            else
            {
                foreach (BulletObject b in bullets)
                {
                    b.Update();
                }
            }


            if (players.Count != 0)
            {
                if (previousState != mouseState)
                {
                    //if(players.FirstOrDefault(x => x.Id == myId).Position == players.FirstOrDefault(x => x.Id == myId).LastPosition)
                    pacchetto = new Pacchetto("ang;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                }

                if (keystate.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.W))
                {
                    pacchetto = new Pacchetto("for;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                }

                if (keystate.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.S))
                {
                    pacchetto = new Pacchetto("bck;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                }

                if (previousState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released && mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                {
                    if (players.FirstOrDefault(x => x.Id == myId).Fire)
                    {
                        pacchetto = new Pacchetto("fire;" + players.FirstOrDefault(x => x.Id == myId).setAngle(), serverAddress);
                    }
                }

                if (pacchetto != null)
                {
                    Send(pacchetto);
                }
            }
            base.Update(gameTime);
        }
예제 #13
0
        private void OnReceive(IAsyncResult ar)
        {
            /* if (InvokeRequired)  // Per gestire il crossthread (questa routine è chiamata da un altro thread)
             * {
             *   BeginInvoke(new del_OnReceive(OnReceive), ar);
             *
             *   return;
             * }*/

            try
            {
                string     strReceived;
                int        idx;
                IPEndPoint ipEPRx;

                if (udpSocket == null)
                {
                    return;
                }

                ipEPRx = new IPEndPoint(IPAddress.Any, 0);
                ep     = (EndPoint)ipEPRx;

                udpSocket.EndReceiveFrom(ar, ref ep);

                string[] astr = ep.ToString().Split(':');
                strReceived = Encoding.UTF8.GetString(abytRx);


                idx = strReceived.IndexOf((char)0);
                if (idx > -1)
                {
                    strReceived = strReceived.Substring(0, idx);
                }

                if (serverStatus)
                {
                    buffer[write] = new Pacchetto(strReceived, astr[0]);

                    if (write == 99)//9999
                    {
                        write       = 0;
                        buffer_full = true;
                    }
                    else
                    {
                        write++;
                    }
                }
                else
                {
                    Analisi(new Pacchetto(strReceived, astr[0]));
                }


                abytRx = new byte[abytRx.Length];
                udpSocket.BeginReceiveFrom(abytRx, 0, abytRx.Length, SocketFlags.None, ref ep, new AsyncCallback(OnReceive), ep);
            }
            catch (ObjectDisposedException ex)
            {
                MessageBox.Show("OnReceive(): Eccezione ObjectDisposedException\n" + ex.Message);
                udpSocket = null;
                Bind();
            }
            catch (Exception ex)
            {
                MessageBox.Show("OnReceive(): Eccezione Exception\n" + ex.Message);
                udpSocket = null;
                Bind();
            }
        }
예제 #14
0
        private void Analisi(Pacchetto pkt)
        {
            GameObject   app;
            BulletObject blt;
            string       pos;
            float        grade;


            var ann = new String[1];

            ann[0] = pkt.Msg;

            if (pkt.Msg.Contains(';'))
            {
                ann = pkt.Msg.Split(';');
            }

            switch (ann[0])
            {
            case "l":
                if (serverStatus)
                {
                    InviaPacchetto(new Pacchetto("0;" + myAddress, pkt.Address));
                }

                break;

            case "0":     //messaggi dal server
                switch (ann[1])
                {
                case "acc":         //gaming true o comunque sono in partita
                    GameObject player = new GameObject();
                    player.Init(new Vector2(19, 41), Content.Load <Texture2D>("tank"), Content.Load <Texture2D>("bulletMin"), "Pippo", myAddress);
                    myId      = Convert.ToInt32(ann[2]);
                    player.Id = myId;
                    players.Add(player);
                    break;

                case "ref":
                    //rimango nel menu, gli spazi sono pieni oppure sono gia all'interno
                    break;

                case "str":
                    //gaming = true;
                    break;

                default:
                    lTimer.Enabled = false;
                    serverAddress  = pkt.Address;

                    if (serverTick != 0)
                    {
                        InviaPacchetto(new Pacchetto("r;" + username, serverAddress));
                    }

                    serverTick = 0;

                    break;
                }
                break;

            case "r":
                if (serverStatus)
                {
                    app = new GameObject();

                    if (players.Count < postiMax && !players.Contains(app))
                    {
                        app.Init(new Vector2(19, 41), Content.Load <Texture2D>("tank"), Content.Load <Texture2D>("bulletMin"), ann[1], pkt.Address);
                        players.Add(app);
                        app.Id = players.IndexOf(app);
                        InviaPacchetto(new Pacchetto("0;acc;" + app.Id, pkt.Address));
                        InviaPacchetto(new Pacchetto(app.Id + ";pos;" + PosizioneIniziale(), pkt.Address));
                    }
                    else
                    {
                        InviaPacchetto(new Pacchetto("0;ref" + app.Id, pkt.Address));
                    }
                }

                break;

            case "for":
                app = players.FirstOrDefault(x => x.Address == pkt.Address);
                if (app != null)
                {
                    pos = app.moveForward();
                    if (VerifyMovement(pos))
                    {
                        //e a tutti quelli all'interno della lobby
                        foreach (GameObject tnk in players.Where(x => x.Id != myId))
                        {
                            InviaPacchetto(new Pacchetto(app.Id + ";pos;" + pos.ToString(), tnk.Address));
                        }

                        Analisi(new Pacchetto(app.Id + ";pos;" + pos.ToString(), serverAddress));     // da lato client host effettuo la mossa... sono avvantaggiato come su COD
                    }
                }
                break;

            case "bck":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        pos = app.moveBack();
                        if (VerifyMovement(pos))
                        {
                            foreach (GameObject tnk in players.Where(x => x.Id != myId))
                            {
                                InviaPacchetto(new Pacchetto(app.Id + ";pos;" + pos.ToString(), tnk.Address));
                            }

                            Analisi(new Pacchetto(app.Id + ";pos;" + pos.ToString(), serverAddress));
                        }
                    }
                }

                break;

            case "dct":
                app = players.FirstOrDefault(x => x.Address == pkt.Address);
                if (app != null)
                {
                    players.Remove(app);

                    foreach (GameObject tnk in players.Where(x => x.Id != myId))
                    {
                        InviaPacchetto(new Pacchetto(app.Id + ";dct", tnk.Address));
                    }
                }
                break;

            case "fire":
                /*app = players.FirstOrDefault(x => x.Address == pkt.Address);
                 * if (app != null)
                 * {
                 *  int id = bullets.Count == 0 ? 0 : bullets[bullets.Count - 1].Id + 1;
                 *
                 *  blt = new Bullet(id, app.Id, app.Pos);
                 *  bullets.Add(blt);
                 *
                 *  foreach (Tank tnk in players.Where(x => x.Id != myId))
                 *  {
                 *      InviaPacchetto(new Pacchetto("blt;" + blt.Id + ";pos;" + blt.Pos.ToString(), tnk.Address));
                 *  }
                 * }*/

                break;

            case "blt":
                /*
                 * blt = bullets.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[1]));
                 * if (ann[2] == "pos")
                 * {
                 *  blt.Pos = new Posizione(Convert.ToInt32(ann[3]), Convert.ToInt32(ann[4]), Convert.ToInt32(ann[5]));
                 *
                 *  foreach (Tank tnk in players.Where(x => x.Id != myId))
                 *  {
                 *      InviaPacchetto(new Pacchetto("blt;" + blt.Id + ";pos;" + blt.Pos.ToString(), tnk.Address));
                 *  }
                 * }
                 * else
                 * {
                 *  if (ann[2] == "0")
                 *  {
                 *      //colpo a vuoto
                 *      bullets.Remove(blt); // rimuovo il proiettile poi rimuoverò anche l'immagine
                 *
                 *      foreach (Tank tnk in players.Where(x => x.Id != myId))
                 *      {
                 *          InviaPacchetto(new Pacchetto("blt;" + blt.Id + ";0", tnk.Address));
                 *      }
                 *  }
                 *  else
                 *  {
                 *      //colpo a segno contro ID in ann[2]
                 *
                 *      foreach (Tank tnk in players.Where(x => x.Id != myId))
                 *      {
                 *          InviaPacchetto(new Pacchetto("blt;" + blt.Id + ";" + ann[2], tnk.Address));
                 *      }
                 *
                 *      //creare funzione verifica colpo
                 *  }
                 *
                 * }
                 */
                break;

            default:
                //metto qua i controlli per i vari giocatori, controllo se esiste in primis, lato client
                List <int> giocatori = new List <int>();
                if (players.Contains(players.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[0]))))
                {
                    app = players.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[0]));

                    if (ann[1] == "pos")
                    {
                        app.Position    = new Vector2(Convert.ToInt32(ann[2]), Convert.ToInt32(ann[3]));
                        app.BoundingBox = new Rectangle(Convert.ToInt32(ann[2]), Convert.ToInt32(ann[3]), 19, 41);
                        app.angle       = (float)Convert.ToDouble(ann[4]);
                    }
                    else
                    {
                        if (ann[1] == "dct")
                        {
                            players.Remove(app);
                        }
                        else
                        {
                            if (ann[1] == "win")
                            {
                                //vittoria del giocatore ID
                            }
                            else
                            {
                                if (ann[1] == "user")
                                {
                                }
                            }
                        }
                    }
                }

                break;
            }
        }
예제 #15
0
        private void Analisi(Pacchetto pkt)
        {
            GameObject   app;
            BulletObject blt;
            string       pos;

            var ann = new String[1];

            ann[0] = pkt.Msg;

            if (pkt.Msg.Contains(';'))
            {
                ann = pkt.Msg.Split(';');
            }

            switch (ann[0])
            {
            case "l":
                if (serverStatus)
                {
                    Send(new Pacchetto("srv;" + myAddress, pkt.Address));
                }

                break;

            case "srv":     //messaggi dal server
                switch (ann[1])
                {
                case "acc":         //gaming true o comunque sono in partita
                    initMyPlayer(Convert.ToInt32(ann[2]));
                    break;

                case "ref":
                    //rimango nel menu, gli spazi sono pieni oppure sono gia all'interno
                    break;

                case "str":
                    //gaming = true;
                    break;

                default:
                    lTimer.Stop();
                    serverAddress = pkt.Address;
                    //operazione che eseguo solo adesso in testing
                    if (serverTick != 0)
                    {
                        Send(new Pacchetto("r;" + username, serverAddress));
                    }

                    serverTick = 0;
                    break;
                }
                break;

            case "r":
                if (serverStatus)
                {
                    if (players.Count < postiMax && (players.FirstOrDefault(x => x.Username == ann[1] && x.Address == pkt.Address)) == null)     //ann[1] username
                    {
                        app = new GameObject();
                        players.Add(app);
                        app.InitEnemy(new Vector2(100, 400), Content.Load <Texture2D>("tankEnemy"), Content.Load <Texture2D>("bulletMin"), ann[1], pkt.Address, players.IndexOf(app));
                        Send(new Pacchetto("srv;acc;" + app.Id, pkt.Address));
                        Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), pkt.Address));
                        SendPlayersInformation(app);
                        SendPlayerInformation(app);
                    }
                    else
                    {
                        Send(new Pacchetto("srv;ref", pkt.Address));
                    }
                }

                break;

            case "ang":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        app.angle = (float)Convert.ToDouble(ann[1]);
                        foreach (GameObject tnk in players)
                        {
                            Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), tnk.Address));
                        }
                    }
                }

                break;

            case "for":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        app.angle = (float)Convert.ToDouble(ann[1]);
                        pos       = app.moveForward();
                        if (VerifyMovement(pos))
                        {
                            //e a tutti quelli all'interno della lobby
                            foreach (GameObject tnk in players)
                            {
                                Send(new Pacchetto(app.Id + ";pos;" + app.ToString(), tnk.Address));
                            }
                        }
                    }
                }
                break;

            case "bck":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        app.angle = (float)Convert.ToDouble(ann[1]);
                        pos       = app.moveBack();
                        if (VerifyMovement(pos))
                        {
                            foreach (GameObject tnk in players)
                            {
                                Send(new Pacchetto(app.Id + ";pos;" + pos, tnk.Address));
                            }
                        }
                    }
                }

                break;

            case "dct":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        players.Remove(app);

                        foreach (GameObject tnk in players.Where(x => x.Id != myId))
                        {
                            Send(new Pacchetto(app.Id + ";dct", tnk.Address));
                        }
                    }
                }

                break;

            case "fire":
                if (serverStatus)
                {
                    app = players.FirstOrDefault(x => x.Address == pkt.Address);
                    if (app != null)
                    {
                        int id = bullets.Count == 0 ? 0 : bullets[bullets.Count - 1].id + 1;

                        blt = new BulletObject();
                        blt.Init(new Vector2(app.Position.X, app.Position.Y), Content.Load <Texture2D>("bulletMin"), (float)Convert.ToDouble(ann[1]));
                        blt.id = id;
                        bullets.Add(blt);
                        time          = new myTimer(blt, 50);
                        time.Elapsed += myTimerTick;
                        time.Start();

                        foreach (GameObject tnk in players.Where(x => x.Id != myId))
                        {
                            Send(new Pacchetto("blt;" + blt.id + ";crt;" + blt.ToString(), tnk.Address));
                        }
                    }
                }

                break;

            case "user":
                app = new GameObject();
                players.Add(app);
                app.InitEnemy(new Vector2(100, 400), Content.Load <Texture2D>("tankEnemy"), Content.Load <Texture2D>("bulletMin"), ann[2], pkt.Address, Convert.ToInt32(ann[1]));
                break;

            case "blt":
                blt = bullets.FirstOrDefault(x => x.id == Convert.ToInt32(ann[1]));

                if (blt != null)
                {
                    if (ann[2] == "wtr")
                    {
                        bullets.Remove(blt);
                    }
                    else
                    {
                        if (ann[2] == "pos")
                        {
                            blt.Position = new Vector2(Convert.ToInt32(ann[3]), Convert.ToInt32(ann[4]));
                            blt.angle    = (float)Convert.ToDouble(ann[5]);
                        }
                    }
                }
                else
                {
                    if (ann[2] == "crt")
                    {
                        blt = new BulletObject();
                        blt.Init(new Vector2(Convert.ToInt32(ann[3]), Convert.ToInt32(ann[4])), Content.Load <Texture2D>("bulletMin"), (float)Convert.ToDouble(ann[5]));
                        blt.id = Convert.ToInt32(ann[1]);
                        bullets.Add(blt);
                    }
                }

                break;

            default:
                //metto qua i controlli per i vari giocatori, controllo se esiste in primis, lato client
                app = players.FirstOrDefault(x => x.Id == Convert.ToInt32(ann[0]));
                if (players.Contains(app))
                {
                    if (ann[1] == "pos")
                    {
                        app.Position = new Vector2(Convert.ToInt32(ann[2]), Convert.ToInt32(ann[3]));
                        app.angle    = (float)Convert.ToDouble(ann[4]);
                    }
                    else
                    {
                        if (ann[1] == "dct")
                        {
                            players.Remove(app);
                        }
                        else
                        {
                            if (ann[1] == "win")
                            {
                                //vittoria del giocatore ID
                            }
                        }
                    }
                }

                break;
            }
        }