private void UpdateGameClients(Protocol.BaseProtocol proto)
    {
        // TODO: prevent game clients from being set again.

        Protocol.GameClientList clientList = proto.AsType <Protocol.GameClientList>();
        clientData = new Client[clientList.client_ids.Length];

        for (int i = 0; i < clientList.client_ids.Length; i++)
        {
            if (clientList.client_ids[i] == playerData.clientId)
            {
                playerData.playerId = clientList.client_player_ids[i];
            }

            clientData[i] = new Client(clientList.client_ids[i], clientList.client_nicknames[i], clientList.client_player_ids[i]);
        }
        print(Inst.clientData.Length + " :: " + clientData.Length);
        gameClientsSet?.Invoke(clientData);

        // now that the final list of active clients have arrived
        // we can now notify the server that the scene is ready to play
        // Also to be far, we should make sure that the object list has been received as well
        // but thats a task for later. for now we'll just hope its all setup correctly :)
        // TODO: ^^^
        // TODO: Uncomment... Im going to get the relix to work first. ( it will be easier to test :) )
        Protocol.ClientStatus clientStatus = new Protocol.ClientStatus()
        {
            StatusType = Protocol.ClientStatusType.GameReady,
            ok         = true
        };

        clientStatus.Send();
    }
    private void UpdateLobbyList(Protocol.BaseProtocol proto)
    {
        print("Identity l processed................");

        Protocol.LobbyList lobbyList = proto.AsType <Protocol.LobbyList>();

        // go thorough every button (that we need or pre existing)
        // if there currently more items than needed will just switch them off
        // otherwise we add new items if neeed
        for (int i = 0; i < Mathf.Max(lobbyList.lobby_ids.Length, lobbyListGroups.Count); i++)
        {
            if (i >= lobbyListGroups.Count)
            {   // Add new buttons
                UI_LobbyButtonGroup button = Instantiate <UI_LobbyButtonGroup>(baseButtonGroup, parent);
                lobbyListGroups.Add(button);
            }
            else if (i >= lobbyList.lobby_ids.Length)
            {   // switch off existing buttons
                lobbyListGroups[i].gameObject.SetActive(false);
            }
            else
            {   // update info
                lobbyListGroups[i].gameObject.SetActive(true);
            }

            // update position and info
            if (i < lobbyList.lobby_ids.Length)
            {
                (lobbyListGroups[i].transform as RectTransform).anchoredPosition = startPosition - (buttonOffset * i);
                lobbyListGroups[i].SetData(lobbyList.lobby_ids[i], lobbyList.lobby_names[i], "Level Name", lobbyList.current_clients[i], lobbyList.max_clients[i]);
            }
        }
    }
    /// <summary>
    /// Updates the objects position when the server says so. :D
    /// </summary>
    /// <param name="proto"></param>
    public void UpdateServerObject(Protocol.BaseProtocol proto)
    {
        Protocol.ServerObject obj = proto.AsType <Protocol.ServerObject>();

        if (obj.Type != serverObjectType || obj.object_id != serverObjectId)
        {
            return;
        }

        print(obj.Action + "==" + Protocol.ServerObject.ObjectAction.Destroy + " && " + obj.Type + "==" + serverObjectType + " && " + obj.object_id + "==" + serverObjectId);
        if (obj.Action == Protocol.ServerObject.ObjectAction.Destroy)
        {
            Destroy(gameObject);
        }

        if (obj.Action != Protocol.ServerObject.ObjectAction.Defualt)
        {
            return;
        }

        // stop the nav agent if present.
        ClientAgent agent = GetComponent <ClientAgent>();

        if (agent != null && !agent.FindingPath && agent.Naving)
        {
            print("Stop Agent.");
            agent?.CancelAction();
        }

        print("TAG " + gameObject.tag + " transform.position " + transform.position);

        // update the position of the object.
        transform.position    = lastPosition = obj.Position;
        transform.eulerAngles = lastRotation = obj.Rotation;
    }
    private void Update_Clients(Protocol.BaseProtocol proto)
    {
        Protocol.LobbyClientList clientList = proto.AsType <Protocol.LobbyClientList>();

        ClientCount = clientList.client_ids.Length;
        name_text.SetText(string.Join("\n", clientList.client_nicknames));
    }
    private void UpdateLobbyInfo(Protocol.BaseProtocol proto)
    {
        Protocol.LobbyInfo lobbyInfo = proto.AsType <Protocol.LobbyInfo>();

        min_players = lobbyInfo.min_players;
        max_players = lobbyInfo.max_players;

        level_name_text.text    = lobbyInfo.level_name;
        level_players_text.text = string.Format("{0} of {1}", clientList.ClientCount, max_players);

        float timeTillStart = lobbyInfo.starts_in;

        if (lobbyInfo.starts_in <= 0)
        {
            level_start_in_text.text = string.Format("Requires {0} more players", (min_players - clientList.ClientCount));
            if (countdownTimer != null)
            {
                StopCoroutine(countdownTimer);
            }
        }
        else
        {
            if (countdownTimer != null)
            {
                StopCoroutine(countdownTimer);
            }

            countdownTimer = StartCoroutine(CountdownTimer(timeTillStart));
        }
    }
    private void ProcessesPing(Protocol.BaseProtocol proto)
    {
        Protocol.PingTime ping = proto.AsType <Protocol.PingTime>();

        System.TimeSpan t = System.DateTime.UtcNow - new System.DateTime(1970, 1, 1);
        double          millisSinceEpoch = t.TotalMilliseconds;

        double total_time     = millisSinceEpoch - ping.client_send_time;
        double time_to_server = ping.server_receive_time - ping.client_send_time;
        double return_time    = millisSinceEpoch - ping.server_receive_time;

        pingTimeText.text = string.Format("ping: {0:f3}ms", total_time);

        /* CSV HEADERS
         * saveLoadFile.AddRow( new string[] {
         * "Client send time",
         * "ServerRecevie time",
         * "client receive time",
         * "total time",
         * "time to server",
         * "return time"
         * } );
         */
        csvFile.AddRow(new string[] {
            ping.client_send_time.ToString(),
            ping.server_receive_time.ToString(),
            millisSinceEpoch.ToString(),
            total_time.ToString(),
            time_to_server.ToString(),
            return_time.ToString()
        });

        csvFile.SaveCSV();
    }
Пример #7
0
    private void ReceiveOtherClientStatus(Protocol.BaseProtocol protocol)
    {
        Protocol.StatusProtocol status = protocol as Protocol.StatusProtocol;

        if (status.IsType(Protocol.StatusProtocol.Type.Client))
        {
            if (status.ok)
            {
                currentGamePlayers.Add(nextLobbyId, new Client(status.from_client));
                ++nextLobbyId;
            }
            else
            {
                foreach (KeyValuePair <int, Client> kp in currentGamePlayers)
                {
                    if (kp.Value.nickname == status.from_client)
                    {
                        currentGamePlayers.Remove(kp.Key);
                        PlayerDisconnected?.Invoke(kp.Key);
                        break;
                    }
                }
            }
        }

        GameInfoUpdated?.Invoke();
    }
Пример #8
0
    private void ChangePlayer(Protocol.BaseProtocol protocol)
    {
        Protocol.ChangePlayerProtocol changePlayer = protocol as Protocol.ChangePlayerProtocol;

        currentPlayerID = changePlayer.player_id;

        GameInfoUpdated?.Invoke();
    }
    private void PrintServerStatus(Protocol.BaseProtocol proto)
    {
        Protocol.ServerStatus serverStatus = proto.AsType <Protocol.ServerStatus>();

        if (!serverStatus.ok)
        {
            AddMessage("Error: " + serverStatus.message, 30);
        }
    }
Пример #10
0
    private void CollectItem(Protocol.BaseProtocol proto)
    {
        Protocol.CollectItem collectItem = proto.AsType <Protocol.CollectItem>();

        if (collectItem.player_id == playerId)
        {
            itemHold.CollectItem(collectItem.object_id);
        }
    }
Пример #11
0
    public void clientRegistered(Protocol.BaseProtocol protocol)
    {
        Protocol.ClientRegistered registered = protocol as Protocol.ClientRegistered;

        if (registered.ok)
        {
            LoadLevel();
        }
    }
Пример #12
0
    public void ServerError(Protocol.BaseProtocol protocol)
    {
        Protocol.StatusProtocol status = protocol as Protocol.StatusProtocol;

        if (status.IsType(Protocol.StatusProtocol.Type.Server) && !status.ok)
        {
            LoadLevel();
        }
    }
Пример #13
0
    private void MovePlayer(Protocol.BaseProtocol protocol)
    {
        Protocol.MovePlayerProtocol movePlayer = protocol as Protocol.MovePlayerProtocol;

        if (movePlayer.player_id == PlayerId)
        {
            MoveAgentToPosition(movePlayer.position);
        }
    }
Пример #14
0
    private void ReceiveServerStatus(Protocol.BaseProtocol protocol)
    {
        Protocol.StatusProtocol serverStatus = protocol as Protocol.StatusProtocol;

        if (serverStatus.IsType(Protocol.StatusProtocol.Type.Server) && !serverStatus.ok)
        {
            SetConnectionStatus(ConnectionStatus.Error, serverStatus.message);
        }
    }
Пример #15
0
    private void ReciveClientIdentityRequest(Protocol.BaseProtocol protocol)
    {
        // fill in the info and send it back to the sever
        Protocol.ClientIdentity clientIdentity = protocol as Protocol.ClientIdentity;

        clientIdentity.nickname = localClient.nickname;

        SocketClient.ActiveSocket.QueueMessage(clientIdentity);
    }
Пример #16
0
    public void MovePlayer(Protocol.BaseProtocol proto)
    {
        Protocol.MovePlayer movePlayer = proto.AsType <Protocol.MovePlayer>();

        if (movePlayer.player_id == playerId)
        {
            clientAgent.MoveAgent(movePlayer.Position);
            currentAction = clientAgent;
        }
    }
    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;
    }
Пример #18
0
    public void BuildObject(Protocol.BaseProtocol protocol)
    {
        Protocol.BuildObject buildObj = protocol.AsType <Protocol.BuildObject>();

        if (buildObj.player_id != playerId)
        {
            return;
        }

        build.BuildObject(buildObj.obj_id);
    }
Пример #19
0
 public void InvokeProtocol(BaseProtocol proto)
 {
     if (protocolEvents.ContainsKey(proto.Identity))
     {
         protocolEvents[proto.Identity]?.Invoke(proto);
     }
     else
     {
         Debug.LogErrorFormat("Unable to invoke protocol {0}", proto.Identity);
     }
 }
    private void ChangePlayer(Protocol.BaseProtocol protocol)
    {
        Protocol.ChangePlayerProtocol changePlayer = protocol as Protocol.ChangePlayerProtocol;

        if (countdownTimer != null)
        {
            StopCoroutine(countdownTimer);
        }

        countdownTimer = StartCoroutine(Countdown(Time.time + changePlayer.turn_len));
    }
Пример #21
0
    /// <summary>
    /// Add a message to the que and starts the send thread if not already running
    /// </summary>
    /// <param name="message"></param>
    public void SendMsg(Protocol.BaseProtocol message)
    {
        outboundQueue.Enqueue(message);

        if (sendThread == null || !sendThread.IsAlive)
        {
            sendThread = new Thread(SendThread);
            sendThread.Start();
        }

        print("outbound message cued");
    }
Пример #22
0
    public void LookAt(Protocol.BaseProtocol protocol)
    {
        Protocol.LookAtPosition lookAtPos = protocol.AsType <Protocol.LookAtPosition>();

        if (lookAtPos.player_id != playerId)
        {
            return;
        }

        lookAtPosition.LookAtPosition(lookAtPos.Position);
        currentAction = lookAtPosition;
    }
Пример #23
0
    private void UpdateRelicCount(Protocol.BaseProtocol proto)
    {
        Protocol.RelicCount relicCount = proto.AsType <Protocol.RelicCount>();

        // make sure that the count belongs to the player
        if (relicCount.player_id != GameCtrl.Inst.playerData.playerId)
        {
            return;
        }

        relicCountText.text = string.Format("{0} of {1}", relicCount.count.ToString(), 4);
    }
Пример #24
0
    private void ReciveClientRegistered(Protocol.BaseProtocol protocol)
    {
        Protocol.ClientRegistered registered = protocol as Protocol.ClientRegistered;

        if (registered.ok)
        {
            localClient.reg_key = registered.reg_key;
        }


        Debug.Log("REG KEY: " + localClient.reg_key);
    }
Пример #25
0
    private void LaunchGame(Protocol.BaseProtocol protocol)
    {
        Protocol.LaunchGameProtocol lGame = protocol as Protocol.LaunchGameProtocol;

        currentGamePlayers.Clear(); // starting a new game

        localClient.player_id = lGame.player_id;

        currentGamePlayers.Add(localClient.player_id, localClient);

        SceneManager.LoadScene("SampleScene", LoadSceneMode.Single);
    }
Пример #26
0
    private void SendThread()
    {
        print(ConnStatus + " :: " + outboundQueue.Count);
        while (ConnStatus == ConnectionStatus.Connected && outboundQueue.Count > 0)
        {
            Protocol.BaseProtocol message = outboundQueue.Dequeue() as Protocol.BaseProtocol;
            string data = message.GetJson(out int messageLength);

            // the byte converter, converts in chunks of 4, we only need the 2 for the len and 1 for the char
            byte[] _dataLenBytes     = System.BitConverter.GetBytes(messageLength);
            byte[] _dataIdenityBytes = System.BitConverter.GetBytes(message.Identity);

            byte[] dataLenBytes     = new byte[MESSAGE_LEN_PACKAGE_SIZE];
            byte[] dataIdenityBytes = new byte[MESSAGE_TYPE_PACKAGE_SIZE];
            byte[] dataBytes        = encoder.GetBytes(data);

            // TODO: Make this work for different packet sizes
            // Get the bytes that we need
            // We are working with Big endian on the server :)
            if (System.BitConverter.IsLittleEndian)
            {   // use first two bytes reversed for little endian
                byte temp = _dataLenBytes[0];
                dataLenBytes[0]     = _dataLenBytes[1];
                dataLenBytes[1]     = temp;
                dataIdenityBytes[0] = _dataIdenityBytes[0];
            }
            else
            {   // use last two bytes for big endian
                dataLenBytes[0]     = _dataLenBytes[3];
                dataLenBytes[1]     = _dataLenBytes[4];
                dataIdenityBytes[0] = _dataIdenityBytes[4];
            }

            Debug.LogWarningFormat("Sending mesage Length: {0}; Idenity: {1}", messageLength, message.Identity);
            Debug.Log("Outbound Message: " + data);

            try
            {
                socket.Send(dataLenBytes);                                      // send the length of the message
                socket.Send(dataIdenityBytes);                                  // send the idenity of the message
                socket.Send(dataBytes);                                         // send the message
            }
            catch (System.Exception e)
            {
                Debug.LogError(e);
                ConnStatus = ConnectionStatus.Error;
                Clean      = true;
                break;
            }
        }
    }
    private void IdentityStatus(Protocol.BaseProtocol prto)
    {
        Protocol.IdentityStatus status = prto.AsType <Protocol.IdentityStatus>();

        if (!status.ok)
        {
            Debug.LogError("Error Bad Identity status");
            return;
        }

        playerData.clientId = status.client_id;
        playerData.reg_key  = status.reg_key;

        UIAct_MessageList.MessageList.AddMessage(string.Format("Wellcom, {0} ({1} :: {2})", playerData.nickname, playerData.clientId, playerData.reg_key), 20);
    }
Пример #28
0
    private void StartGame(Protocol.BaseProtocol protocol)
    {
        Protocol.StartGameProtocol startgame = protocol as Protocol.StartGameProtocol;

        if (startgame.ok)
        {
            gameActive = true;
        }
        // else
        // about the game
        // TODO: above

        GameInfoUpdated?.Invoke();
        GameActiveStateChanged?.Invoke(gameActive);
    }
Пример #29
0
    private void PreStartGame(Protocol.BaseProtocol protocol)
    {
        Protocol.PreStartGameProtocol preStartGame = protocol as Protocol.PreStartGameProtocol;
        currentGamePlayers.Clear();

        for (int i = 0; i < preStartGame.player_ids.Length; i++)
        {
            int    pid    = preStartGame.player_ids[i];
            Client client = new Client(preStartGame.player_names[i]);

            currentGamePlayers.Add(pid, client);
        }

        currentPlayerID = 0;
        PlayersJoined?.Invoke(currentGamePlayers);
    }
    private void IdentityRequest(Protocol.BaseProtocol prto)
    {
        Protocol.IdentityRequest request = prto.AsType <Protocol.IdentityRequest>();

        if (string.IsNullOrWhiteSpace(playerData.nickname))      // only set a nickname if we dont have one already.
        {
            playerData.nickname = request.nickname;
        }
        else                                                     // otherwise return our current nickname
        {
            request.nickname = playerData.nickname;
        }

        request.client_id = playerData.clientId;
        request.reg_key   = playerData.reg_key;

        ClientSocket.ActiveSocket.SendMsg(request);
    }