Ejemplo n.º 1
0
 private void UpdateConnectionsList(NetConnection connection, NetConnectionStatus status)
 {
     if (status == NetConnectionStatus.Connected)
     {
         string name = connection.RemoteHailMessage.ReadString();
         Output(name + " @" + connection.RemoteEndPoint + " has connected");
         ConnectionInfo info = new ConnectionInfo {
             Name = name, Connection = connection
         };
         _connectionInfoList.Add(info);
         if (PlayerJoined != null)
         {
             PlayerJoined.Invoke(info, null);
         }
     }
     else if (status == NetConnectionStatus.Disconnected)
     {
         ConnectionInfo info = _connectionInfoList.Find((x) => { return(x.Connection == connection); });
         Output(info.Name + " @" + connection.RemoteEndPoint + " has disconnected");
         _connectionInfoList.Remove(info);
         if (PlayerLeft != null)
         {
             PlayerLeft.Invoke(info, null);
         }
         // _connectionInfoList.RemoveAll((x)=> { return x.Connection == connection;});
     }
 }
Ejemplo n.º 2
0
 internal async Task PlayerLeftNotification(PlayerLeftNotification notification)
 {
     if (PlayerLeft != null)
     {
         await PlayerLeft?.Invoke(notification);
     }
 }
Ejemplo n.º 3
0
 public void Delete(int playerID)
 {
     //Destroy(characters[playerID].playerController.transform.gameObject); EDIT
     //characters.RemoveAt(playerID);
     Debug.Log("FINISH HIM");
     PlayerLeft?.Invoke(playerID);
 }
Ejemplo n.º 4
0
 private void OnTriggerExit(Collider other)
 {
     if (other.GetComponent <PlayerControl>() != null)
     {
         interactionAvailableHint.SetActive(false);
         PlayerLeft?.Invoke();
     }
 }
Ejemplo n.º 5
0
 protected virtual void OnPlayerLeft(RoomPlayerEventArgs e)
 {
     if (Disposed)
     {
         return;
     }
     PlayerLeft?.Invoke(this, e);
     RoomManager.Channel.BroadcastCencored(new RoomChangeRoomInfoAck2Message(GetRoomInfo()));
 }
Ejemplo n.º 6
0
 private void OnClientLeft(ulong steamId, MyChatMemberStateChangeEnum stateChange)
 {
     Players.TryGetValue(steamId, out PlayerViewModel vm);
     if (vm == null)
     {
         vm = new PlayerViewModel(steamId);
     }
     Log.Info($"{vm.Name} ({vm.SteamId}) {(ConnectionState)stateChange}.");
     PlayerLeft?.Invoke(vm);
     Players.Remove(steamId);
 }
Ejemplo n.º 7
0
 private void PlayerDisconnected(long playerId)
 {
     MyAPIGateway.Utilities.InvokeOnGameThread(() =>
     {
         PlayerAuxData aux;
         if (_playerById.TryGetValue(playerId, out aux) && aux.RealPlayer != null)
         {
             PlayerLeft?.Invoke(aux.RealPlayer);
         }
         Refresh();
     });
 }
Ejemplo n.º 8
0
        public void OnPlayerLeft(int peerId)
        {
            _accessesInUse.Remove(peerId);

            _players.TryGetValue(peerId, out var playerPeer);

            if (playerPeer == null)
            {
                return;
            }

            PlayerLeft?.Invoke(playerPeer);
        }
Ejemplo n.º 9
0
    protected virtual void OnPlayerLeft(UnetMsfPlayer player)
    {
        // Remove from lookups
        PlayersByPeerId.Remove(player.PeerId);
        PlayersByUsername.Remove(player.Username);
        PlayersByConnectionId.Remove(player.Connection.connectionId);

        if (PlayerLeft != null)
        {
            PlayerLeft.Invoke(player);
        }

        // Notify controller that the player has left
        Controller.PlayerLeft(player.PeerId);
    }
        private async Task ClientOnPlayerLeft(BigInteger roomId, Address player)
        {
            if (roomId != this.gameState.RoomId)
            {
                return;
            }

            Debug.Log("Player left " + player);
            PlayerLeft?.Invoke(player);
            if (this.client.Address == player)
            {
                return;
            }

            await UpdateGameState();
        }
Ejemplo n.º 11
0
 private void PlayerDisconnected(long playerId)
 {
     MyAPIGateway.Utilities.InvokeOnGameThread(() =>
     {
         PlayerAuxData aux;
         if (_playerById.TryGetValue(playerId, out aux) && aux.RealPlayer != null)
         {
             PlayerLeft?.Invoke(aux.RealPlayer);
         }
         else
         {
             ResearchCore.ResearchCore.LoggerStatic?.Warning(
                 $"Failed to find real player for disconnecting player {playerId}");
         }
         Refresh();
     });
 }
Ejemplo n.º 12
0
        public void OnPlayerLeft(int peerId)
        {
            _accessesInUse.Remove(peerId);

            IPeer playerPeer;

            _players.TryGetValue(peerId, out playerPeer);

            if (playerPeer == null)
            {
                return;
            }

            if (PlayerLeft != null)
            {
                PlayerLeft.Invoke(playerPeer);
            }
        }
Ejemplo n.º 13
0
    public void notify(GameObject from)
    {
        PlayerLeft?.Invoke(from);
        _prevLevelIndex = GetIndexFromPosition(from.transform.position);

        var positionIndex = GetIndexFromPosition(_properties.character.transform.position);

        if (_levels.ContainsKey(positionIndex))
        {
            var level = _levels[positionIndex];
            ActivateLevels(_prevLevelIndex, positionIndex);
            PlayerEntered?.Invoke(level);
        }
        else
        {
            _checkForCharacter = true;
        }
    }
Ejemplo n.º 14
0
        public override void OnPlayerLeftRoom(Player otherPlayer)
        {
            if (!PhotonNetwork.IsMasterClient)
            {
                return;
            }

            var i = 0;

            for (; i < PlayerNumbering.SortedPlayers.Length; i++)
            {
                if (otherPlayer.ActorNumber == PlayerNumbering.SortedPlayers[i].ActorNumber)
                {
                    break;
                }
            }

            PlayerLeft?.Invoke(i);
        }
Ejemplo n.º 15
0
        public void Update(float deltaTime)
        {
            var currentVehicle = Game.PlayerPed.CurrentVehicle;

            if (!_isInVehicle && !Game.Player.IsDead)
            {
                var vehicleTryingToEnter = Game.PlayerPed.VehicleTryingToEnter;
                if (vehicleTryingToEnter != null && !_isEnteringVehicle)
                {
                    _prevVehicle       = vehicleTryingToEnter;
                    _isEnteringVehicle = true;
                    PlayerEntering?.Invoke(this, vehicleTryingToEnter);
                }
                else if (vehicleTryingToEnter == null && currentVehicle == null && _isEnteringVehicle)
                {
                    _isEnteringVehicle = false;
                    PlayerAbortedEntering?.Invoke(this, _prevVehicle);
                }
                else if (currentVehicle != null)
                {
                    _prevVehicle       = currentVehicle;
                    _isEnteringVehicle = false;
                    _isInVehicle       = true;
                    PlayerEntered?.Invoke(this, currentVehicle);
                }
            }
            else if (_isInVehicle)
            {
                if (currentVehicle == null || Game.Player.IsDead)
                {
                    _isInVehicle = false;
                    PlayerLeft?.Invoke(this, _prevVehicle);
                }
                else if (_prevVehicle != currentVehicle)
                {
                    PlayerLeft?.Invoke(this, _prevVehicle);
                    PlayerEntered?.Invoke(this, currentVehicle);
                    _prevVehicle = currentVehicle;
                }
            }
        }
Ejemplo n.º 16
0
        private void OnDataReceived(object sender, string json)
        {
            Parameter parameter = JsonConvert.DeserializeObject <Parameter>(json);

            if (parameter.ActionType == ActionType.UpdateGameboard && UpdateGameboard != null)
            {
                UpdateGameboard.Invoke(this, JsonConvert.DeserializeObject <UpdateGameboardParameter>(json));
            }
            else if (parameter.ActionType == ActionType.JoinRoom && PlayerJoined != null)
            {
                PlayerJoined.Invoke(this, EventArgs.Empty);
            }
            else if (parameter.ActionType == ActionType.LeaveRoom && PlayerLeft != null)
            {
                PlayerLeft.Invoke(this, EventArgs.Empty);
            }
            else if (parameter.ActionType == ActionType.StartGame && GameStarted != null)
            {
                GameStarted.Invoke(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 17
0
        protected virtual void OnPlayerLeft(RoomPlayerEventArgs e)
        {
            PlayerLeft?.Invoke(this, e);

            RoomDto roomDto = new RoomDto();

            roomDto.RoomId      = (byte)this.Id;
            roomDto.PlayerCount = (byte)this.Players.Count;
            roomDto.PlayerLimit = this.Options.PlayerLimit;
            roomDto.State       = (byte)this.GameRuleManager.GameRule.StateMachine.State;
            roomDto.State2      = (byte)this.GameRuleManager.GameRule.StateMachine.State;
            roomDto.GameRule    = (int)this.Options.GameRule;
            roomDto.Map         = (byte)this.Options.MapID;
            roomDto.WeaponLimit = this.Options.ItemLimit;
            roomDto.Name        = this.Options.Name;
            roomDto.Password    = this.Options.Password;
            roomDto.FMBURNMode  = GetFMBurnModeInfo();
            RoomManager.Channel.Broadcast(new RoomChangeRoomInfoAck2Message(roomDto));
            //RoomManager.Channel.Broadcast(new RoomChangeRoomInfoAckMessage(this.Map<Room, RoomDto>()));
            //RoomManager.Channel.Broadcast(new SUserDataAckMessage(e.Player.Map<Player, UserDataDto>()));
        }
Ejemplo n.º 18
0
        static Server()
        {
            Events.GameLobby.Initialized.Subscribe(data =>
            {
                LobbyInitialized?.Invoke(null, System.EventArgs.Empty);
            });

            Events.ServerToClient.AddClient.Subscribe(data =>
            {
                if (G.Sys.NetworkingManager_.IsOnline_)
                {
                    var eventArgs = new PlayerEventArgs(data.clientName_, data.ready_, (LevelCompatibility)data.status_);
                    PlayerJoined?.Invoke(null, eventArgs);
                }
            });

            Events.ServerToClient.RemovePlayerFromClientList.Subscribe(data =>
            {
                var serverLogicObject = GameObject.Find("GameManager")?.GetComponent <ServerLogic>();
                var clientLogic       = serverLogicObject?.GetType().GetField("clientLogic_", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(serverLogicObject) as ClientLogic;
                var clientInfo        = clientLogic?.GetPlayerInfo(data.playerIndex_);

                if (clientInfo != null)
                {
                    var eventArgs = new PlayerEventArgs(clientInfo.Username_, clientInfo.Ready_, (LevelCompatibility)clientInfo.LevelCompatabilityStatus_);
                    PlayerLeft?.Invoke(null, eventArgs);
                }
            });

            Events.ServerToClient.SetGameMode.Subscribe(data =>
            {
                if (G.Sys.NetworkingManager_.IsOnline_)
                {
                    var eventArgs = new GameModeChangedEventArgs(data.mode_);
                    GameModeChanged?.Invoke(null, eventArgs);
                }
            });
        }
Ejemplo n.º 19
0
        public void Update(float deltaTime)
        {
            if (IsPlayerInside())
            {
                if (_playerWasInside)
                {
                    return;
                }

                _playerWasInside = true;
                PlayerEntered?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                if (!_playerWasInside)
                {
                    return;
                }

                _playerWasInside = false;
                PlayerLeft?.Invoke(this, EventArgs.Empty);
            }
        }
Ejemplo n.º 20
0
 protected virtual void OnPlayerLeft(ChannelPlayerLeftEventArgs e)
 {
     PlayerLeft?.Invoke(this, e);
 }
Ejemplo n.º 21
0
 private void OnClientLeft(ulong steamId, ChatMemberStateChangeEnum stateChange)
 {
     _log.Info($"{GetSteamUsername(steamId)} disconnected ({(ConnectionState)stateChange}).");
     PlayerLeft?.Invoke(steamId, (ConnectionState)stateChange);
 }
Ejemplo n.º 22
0
    private void Start()
    {
        StartCoroutine(Upload("socket.io/?EIO=3&transport=polling", async(response, error) =>
        {
            if (error != null)
            {
                return;
            }

            string sid = (string)response["sid"];

            _websocket = new WebSocket(APIWrapper.WS_PROTOCOL + APIWrapper.URL + "socket.io/?EIO=3&transport=websocket&sid=" + sid);

            _websocket.OnOpen += () =>
            {
                _closed = false;
                Debug.Log("Connection open!");
                _websocket.SendText("2probe");
            };

            _websocket.OnError += (e) =>
            {
                Debug.Log("Error! " + e);
            };

            _websocket.OnClose += (e) =>
            {
                Debug.Log("Connection closed!");
                if (!_closed)
                {
                    Start();
                }
            };

            _websocket.OnMessage += (bytes) =>
            {
                if (_closed)
                {
                    return;
                }

                try
                {
                    var message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);

                    if (message == "3probe")
                    {
                        _websocket.SendText("5");
                        return;
                    }

                    if (message.Length <= 3 || message.Substring(0, 2) != "42")
                    {
                        return;
                    }

                    message   = message.Substring(2);
                    var array = JArray.Parse(message);

                    Debug.Log(array[0]);

                    switch ((string)array[0])
                    {
                    case "playerJoined":
                        {
                            var player = Player.GetPlayer(array[1]["player"]);
                            GetCurrentGame().Players.Add(player);
                            PlayerJoined?.Invoke(player);
                            break;
                        }

                    case "playerLeft":
                        {
                            foreach (var player in GetCurrentGame().Players.ToArray())
                            {
                                if (player.UserId != (string)array[1]["user"])
                                {
                                    continue;
                                }

                                GetCurrentGame().Players.Remove(player);
                                PlayerLeft?.Invoke(player);
                            }
                            break;
                        }

                    case "gameStarted":
                        {
                            var firstPlayer = Player.GetPlayerById(array[1]["firstPlayer"].ToString());
                            GameManager.Instance.Game.UpdateCurrentPlayer(firstPlayer);
                            GameManager.Instance.Game.SetRunning();
                            GameStarted?.Invoke();
                            break;
                        }

                    case "playerRolledDice":
                        {
                            var player = Player.GetPlayerById(array[1]["user"].ToString());
                            var dice   = ((JArray)array[1]["dice"]).Select(d => (int)d).ToArray();

                            PlayerRolledDice?.Invoke(player, dice);
                            break;
                        }

                    case "playerTurnChanged":
                        {
                            var player = Player.GetPlayerById(array[1]["user"].ToString());
                            GameManager.Instance.Game.UpdateCurrentPlayer(player);

                            Debug.Log(player.UserId);

                            PlayerTurnChanged?.Invoke(player);
                            break;
                        }

                    case "playerPlaysAgain":
                        {
                            var player = Player.GetPlayerById(array[1]["user"].ToString());

                            PlayerPlaysAgain?.Invoke(player);
                            break;
                        }

                    case "playerMoved":
                        {
                            var player   = Player.GetPlayerById(array[1]["user"].ToString());
                            var location = (int)array[1]["location"];

                            PlayerMoved?.Invoke(player, location);
                            break;
                        }

                    case "playerBalanceChanged":
                        {
                            var player  = Player.GetPlayerById(array[1]["user"].ToString());
                            var balance = (int)array[1]["balance"];

                            player.Balance = balance;

                            PlayerBalanceChanged?.Invoke(player, balance);
                            break;
                        }

                    case "playerSteppedOnChance":
                        {
                            var player = Player.GetPlayerById(array[1]["user"].ToString());
                            var text   = array[1]["card"].ToString();

                            PlayerSteppedOnChance?.Invoke(player, text);
                            break;
                        }

                    case "playerSteppedOnCommunityChest":
                        {
                            var player = Player.GetPlayerById(array[1]["user"].ToString());
                            var text   = array[1]["card"].ToString();

                            PlayerSteppedOnCommunityChest?.Invoke(player, text);
                            break;
                        }

                    case "propertyOwnerChanged":
                        {
                            var propertyIndex = (int)array[1]["propertyIndex"];
                            var ownerId       = array[1]["ownerId"].ToString();

                            var property     = GameManager.Instance.Game.GetPropertyByIndex(propertyIndex);
                            property.OwnerId = ownerId;

                            PropertyOwnerChanged?.Invoke(propertyIndex, ownerId);
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.Log(e.Message);
                }
            };

            // Keep sending messages every 15s
            InvokeRepeating(nameof(SendWebSocketMessage), 0.0f, 5.0f);

            // Waiting for messages
            await _websocket.Connect();
        }));
    }
Ejemplo n.º 23
0
 protected virtual void OnPlayerLeft(RoomPlayerEventArgs e)
 {
     PlayerLeft?.Invoke(this, e);
     RoomManager.Channel.Broadcast(new SChangeGameRoomAckMessage(this.Map <Room, RoomDto>()));
     RoomManager.Channel.Broadcast(new SUserDataAckMessage(e.Player.Map <Player, UserDataDto>()));
 }
 private void EventReceivedHandler(object sender, EvmChainEventArgs e)
 {
     lock (this.roomIdToRoomEventActionsMap)
     {
         switch (e.EventName)
         {
             case "RoomCreated":
             {
                 RoomCreatedEventData eventDto = e.DecodeEventDto<RoomCreatedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     -1,
                     () => RoomCreated?.Invoke((Address) eventDto.Creator, eventDto.RoomId)
                     );
                 break;
             }
             case "PlayerJoined":
             {
                 PlayerRelatedEventData eventDto = e.DecodeEventDto<PlayerRelatedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => PlayerJoined?.Invoke(eventDto.RoomId, (Address) eventDto.Player)
                 );
                 break;
             }
             case "PlayerLeft":
             {
                 PlayerRelatedEventData eventDto = e.DecodeEventDto<PlayerRelatedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => PlayerLeft?.Invoke(eventDto.RoomId, (Address) eventDto.Player)
                 );
                 break;
             }
             case "PlayerBetted":
             {
                 PlayerBettedEventData eventDto = e.DecodeEventDto<PlayerBettedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => PlayerBetted?.Invoke(eventDto.RoomId, (Address) eventDto.Player, eventDto.Bet)
                 );
                 break;
             }
             case "PlayerReadyForNextRoundChanged":
             {
                 PlayerReadyForNextRoundChangedEventData eventDto = e.DecodeEventDto<PlayerReadyForNextRoundChangedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => PlayerReadyForNextRoundChanged?.Invoke(eventDto.RoomId, (Address) eventDto.Player, eventDto.Ready)
                 );
                 break;
             }
             case "GameStageChanged":
             {
                 GameStageChangedEventData eventDto = e.DecodeEventDto<GameStageChangedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => GameStageChanged?.Invoke(eventDto.RoomId, eventDto.Stage)
                 );
                 break;
             }
             case "CurrentPlayerIndexChanged":
             {
                 CurrentPlayerIndexChangedEventData eventDto = e.DecodeEventDto<CurrentPlayerIndexChangedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => CurrentPlayerIndexChanged?.Invoke(eventDto.RoomId, eventDto.PlayerIndex, (Address) eventDto.PlayerAddress)
                 );
                 break;
             }
             case "PlayerDecisionReceived":
             {
                 PlayerDecisionReceivedEventData eventDto = e.DecodeEventDto<PlayerDecisionReceivedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => PlayerDecisionReceived?.Invoke(eventDto.RoomId, (Address) eventDto.Player, eventDto.PlayerDecision)
                 );
                 break;
             }
             case "GameRoundResultsAnnounced":
             {
                 GameRoundResultsAnnouncedEventData eventDto = e.DecodeEventDto<GameRoundResultsAnnouncedEventData>();
                 EnqueueRoomEventAction(
                     eventDto.RoomId,
                     eventDto.Nonce,
                     () => GameRoundResultsAnnounced?.Invoke(
                         eventDto.RoomId,
                         eventDto.DealerOutcome,
                         eventDto.Players.Select(p => (Address) p).ToArray(),
                         eventDto.PlayerOutcome.ToArray())
                 );
                 break;
             }
             case "Log":
             {
                 break;
             }
             default:
                 throw new ArgumentOutOfRangeException($"Unknown event {e.EventName}");
         }
     }
 }
Ejemplo n.º 25
0
        private async Task ReadLoop()
        {
            if (!this.IsAttached)
            {
                return;
            }

            if (!isReading)
            {
                isReading = true;
            }


            try
            {
                PreviousState = new AmongUsState(this);

                Logger.Write("Starting read..\n" +
                             "Game State:\n" +
                             $"  Game state: <Green>{PreviousState.State}</Green>\n" +
                             $"  Code: <Green>{PreviousState.GameCode}</Green>\n" +
                             $"  Players: <Green>{PreviousState.PlayerCount}</Green>:\n" +
                             $"   - " + string.Join("\n   - ", PreviousState.Players), Logger.Severity.Game

                             );

                while (this.IsAttached)
                {
                    try
                    {
                        var currentState = new AmongUsState(this);
                        currentState.Update(PreviousState, this);

                        if (currentState.State != PreviousState.State)
                        {
                            Logger.Write($"Gamestate updated from <Gray>{PreviousState.State}</Gray> to <Green>{currentState.State}</Green>", Logger.Severity.Game);
                        }

                        if (currentState.ConnectedToServer != PreviousState.ConnectedToServer)
                        {
                            if (currentState.ConnectedToServer)
                            {
                                Logger.Write($"Connected to the game <Cyan>{currentState.GameCode}</Cyan> with <Cyan>{currentState.PlayerCount}</Cyan> players", Logger.Severity.Game);
                            }
                            else
                            {
                                Logger.Write($"Disconnected from the game with <Cyan>{PreviousState.Players.Count(x => !x.IsDead)}</Cyan> players", Logger.Severity.Game);
                            }
                        }

                        if (currentState.InGame != PreviousState.InGame)
                        {
                            if (currentState.InGame)
                            {
                                GameStarted?.Invoke(null, currentState);
                                Logger.Write($"Game <Cyan>{currentState.GameCode}</Cyan> <Green>Started</Green> with <Green>{currentState.PlayerCount}</Green> players.", Logger.Severity.Game);
                            }
                            else
                            {
                                if (currentState.ConnectedToServer)
                                {
                                    GameEnded?.Invoke(null, currentState);
                                    var isCrewmateWin = this.IsCrewMateWin(currentState);
                                    Logger.Write($"Game <Cyan>{currentState.GameCode}</Cyan> <Red>Ended</Red> with {(isCrewmateWin ? $"<Green>Crewmate Victory</Green>" : "<Red>Imposter Win</Red>")}", Logger.Severity.Game);
                                }
                            }
                        }

                        if (currentState.ConnectedToServer)
                        {
                            var Joined = currentState.Players.Select(x => (x.Name, x.Id)).Except(PreviousState.Players.Select(x => (x.Name, x.Id))).ToList();

                            if (Joined.Count > 0)
                            {
                                foreach (var item in Joined.Where(x => x.Name != ""))
                                {
                                    var newPlayer = currentState.Players.FirstOrDefault(x => x.Id == item.Id);
                                    PlayerJoined?.Invoke(null, new PlayerJoinedEventArgs()
                                    {
                                        GameState = currentState,
                                        Player    = newPlayer
                                    });

                                    Logger.Write($"Player <Gray>{newPlayer.Id}: \'{newPlayer.Name}\'</Gray> joined <Cyan>{currentState.GameCode}</Cyan>", Logger.Severity.Game);
                                }
                            }


                            var LeftIngame = currentState.Players.Where(x =>
                            {
                                var plr = PreviousState.Players.FirstOrDefault(y => y.Id == x.Id);

                                if (plr == null)
                                {
                                    return(false);
                                }

                                if (x.Disconnected && !plr.Disconnected)
                                {
                                    return(true);
                                }
                                return(false);
                            }).Select(x => x.Id);

                            var Left = PreviousState.Players.Select(x => x.Id).Except(currentState.Players.Select(x => x.Id)).Concat(LeftIngame).ToList();

                            if (Left.Count > 0)
                            {
                                foreach (var item in Left)
                                {
                                    var oldPlayer = PreviousState.Players.FirstOrDefault(x => x.Id == item);
                                    PlayerLeft?.Invoke(null, new PlayerLeftEventArgs()
                                    {
                                        GameState = currentState,
                                        Player    = oldPlayer
                                    });

                                    Logger.Write($"Player <Gray>{oldPlayer.Id}: \'{oldPlayer.Name}\'</Gray> Left <Cyan>{currentState.GameCode}</Cyan>", Logger.Severity.Game);
                                }
                            }

                            if (PreviousState.CanTalk != currentState.CanTalk)
                            {
                                VoipSettingUpdate?.Invoke(null, currentState.CanTalk);
                                Logger.Write($"Voice state changed from {(PreviousState.CanTalk ? "<Green>Can talk</Green>" : "<Red>Cannot Talk</Red>")} to {(currentState.CanTalk ? "<Green>Can talk</Green>" : "<Red>Cannot Talk</Red>")}", Logger.Severity.Game);
                            }

                            if (currentState.State == AmongUsReader.GameState.Discussion && currentState.State != PreviousState.State)
                            {
                                MeetingCalled?.Invoke(null, currentState);
                                Logger.Write("Meeting called, Entered discussion", Logger.Severity.Game);
                            }
                        }

                        PreviousState = currentState;
                    }
                    catch (Exception x)
                    {
                        Logger.Write($"Error on read loop: {x}");
                    }
                    finally
                    {
                        await Task.Delay(50);
                    }
                }
            }
            catch (Exception x)
            {
                Logger.Write($"Fatal before read loop: {x}", Logger.Severity.Critical);
            }
            finally
            {
                isReading = false;
            }
        }
Ejemplo n.º 26
0
 public void RemovePlayer(Player player)
 {
     _players.Remove(player);
     PlayerLeft?.Invoke(player);
 }
Ejemplo n.º 27
0
 protected virtual void OnPlayerLeft(PlayerLeftArgs e)
 {
     PlayerLeft?.Invoke(this, e);
 }
Ejemplo n.º 28
0
 protected virtual void OnPlayerLeft(Channel channel, Player plr)
 {
     PlayerLeft?.Invoke(this, new ChannelEventArgs(channel, plr));
 }
Ejemplo n.º 29
0
        private void talker_SpringEvent(object sender, Talker.SpringEventArgs e)
        {
            try
            {
                switch (e.EventType)
                {
                case Talker.SpringEventType.PLAYER_JOINED:
                    var entry = Context?.GetOrAddPlayer(e.PlayerName);
                    if (entry != null)
                    {
                        entry.IsIngame = true;
                    }
                    PlayerJoined?.Invoke(this, new SpringLogEventArgs(e.PlayerName));
                    break;

                case Talker.SpringEventType.PLAYER_LEFT:
                    entry = Context?.GetOrAddPlayer(e.PlayerName);
                    if (entry != null)
                    {
                        entry.IsIngame = false;
                        entry.QuitTime = (int)DateTime.UtcNow.Subtract(Context.IngameStartTime ?? Context.StartTime).TotalSeconds;
                    }
                    if (e.Param == 0)
                    {
                        PlayerDisconnected?.Invoke(this, new SpringLogEventArgs(e.PlayerName));
                    }
                    PlayerLeft?.Invoke(this, new SpringLogEventArgs(e.PlayerName));
                    break;

                case Talker.SpringEventType.GAME_LUAMSG:
                    HandleSpecialMessages(e);
                    break;

                case Talker.SpringEventType.PLAYER_CHAT:
                    if (e.Param == 255)
                    {
                        HandleSpecialMessages(e);
                    }
                    else
                    {
                        AddToLogs(e);
                    }

                    if ((PlayerSaid != null) && !string.IsNullOrEmpty(e.PlayerName))
                    {
                        SpringChatLocation location = SpringChatLocation.Private;
                        if (((e.Param == Talker.TO_EVERYONE) || (e.Param == Talker.TO_EVERYONE_LEGACY)))
                        {
                            location = SpringChatLocation.Public;
                        }
                        if (e.Param == Talker.TO_ALLIES)
                        {
                            location = SpringChatLocation.Allies;
                        }
                        if (e.Param == Talker.TO_SPECTATORS)
                        {
                            location = SpringChatLocation.Spectators;
                        }
                        PlayerSaid(this, new SpringChatEventArgs(e.PlayerName, e.Text, location));
                    }
                    break;

                case Talker.SpringEventType.PLAYER_DEFEATED:
                    MarkPlayerDead(e.PlayerName, true);
                    if (PlayerLost != null)
                    {
                        PlayerLost(this, new SpringLogEventArgs(e.PlayerName));
                    }
                    break;

                case Talker.SpringEventType.SERVER_GAMEOVER:
                    if (!Context.GameEndedOk)     // server gameover runs multiple times
                    {
                        foreach (var p in Context.ActualPlayers)
                        {
                            if (!p.IsIngame && !p.IsSpectator)
                            {
                                MarkPlayerDead(p.Name, true);
                            }
                            p.IsIngame = false;
                        }

                        // set victory team for all allied with currently alive
                        if (e.winningAllyTeams.Length > 0)
                        {
                            foreach (var ally in e.winningAllyTeams)
                            {
                                foreach (var p in Context.ActualPlayers.Where(x => !x.IsSpectator && (x.AllyNumber == ally)))
                                {
                                    p.IsVictoryTeam = true;
                                }
                            }
                        }
                        else         // Fallback, shouldn't happen
                        {
                            foreach (var p in Context.ActualPlayers.Where(x => !x.IsSpectator && (x.LoseTime == null)))
                            {
                                foreach (var q in Context.ActualPlayers.Where(x => !x.IsSpectator && (x.AllyNumber == p.AllyNumber)))
                                {
                                    q.IsVictoryTeam = true;
                                }
                            }
                        }

                        if (Context.IngameStartTime != null)
                        {
                            Context.GameEndedOk = true;
                            Context.Duration    = (int)DateTime.UtcNow.Subtract(Context.IngameStartTime ?? Context.StartTime).TotalSeconds;

                            GameOver?.Invoke(this, new SpringLogEventArgs(e.PlayerName));
                        }
                        else
                        {
                            Trace.TraceWarning("recieved GAMEOVER before STARTPLAYING!");
                        }

                        Task.Delay(10000).ContinueWith(x => ExitGame());
                    }
                    break;

                case Talker.SpringEventType.PLAYER_READY:
                    if (e.Param == 1)
                    {
                        entry = Context.GetOrAddPlayer(e.PlayerName);
                        if (entry != null)
                        {
                            entry.IsIngameReady = true;
                        }
                    }
                    break;

                case Talker.SpringEventType.SERVER_STARTPLAYING:
                    Context.ReplayName            = e.ReplayFileName;
                    Context.EngineBattleID        = e.GameID;
                    Context.IngameStartTime       = DateTime.UtcNow;
                    Context.PlayersUnreadyOnStart = Context.ActualPlayers.Where(x => !x.IsSpectator && !(x.IsIngameReady && x.IsIngame)).Select(x => x.Name).ToList();
                    foreach (var p in Context.ActualPlayers.Where(x => !x.IsSpectator))
                    {
                        p.IsIngameReady = true;
                    }

                    process.PriorityClass = ProcessPriorityClass.High;

                    BattleStarted(this, Context);
                    break;

                case Talker.SpringEventType.SERVER_QUIT:
                    if (LobbyStartContext != null)
                    {
                        foreach (var p in Context.ActualPlayers)
                        {
                            p.IsIngame = false;
                        }
                    }
                    //if (GameOver != null) GameOver(this, new SpringLogEventArgs(e.PlayerName));
                    break;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error processing spring message:{0}", ex);
            }
        }
Ejemplo n.º 30
0
    private void HandleSocketIoMessage(JArray array)
    {
        switch ((string)array[0])
        {
        case "playerJoined":
        {
            var player = Player.GetPlayer(array[1]["player"]);
            PlayerJoined?.Invoke(player);
            break;
        }

        case "playerLeft":
        {
            var player = Player.GetPlayerById((string)array[1]["user"]);
            PlayerLeft?.Invoke(player);
            break;
        }

        case "gameIsStarting":
        {
            GameIsStarting?.Invoke();
            break;
        }

        case "gameLobbyTimer":
        {
            var remainingSeconds = (int)array[1]["remainingSeconds"];
            GameLobbyTimer?.Invoke(remainingSeconds);
            break;
        }

        case "gameStarted":
        {
            var firstPlayer = Player.GetPlayerById(array[1]["firstPlayer"].ToString());

            GameStarted?.Invoke(firstPlayer);
            break;
        }

        case "playerRolledDice":
        {
            var player = Player.GetPlayerById(array[1]["user"].ToString());
            var dice   = ((JArray)array[1]["dice"]).Select(d => (int)d).ToArray();
            PlayerRolledDice?.Invoke(player, dice);
            break;
        }

        case "playerTurnChanged":
        {
            var player = Player.GetPlayerById(array[1]["user"].ToString());
            PlayerTurnChanged?.Invoke(player);
            break;
        }

        case "playerPlaysAgain":
        {
            var player = Player.GetPlayerById(array[1]["user"].ToString());
            PlayerPlaysAgain?.Invoke(player);
            break;
        }

        case "playerMoved":
        {
            var player   = Player.GetPlayerById(array[1]["user"].ToString());
            var location = (int)array[1]["location"];
            PlayerMoved?.Invoke(player, location);
            break;
        }

        case "playerBalanceChanged":
        {
            var player  = Player.GetPlayerById(array[1]["user"].ToString());
            var balance = (int)array[1]["balance"];
            PlayerBalanceChanged?.Invoke(player, balance);
            break;
        }

        case "playerSteppedOnChance":
        {
            var player = Player.GetPlayerById(array[1]["user"].ToString());
            var text   = array[1]["card"].ToString();
            PlayerSteppedOnChance?.Invoke(player, text);
            break;
        }

        case "playerSteppedOnCommunityChest":
        {
            var player = Player.GetPlayerById(array[1]["user"].ToString());
            var text   = array[1]["card"].ToString();
            PlayerSteppedOnCommunityChest?.Invoke(player, text);
            break;
        }

        case "propertyOwnerChanged":
        {
            var propertyIndex = (int)array[1]["propertyIndex"];
            var ownerId       = array[1]["ownerId"].ToString();
            PropertyOwnerChanged?.Invoke(propertyIndex, ownerId);
            break;
        }
        }
    }