private void UpdateMessages(Protocol.BaseProtocol proto)
    {
        Protocol.Message message = proto.AsType <Protocol.Message>();

        string receivedTime = System.DateTime.Now.ToShortTimeString();

        string outStr = string.Format("{0}\n{1} | {2}: {3}", output.text, receivedTime, message.from_client_name, message.message);

        output.text = outStr;
    }
 public void SendMsg()
 {
     if (!string.IsNullOrWhiteSpace(input.text))
     {
         Protocol.Message msg = new Protocol.Message()
         {
             message = input.text
         };
         msg.Send();
         input.text = "";
     }
 }
Beispiel #3
0
    void StartingPosition(int[] positions)
    {
        Protocol.StartingPosition sp = new Protocol.StartingPosition {
        };
        sp.Position.Add(positions);

        // final message that we can send
        Protocol.Message msg =
            new Protocol.Message {
            Type = "starting_position", StartingPosition = sp
        };

        sendMessage(msg);
    }
Beispiel #4
0
    void sendChatMessage(string data)
    {
        Protocol.ChatMessage chatMsg =
            new Protocol.ChatMessage {
            User = clientName, Content = data
        };

        Protocol.Message msg =
            new Protocol.Message {
            Type = "chat_message", ChatMessage = chatMsg
        };

        sendMessage(msg);
    }
Beispiel #5
0
    void sendMessage(Protocol.Message msg)
    {
        byte[] msgBytes  = msg.ToByteArray();
        byte[] msgLength = BitConverter.GetBytes(msgBytes.Length);
        if (!BitConverter.IsLittleEndian)
        {
            Array.Reverse(msgLength);
        }

        byte[] finalMessage = new byte[4 + msgBytes.Length];
        Array.Copy(msgLength, finalMessage, 4);
        Array.Copy(msgBytes, 0, finalMessage, 4, msgBytes.Length);

        stream.Write(finalMessage, 0, finalMessage.Length);
    }
Beispiel #6
0
    void register()
    {
        if (username == "" || password == "")
        {
            GameObject.Find("LogRegForm")
            .GetComponent <log_reg_form>()
            .LogInError("Veuillez saisir vos identifiants.");
            return;
        }

        Protocol.RegisterRequest rr =
            new Protocol.RegisterRequest {
            Username = username, Password = password
        };

        Protocol.Message msg =
            new Protocol.Message {
            Type = "register_request", RegisterRequest = rr
        };

        sendMessage(msg);
    }
Beispiel #7
0
    void updatePlayerPosition(Protocol.Vector vecPosition,
                              Protocol.Vector vecRotation,
                              Protocol.Vector vecScale,
                              Protocol.Vector vecVelocity)
    {
        int carType =
            GameObject.Find("UserStats").GetComponent <UserStats>().carIndex;
        int carR =
            GameObject.Find("UserStats").GetComponent <UserStats>().currentCarR;
        int carG =
            GameObject.Find("UserStats").GetComponent <UserStats>().currentCarG;
        int carB =
            GameObject.Find("UserStats").GetComponent <UserStats>().currentCarB;

        // all together
        Protocol.UpdatePlayerPosition upp =
            new Protocol.UpdatePlayerPosition {
            Position  = vecPosition,
            Direction = vecRotation,
            Scale     = vecScale,
            User      = clientName,
            Velocity  = vecVelocity,
            CarType   = carType,
            CarR      = carR,
            CarG      = carG,
            CarB      = carB
        };

        // final message that we can send
        Protocol.Message msg = new Protocol.Message {
            Type = "update_player_position",
            UpdatePlayerPosition = upp
        };

        sendMessage(msg);
    }
Beispiel #8
0
    void filterIncomingMessages(Protocol.Message parsedData)
    {
        GameObject player;
        string     user;

        switch (parsedData.Type)
        {
        case "update_player_position":
            Protocol.UpdatePlayerPosition upp = parsedData.UpdatePlayerPosition;
            Protocol.Vector vecPos            = upp.Position;
            Protocol.Vector vecRot            = upp.Direction;
            Protocol.Vector vecScale          = upp.Scale;
            Protocol.Vector vecVelocity       = upp.Velocity;
            user = upp.User;

            if (user == clientName)
            {
                break;
            }

            player = getPlayer(user, upp.CarType, upp.CarR, upp.CarG, upp.CarB);

            player.transform.localPosition =
                new Vector3(vecPos.X, vecPos.Y, vecPos.Z);
            player.transform.localScale =
                new Vector3(vecScale.X, vecScale.Y, vecScale.Z);

            player.transform.rotation = Quaternion.Lerp(
                player.transform.rotation,
                Quaternion.Euler(new Vector3(vecRot.X, vecRot.Y, vecRot.Z)),
                Time.time * 0.2f);

            Rigidbody rb = player.GetComponent <Rigidbody>();
            rb.velocity = new Vector3(vecVelocity.X, vecVelocity.Y, vecVelocity.Z);
            break;

        case "update_player_status":
            Protocol.UpdatePlayerStatus ups = parsedData.UpdatePlayerStatus;

            IEnumerator <bool> num  = ups.WentThrough.GetEnumerator();
            List <bool>        list = new List <bool>();
            while (num.MoveNext())
            {
                list.Add(num.Current);
            }
            bool[] wentThrough = list.ToArray();

            int  lapCount                     = ups.LapCount;
            bool hasHitSFLineOnce             = ups.HasHitSFLineOnce;
            int  cpCount                      = ups.CpCount;
            int  nextCheckpointNumber         = ups.NextCheckpointNumber;
            int  supposedNextCheckpointNumber = ups.SupposedNextCheckpointNumber;
            int  virtual_lap_count            = ups.VirtualLapCount;
            int  lastHittedCP                 = ups.LastHittedCp;
            int  secondLastHittedCP           = ups.SecondLastHittedCp;
            user = ups.User;

            if (user == clientName)
            {
                break;
            }

            player = getPlayer(user, 0, 0, 0, 0);

            player.GetComponent <Player_Info_Ingame>().lap_count        = lapCount;
            player.GetComponent <Player_Info_Ingame>().hasHitSFLineOnce =
                hasHitSFLineOnce;
            player.GetComponent <Player_Info_Ingame>().cp_count             = cpCount;
            player.GetComponent <Player_Info_Ingame>().nextCheckpointNumber =
                nextCheckpointNumber;
            player.GetComponent <Player_Info_Ingame>().supposedNextCheckpointNumber =
                supposedNextCheckpointNumber;
            player.GetComponent <Player_Info_Ingame>().wentThrough       = wentThrough;
            player.GetComponent <Player_Info_Ingame>().virtual_lap_count =
                virtual_lap_count;
            player.GetComponent <Player_Info_Ingame>().lastHittedCP       = lastHittedCP;
            player.GetComponent <Player_Info_Ingame>().secondLastHittedCP =
                secondLastHittedCP;

            break;

        case "update_player_status_request":
            GameObject[] cars = GameObject.FindGameObjectsWithTag("Player");

            foreach (GameObject car in cars)
            {
                if (car.GetComponent <CarController>().isLocalPlayer)
                {
                    car.GetComponent <CarController>().updatePlayerStatus();
                }
            }

            break;

        case "chat_message":
            Protocol.ChatMessage chatMsg = parsedData.ChatMessage;
            Debug.Log("Received from " + chatMsg.User +
                      " the following message: " + chatMsg.Content);
            break;

        case "disconnect":
            user = parsedData.Disconnect.User;
            Destroy(getPlayer(user, 0, 0, 0, 0));
            players.Remove(user);
            break;
        // case "starting_position":
        //   Protocol.StartingPosition sp = parsedData.StartingPosition;
        //   IEnumerator<int> numInt = sp.Position.GetEnumerator();
        //   List<int> listInt = new List<int>();
        //   while (numInt.MoveNext()) {
        //     listInt.Add(numInt.Current);
        //   }
        //   int[] positions = listInt.ToArray();

        //   // @TODO: do something with positions

        //   break;
        case "register_response":
            Protocol.RegisterResponse registerResponse =
                parsedData.RegisterResponse;
            bool   registredSuccess  = registerResponse.Success;
            string registredUsername = registerResponse.Username;

            if (registredSuccess)
            {
                updateUserStats(registerResponse.UserStats);
                GameObject.Find("LogRegForm")
                .GetComponent <log_reg_form>()
                .RegisterSuccess();
                clientName = registredUsername;
            }
            else
            {
                Debug.Log("Error while trying to register as " + registredUsername);
                GameObject.Find("LogRegForm")
                .GetComponent <log_reg_form>()
                .RegisterError("Nom d'utilisateur déjà existant.");
            }

            break;

        case "login_response":
            Protocol.LoginResponse loginResponse = parsedData.LoginResponse;
            bool   loggedSuccess  = loginResponse.Success;
            string loggedUsername = loginResponse.Username;

            if (loggedSuccess)
            {
                updateUserStats(loginResponse.UserStats);
                GameObject.Find("LogRegForm")
                .GetComponent <log_reg_form>()
                .LogInSuccess();
                clientName = loggedUsername;
            }
            else
            {
                Debug.Log("Error while trying to log in as " + loggedUsername);
                GameObject.Find("LogRegForm")
                .GetComponent <log_reg_form>()
                .LogInError("Nom d'utilisateur ou mot de passe incorrect.");
            }

            break;

        case "room_list_response":
            Protocol.RoomListResponse rlr = parsedData.RoomListResponse;

            foreach (Protocol.RoomListItem rli in rlr.RoomList)
            {
                List <string> playersUsernameList = new List <string>();
                List <int>    playersNbRacesList  = new List <int>();
                List <int>    playersNbWinsList   = new List <int>();
                List <string> playersRecordList   = new List <string>();

                IEnumerator <Protocol.Player> numPlayers = rli.Players.GetEnumerator();
                while (numPlayers.MoveNext())
                {
                    playersUsernameList.Add(numPlayers.Current.Username);
                    playersNbRacesList.Add(numPlayers.Current.NbRaces);
                    playersNbWinsList.Add(numPlayers.Current.NbWins);
                    playersRecordList.Add(numPlayers.Current.Record);
                }

                string[] playersUsername = playersUsernameList.ToArray();
                int[]    playersNbRaces  = playersNbRacesList.ToArray();
                int[]    playersNbWins   = playersNbWinsList.ToArray();
                string[] playersRecord   = playersRecordList.ToArray();

                List <int>        rliStartingPositionsList = new List <int>();
                IEnumerator <int> numSP = rli.StartingPositions.GetEnumerator();
                while (numSP.MoveNext())
                {
                    rliStartingPositionsList.Add(numSP.Current);
                }
                int[] rliStartingPositions = rliStartingPositionsList.ToArray();

                GameObject.Find("Rooms_Script")
                .GetComponent <room_info_container>()
                .addOrUpdateRoom(rli.Id, rli.RoomType, rli.IdCircuit,
                                 rli.MaxPlayers, rli.NbPlayers, playersUsername,
                                 playersNbRaces, playersNbWins, playersRecord,
                                 rliStartingPositions);
            }

            break;

        case "join_room_response":
            Protocol.JoinRoomResponse jrr    = parsedData.JoinRoomResponse;
            Protocol.RoomListItem     rlitem = jrr.Room;

            if (jrr.Success)
            {
                List <string> playersUsernameList = new List <string>();
                List <int>    playersNbRacesList  = new List <int>();
                List <int>    playersNbWinsList   = new List <int>();
                List <string> playersRecordList   = new List <string>();

                IEnumerator <Protocol.Player> numPlayers =
                    rlitem.Players.GetEnumerator();
                while (numPlayers.MoveNext())
                {
                    playersUsernameList.Add(numPlayers.Current.Username);
                    playersNbRacesList.Add(numPlayers.Current.NbRaces);
                    playersNbWinsList.Add(numPlayers.Current.NbWins);
                    playersRecordList.Add(numPlayers.Current.Record);
                }

                string[] playersUsername = playersUsernameList.ToArray();
                int[]    playersNbRaces  = playersNbRacesList.ToArray();
                int[]    playersNbWins   = playersNbWinsList.ToArray();
                string[] playersRecord   = playersRecordList.ToArray();

                // List<int> rlitemStartingPositionsList = new List<int>();
                // IEnumerator<int> nSP = rlitem.StartingPositions.GetEnumerator();
                // while (nSP.MoveNext()) {
                //   rlitemStartingPositionsList.Add(nSP.Current);
                // }
                // int[] rlitemStartingPositions =
                // rlitemStartingPositionsList.ToArray();

                GameObject.Find("Rooms_Script")
                .GetComponent <room_info_container>()
                .goToLobby(rlitem.Id, rlitem.RoomType, rlitem.IdCircuit,
                           rlitem.MaxPlayers, rlitem.NbPlayers, playersUsername,
                           playersNbRaces, playersNbWins, playersRecord);
            }
            break;

        case "start_room":
            Protocol.StartRoom sr = parsedData.StartRoom;

            if (sr.Success)
            {
                IEnumerator coroutine;
                coroutine = GameObject.Find("Rooms_Script")
                            .GetComponent <room_info_container>()
                            .roomStartCountdown(10.0f);
                StartCoroutine(coroutine);
            }

            break;

        case "global_record":
            Protocol.GlobalRecord gr = parsedData.GlobalRecord;
            Debug.Log(gr.Track + gr.Record);
            if (gr.Track == 1)
            {
                GameObject.Find("UserStats")
                .GetComponent <UserStats>()
                .track1WorldRecord = gr.Record;
            }
            if (gr.Track == 2)
            {
                GameObject.Find("UserStats")
                .GetComponent <UserStats>()
                .track2WorldRecord = gr.Record;
            }
            if (gr.Track == 3)
            {
                GameObject.Find("UserStats")
                .GetComponent <UserStats>()
                .track3WorldRecord = gr.Record;
            }
            break;

        default:
            Debug.LogWarning("unsupported message type for " + parsedData);
            break;
        }
    }