コード例 #1
0
ファイル: CodeController.cs プロジェクト: jorik041/AIGame
 public CodeController(IUserRepository repository,
                       GameServerContext context, SecurityHelper helper)
 {
     this.repository = repository;
     this.context    = context;
     this.helper     = helper;
 }
コード例 #2
0
        private void OnUpdateGameServerStats(GameServerContext gameServerContext, int peerCount, int gameCount)
        {
            GameServerApplicationState stats;

            if (this.gameServerStats.TryGetValue(gameServerContext, out stats) == false)
            {
                stats = new GameServerApplicationState();
                this.gameServerStats.Add(gameServerContext, stats);
            }

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Updating game server stats. new values peerCount={0}, gameCount={1}", peerCount, gameCount);
            }

            int playerDiff = peerCount - stats.PlayerCount;
            int gameDiff   = gameCount - stats.GameCount;

            this.PeerCountGameServer += playerDiff;
            this.GameCount           += gameDiff;
            stats.PlayerCount         = peerCount;
            stats.GameCount           = gameCount;

            if (playerDiff != 0 || gameDiff != 0)
            {
                this.OnStatsUpdated();
            }
        }
コード例 #3
0
        public override bool UpdateGameState(UpdateGameEvent updateOperation, GameServerContext incomingGameServerPeer, out GameState gameState)
        {
            //use the exisiting values for the protected game parameters
            if (useStoredProcedures)
            {
                if (log.IsDebugEnabled)
                {
                    log.DebugFormat("UpdateGameState {0}", updateOperation.GameId);
                }

                if (!this.gameDict.TryGetValue(updateOperation.GameId, out gameState))
                {
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Game not found");
                    }
                    return(false);
                }
                if (gameState.Properties != null)
                {
                    if (updateOperation.GameProperties == null)
                    {
                        updateOperation.GameProperties = new Hashtable();
                    }

                    foreach (var key in protectedGameProperties)
                    {
                        if (gameState.Properties.ContainsKey(key))
                        {
                            updateOperation.GameProperties[key] = gameState.Properties[key];
                            if (log.IsDebugEnabled)
                            {
                                log.DebugFormat("UpdateGameState, set key {0}/{1}", key, gameState.Properties[key]);
                            }
                        }
                        else
                        {
                            updateOperation.GameProperties.Remove(key);
                            if (log.IsDebugEnabled)
                            {
                                log.DebugFormat("UpdateGameState, removed key {0}", key);
                            }
                        }
                    }
                }
            }

            if (base.UpdateGameState(updateOperation, incomingGameServerPeer, out gameState))
            {
                if (gameState.IsJoinable)
                {
                    this.gameDatabase.Update(gameState.Id, gameState.Properties);
                }
                return(true);
            }
            return(false);
        }
コード例 #4
0
        public virtual void OnServerWentOffline(GameServerContext gameServerContext)
        {
            this.RemoveGameServerFromLobby(gameServerContext);

            if (AppStats != null)
            {
                AppStats.HandleGameServerRemoved(gameServerContext);
            }
        }
コード例 #5
0
        public static void RegisterTypes(IUnityContainer container)
        {
            GameServerContext gameServerContext = new GameServerContext();

            container.RegisterInstance(
                (IUserRepository) new MemoryUserRepository(gameServerContext));
            container.RegisterInstance(gameServerContext);
            container.RegisterType <SecurityHelper, SecurityHelper>();
        }
コード例 #6
0
 public void SetExpectReplicationFlag(bool flag, GameServerContext gameServerContext)
 {
     foreach (var gameState in this.gameDict.Values)
     {
         if (gameState.GameServer == gameServerContext)
         {
             gameState.ExpectsReplication = flag;
         }
     }
 }
コード例 #7
0
 private void HandleReplicationFinish(GameServerContext gameServerContext)
 {
     try
     {
         this.GameList.RemoveNotReplicatedGames(gameServerContext);
     }
     catch (Exception ex)
     {
         log.Error(string.Format("Exception in AppLobby:{0}, Exception Msg:{1}", this, ex.Message), ex);
     }
 }
コード例 #8
0
        public void RemoveGameServer(GameServerContext gameServer)
        {
            // find games belonging to the game server instance
            var instanceGames = this.gameDict.Where(gameState => gameState.GameServer == gameServer).ToList();

            // remove game server instance games
            foreach (var gameState in instanceGames)
            {
                this.RemoveGameStateByState(gameState);
            }
        }
コード例 #9
0
 private void HandleReplicationStop(GameServerContext gameServerContext)
 {
     try
     {
         this.GameList.SetExpectReplicationFlag(false, gameServerContext);
     }
     catch (Exception ex)
     {
         log.Error(string.Format("Exception in AppLobby:{0}, Exception Msg:{1}", this, ex.Message), ex);
     }
 }
コード例 #10
0
 private void HandleRemoveGameServer(GameServerContext gameServer)
 {
     try
     {
         this.GameList.RemoveGameServer(gameServer);
         this.SchedulePublishGameChanges();
     }
     catch (Exception ex)
     {
         log.Error(string.Format("Exception in AppLobby:{0}, Exception Msg:{1}", this, ex.Message), ex);
     }
 }
コード例 #11
0
        public void OnFinishReplication(GameServerContext gameServerContext)
        {
            this.defaultLobby.OnFinishReplication(gameServerContext);

            lock (this.lobbyDict)
            {
                foreach (var lobby in this.lobbyDict.Values)
                {
                    lobby.OnFinishReplication(gameServerContext);
                }
            }
        }
コード例 #12
0
        public void OnGameServerRemoved(GameServerContext gameServer)
        {
            this.defaultLobby.RemoveGameServer(gameServer);

            lock (this.lobbyDict)
            {
                foreach (var lobby in this.lobbyDict.Values)
                {
                    lobby.RemoveGameServer(gameServer);
                }
            }
        }
コード例 #13
0
        public void OnGameUpdateOnGameServer(UpdateGameEvent updateGameEvent, GameServerContext gameServer)
        {
            GameState gameState;

            lock (this.gameDict)
            {
                if (!this.gameDict.TryGetValue(updateGameEvent.GameId, out gameState))
                {
                    if (updateGameEvent.Reinitialize)
                    {
                        AppLobby lobby;
                        string   errorMsg;
                        if (!this.LobbyFactory.GetOrCreateAppLobby(updateGameEvent.LobbyId, (AppLobbyType)updateGameEvent.LobbyType, out lobby, out errorMsg))
                        {
                            // getting here should never happen
                            if (log.IsWarnEnabled)
                            {
                                log.WarnFormat("Could not get or create lobby: name={0}, type={1}, ErrorMsg:{2}", updateGameEvent.LobbyId,
                                               (AppLobbyType)updateGameEvent.LobbyType, errorMsg);
                            }
                            return;
                        }

                        ErrorCode errorCode;
                        var       maxPlayers = updateGameEvent.MaxPlayers.GetValueOrDefault(0);
                        this.GetOrCreateGame(updateGameEvent.GameId, lobby, maxPlayers, gameServer, out gameState, out errorCode, out errorMsg);
                        if (errorCode != ErrorCode.Ok)
                        {
                            log.WarnFormat("Error during game creation initiated by GS. GameId:'{0}', AppId:{2}. ErrorMsg:{1}",
                                           updateGameEvent.GameId, errorMsg, this.ApplicationId);
                        }
                    }
                }
            }

            if (gameState != null)
            {
                if (gameState.GameServer != gameServer)
                {
                    return;
                }

                gameState.CreateRequest = updateGameEvent;
                gameState.Lobby.UpdateGameState(updateGameEvent, gameServer);
                return;
            }

            if (log.IsDebugEnabled)
            {
                log.DebugFormat("Game to update not found: {0}", updateGameEvent.GameId);
            }
        }
コード例 #14
0
        public MemoryUserRepository(GameServerContext context)
        {
            /*DBUser u = new DBUser();
             * u.Username = "******";
             * u.ShipPresetId = 1;
             * u.Code = "";
             * u.CellTypes = new int[] { 0, 2, 1, 3, 1, 2 };
             * u.PasswordHash = "123";
             * context.Users.Add(u);
             * context.SaveChanges();*/

            UpdateFromDB(context);
        }
コード例 #15
0
        /// <summary>
        /// Loading all users from database to Users list
        /// </summary>
        /// <param name="context"></param>
        public void UpdateFromDB(GameServerContext context)
        {
            _users = new List <User>();
            foreach (DBUser dbUser in context.Users)
            {
                addUserFromDB(dbUser);
            }

            if (_users.Count >= 2)
            {
                _users[0].enemyShip = _users[1].ship;
                _users[1].enemyShip = _users[0].ship;
            }
        }
コード例 #16
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "GameState" /> class.
 /// </summary>
 /// <param name="lobby">
 /// The lobby to which the game belongs.
 /// </param>
 /// <param name = "id">
 ///   The game id.
 /// </param>
 /// <param name = "maxPlayer">
 ///   The maximum number of player who can join the game.
 /// </param>
 /// <param name = "gsContext">
 ///   The game server peer.
 /// </param>
 public GameState(AppLobby lobby, string id, byte maxPlayer, GameServerContext gsContext)
 {
     this.Lobby     = lobby;
     this.Id        = id;
     this.MaxPlayer = maxPlayer;
     this.IsOpen    = true;
     this.IsVisible = true;
     this.HasBeenCreatedOnGameServer = false;
     this.GameServerPlayerCount      = 0;
     this.gameServerContext          = gsContext;
     this.IsJoinable         = this.CheckIsGameJoinable();
     this.activeUserIdList   = new List <string>(maxPlayer > 0 ? maxPlayer : 5);
     this.inactiveUserIdList = new List <string>(maxPlayer > 0 ? maxPlayer : 5);
     this.expectedUsersList  = new List <string>(maxPlayer > 0 ? maxPlayer : 5);
     this.excludedActors     = new List <ExcludedActorInfo>();
 }
コード例 #17
0
        public void OnGameRemovedOnGameServer(GameServerContext context, string gameId, byte removeReason)
        {
            bool      found;
            GameState gameState;

            lock (this.gameDict)
            {
                found = this.gameDict.TryGetValue(gameId, out gameState);
            }

            if (found)
            {
                if (gameState.GameServer != context)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Game found, but not removed because it is created on another game server.gameId:{0}, gs:{1}, gs2:{2}",
                                        gameId, gameState.GameServer, context);
                    }
                    return;
                }
                if (!this.forceGameToRemove && removeReason == GameRemoveReason.GameRemoveClose && gameState.ShouldBePreservedInList)
                {
                    if (log.IsDebugEnabled)
                    {
                        log.DebugFormat("Game '{0}' will be preserved in game list for {1} minutes", gameState.Id,
                                        MasterServerSettings.Default.PersistentGameExpiryMinute);
                    }

                    gameState.Lobby.ResetGameServer(gameState);
                    this.AddGameToRedis(gameState);
                    this.AddGameToExpiryList(gameState);
                }
                else
                {
                    if (gameState.IsPersistent)
                    {
                        this.RemoveGameFromRedis(gameState);
                    }
                    gameState.Lobby.RemoveGame(gameId);
                }
            }
            else if (log.IsDebugEnabled)
            {
                log.DebugFormat("Game to remove not found: gameid={0}, appId={1}", gameId, this.ApplicationId);
            }
        }
コード例 #18
0
ファイル: GuildActionTest.cs プロジェクト: xtr3sor/OpenMU
        private IGameServerContext CreateGameServer()
        {
            var gameConfiguration = new GameConfiguration();

            gameConfiguration.Maps.Add(new GameMapDefinition());
            var gameServer = new GameServerContext(
                new GameServerDefinition {
                GameConfiguration = gameConfiguration
            },
                this.GuildServer,
                new Mock <ILoginServer>().Object,
                new Mock <IFriendServer>().Object,
                new InMemoryPersistenceContextProvider(),
                new MapInitializer(gameConfiguration));

            return(gameServer);
        }
コード例 #19
0
        public void RemoveNotReplicatedGames(GameServerContext gameServerContext)
        {
            var games4remove = new List <GameState>(100);

            foreach (var gameState in this.gameDict.Values)
            {
                if (gameState.GameServer == gameServerContext && gameState.ExpectsReplication)
                {
                    games4remove.Add(gameState);
                }
            }

            foreach (var game in games4remove)
            {
                this.RemoveGameStateByState(game);
            }
        }
コード例 #20
0
        private IGameServerContext CreateGameServer()
        {
            var gameConfiguration = new GameConfiguration();

            gameConfiguration.Maps.Add(new GameMapDefinition());
            var gameServer = new GameServerContext(
                new GameServerDefinition {
                GameConfiguration = gameConfiguration
            },
                this.GuildServer,
                new Mock <ILoginServer>().Object,
                new Mock <IFriendServer>().Object,
                new InMemoryPersistenceContextProvider(),
                new MapInitializer(gameConfiguration, new NullLogger <MapInitializer>()),
                new NullLoggerFactory(),
                new PlugInManager(new List <PlugIns.PlugInConfiguration>(), new NullLoggerFactory(), null));

            return(gameServer);
        }
コード例 #21
0
        private void HandleUpdateGameState(UpdateGameEvent operation, GameServerContext incomingGameServer)
        {
            try
            {
                GameState gameState;

                if (this.GameList.UpdateGameState(operation, incomingGameServer, out gameState) == false)
                {
                    return;
                }

                this.SchedulePublishGameChanges();

                this.OnGameStateChanged(gameState);
            }
            catch (Exception ex)
            {
                log.Error(string.Format("Exception in AppLobby:{0}, Exception Msg:{1}", this, ex.Message), ex);
            }
        }
コード例 #22
0
        public GameState(AppLobby lobby, Hashtable data)
        {
            this.Lobby     = lobby;
            this.Id        = (string)data[GameId];
            this.MaxPlayer = (byte)data[MaxPlayerId];
            this.IsOpen    = (bool)data[IsOpenId];
            this.IsVisible = (bool)data[IsVisibleId];

            this.InactivePlayerCount = (int)data[InactiveCountId];
            this.createDateUtc       = DateTime.FromBinary((long)data[CreateDateId]);
            this.activeUserIdList    = new List <string>((string[])data[UserListId]);
            this.inactiveUserIdList  = new List <string>((string[])data[InactiveUsersId]);
            this.expectedUsersList   = new List <string>((string[])data[ExpectedUsersId]);
            this.excludedActors      = new List <ExcludedActorInfo>((ExcludedActorInfo[])data[ExcludedUsersId]);
            this.properties          = (Dictionary <object, object>)data[PropertiesId];

            this.HasBeenCreatedOnGameServer = true;
            this.GameServerPlayerCount      = 0;
            this.gameServerContext          = null;
            this.IsJoinable = this.CheckIsGameJoinable();
        }
コード例 #23
0
        private void OnGameServerRemoved(GameServerContext gameServerContext)
        {
            GameServerApplicationState stats;

            if (this.gameServerStats.TryGetValue(gameServerContext, out stats) == false)
            {
                return;
            }

            this.gameServerStats.Remove(gameServerContext);
            this.PeerCountGameServer -= stats.PlayerCount;
            this.GameCount           += stats.GameCount;

            if (stats.PlayerCount != 0 || stats.GameCount != 0)
            {
                if (this.PeerCountGameServer < 0 || this.GameCount < 0)
                {
                    log.WarnFormat("Negative stats values PeerCountGameServer:{0}, GameCount:{1}", this.PeerCountGameServer, this.GameCount);
                    this.PeerCountGameServer = 0;
                    this.GameCount           = 0;
                }
                this.OnStatsUpdated();
            }
        }
コード例 #24
0
        public virtual bool UpdateGameState(UpdateGameEvent updateOperation, GameServerContext incomingGameServer, out GameState gameState)
        {
            if (!this.GetOrAddUpdatedGameState(updateOperation, out gameState))
            {
                return(false);
            }

            bool oldVisible = gameState.IsVisbleInLobby;
            bool changed    = gameState.Update(updateOperation);

            if (!changed)
            {
                return(false);
            }

            if (log.IsDebugEnabled)
            {
                LogGameState("UpdateGameState: ", gameState);
            }

            this.HandleVisibility(gameState, oldVisible);

            return(true);
        }
コード例 #25
0
 public void OnStopReplication(GameServerContext gameServerContext)
 {
     this.ExecutionFiber.Enqueue(() => this.HandleReplicationStop(gameServerContext));
 }
コード例 #26
0
 public void HandleGameServerRemoved(GameServerContext gameServerContext)
 {
     this.fiber.Enqueue(() => this.OnGameServerRemoved(gameServerContext));
 }
コード例 #27
0
 public void UpdateGameServerStats(GameServerContext gameServerContext, int peerCount, int gameCount)
 {
     this.fiber.Enqueue(() => this.OnUpdateGameServerStats(gameServerContext, peerCount, gameCount));
 }
コード例 #28
0
        public string GetServerAddress(ILobbyPeer peer)
        {
            string address;

            Func <GameServerContext, bool> filter = ctx =>
            {
                if (ctx.SupportedProtocols == null)
                {
                    return(true);
                }
                return(ctx.SupportedProtocols.Contains((byte)peer.NetworkProtocol));
            };


            // savedgames-poc:
            if (this.gameServerContext == null)
            {
                // try to get a game server instance from the load balancer

                GameServerContext newGameServerContext;
                if (!this.Lobby.Application.LoadBalancer.TryGetServer(out newGameServerContext, filter))
                {
                    throw new Exception("Failed to get server instance.");
                }
                this.gameServerContext = newGameServerContext;
                log.DebugFormat("GetServerAddress: game={0} got new host GS={1}", this.Id, this.gameServerContext.Key);
            }
            else
            {
                if (!filter(this.gameServerContext))
                {
                    log.WarnFormat("Client tries to join game with protocol {0}, but gs does not support it", peer.NetworkProtocol);
                    throw new NotSupportedException(
                              string.Format("Failed to get GS for game. It is on GS which does not support protcol {0} ",
                                            peer.NetworkProtocol));
                }
            }

            var useHostnames = peer.UseHostnames; // || config settimg ForceHostnames

            var useIPv4  = peer.LocalIPAddress.AddressFamily == AddressFamily.InterNetwork;
            var addrInfo = this.gameServerContext.AddressInfo;

            switch (peer.NetworkProtocol)
            {
            case NetworkProtocolType.Udp:
                address = useHostnames ? addrInfo.UdpHostname : (useIPv4 ? addrInfo.UdpAddress : addrInfo.UdpAddressIPv6);
                break;

            case NetworkProtocolType.Tcp:
                address = useHostnames ? addrInfo.TcpHostname : (useIPv4 ? addrInfo.TcpAddress : addrInfo.TcpAddressIPv6);
                break;

            case NetworkProtocolType.WebSocket:
                address = useHostnames ? addrInfo.WebSocketHostname : (useIPv4 ? addrInfo.WebSocketAddress : addrInfo.WebSocketAddressIPv6);
                break;

            case NetworkProtocolType.SecureWebSocket:
                address = addrInfo.SecureWebSocketHostname;
                break;

            case NetworkProtocolType.Http:
                if (peer.LocalPort == 443)     // https:
                {
                    address = addrInfo.SecureHttpHostname;
                }
                else     // http:
                {
                    address = useIPv4 ? addrInfo.HttpAddress : addrInfo.HttpAddressIPv6;
                }
                break;

            case NetworkProtocolType.WebRTC:
                address = addrInfo.WebRTCAddress;
                break;

            default:
                throw new NotSupportedException(string.Format("No GS address configured for Protocol {0} (Peer Type: {1})", peer.NetworkProtocol, ((PeerBase)peer).NetworkProtocol));
            }
            if (string.IsNullOrEmpty(address))
            {
                throw new NotSupportedException(
                          string.Format("No GS address configured for Protocol {0} (Peer Type: {1}, AddressFamily: {2})", peer.NetworkProtocol, peer.NetworkProtocol, peer.LocalIPAddress.AddressFamily));
            }
            return(address);
        }
コード例 #29
0
 // savedgames-poc:
 public void ResetGameServer()
 {
     this.gameServerContext = null;
 }
コード例 #30
0
 public override void OnStopReplication(GameServerContext gameServerContext)
 {
     ++this.OnStopReplicationCount;
     base.OnStopReplication(gameServerContext);
 }