Пример #1
0
        //For commands to check if positions have been set
        public static bool checkStoredPositions(IActor actor, out Point3D pos1, out Point3D pos2)
        {
            //Get the server
            IGameServer Server = actor.State as IGameServer;

            pos1 = new Point3D();
            pos2 = new Point3D();

            if (actor.SessionVariables.ContainsKey("SNEditPos1"))
            {
                pos1 = (Point3D)actor.SessionVariables["SNEditPos1"];
            }
            else
            {
                Server.ChatManager.SendActorMessage("Position 1 is not set.", actor);
                return(false);
            }

            if (actor.SessionVariables.ContainsKey("SNEditPos2"))
            {
                pos2 = (Point3D)actor.SessionVariables["SNEditPos2"];
            }
            else
            {
                Server.ChatManager.SendActorMessage("Position 2 is not set.", actor);
                return(false);
            }

            return(true);
        }
Пример #2
0
        //For commands to check if positions have been set
        public static bool checkStoredPositions(IActor actor, out Point3D pos1, out Point3D pos2)
        {
            //Get the server
            IGameServer Server = actor.State as IGameServer;

            pos1 = (Point3D)actor.SessionVariables["SNEditPos1"];
            pos2 = (Point3D)actor.SessionVariables["SNEditPos2"];

            if (pos1 == null)
            {
                Server.ChatManager.SendActorMessage("Position 1 is not set.", actor);
                return(false);
            }
            else if (pos2 == null)
            {
                Server.ChatManager.SendActorMessage("Position 2 is not set.", actor);
                return(false);
            }
            else if (pos2 != null && pos1 != null)
            {
                return(true);
            }
            else
            {
                Server.ChatManager.SendActorMessage("Position 1 and Position 2 are not set.", actor);
                return(false);
            }
        }
Пример #3
0
        public ReconnectDialogViewModel()
        {
            ReconnectCommand = new CommandHandler(Reconnect);
            CancelCommand    = new CommandHandler(Cancel);

            gameServer = ClientProxyManager.Instance;
        }
Пример #4
0
 public static IEntityHandle Player(string name, IGameServer server, IPosition pos)
 {
     var players = server.Services.ThrowOrGet<PlayerCatalogue>();
     var p = players.Create(SerializablePlayerModel.Default(name, server.Services.ThrowOrGet<SkillDb>()), MockSocketContext.Instance, MockPacketParser.Instance, new PacketHandlerCatalogue(server.Services));
     p.Get().GetTransform().Teleport(pos);
     return p;
 }
Пример #5
0
    void Awake()
    {
        _instance = this;

        server = new DemoTcpClient();
        MyId  += Random.Range(1, 20000).ToString();
    }
Пример #6
0
 private void Awake()
 {
     m_gSettings    = Dependencies.Settings;
     m_gameServer   = Dependencies.GameServer;
     m_notification = Dependencies.Notification;
     m_gameState    = Dependencies.GameState;
 }
Пример #7
0
 private async void connectButton_Click(object sender, EventArgs e)
 {
     _gameData.PlayerName = nameTextBox.Text;
     try
     {
         connectButton.Enabled = !connectButton.Enabled;
         if (connectButton.Text == "Connect")
         {
             await Task.Factory.StartNew(() =>
             {
                 _server = _channelFactory.CreateChannel();
                 _server.ConnectToServer(_gameData.PlayerName);
                 //this.Text = $"Tic Tac Toe, [{nameTextBox.Text}]";
                 this.Text = string.Format("Tic Tac Toe, [{0}]", nameTextBox.Text);
                 isConnected = true;
             });
         }
         else
             _server.StopGame();
         nameTextBox.Visible = false;
         connectButton.Text = connectButton.Text == "Connect" ? "Disconnect" : "Connect";
         connectButton.Enabled = !connectButton.Enabled;
     }
     catch (Exception)
     {
         infoLabel.Text = (_message_UnableToConnect);
         connectButton.Enabled = !connectButton.Enabled;
         isConnected = false;
         connectButton.Text = "Connect";
     }
 }
        private void OnDeviceDisabled(int index)
        {
            m_connectButton.gameObject.SetActive(m_inputManager.DeviceCount > 0);

            Player player = m_playerMenu[index].Player;

            m_playerMenu[index].gameObject.SetActive(false);

            if (player != null)
            {
                IProgressIndicator progress = m_progress.GetChild(index);
                progress.IsVisible = true;

                IGameServer gameServer = Dependencies.GameServer;
                gameServer.Logoff(m_gSettings.ClientId, player.Id, (error, playerId) =>
                {
                    progress.IsVisible = false;
                    if (gameServer.HasError(error))
                    {
                        m_notification.ShowError(error);
                        return;
                    }

                    SetDisabledAsLast(index);
                    TryNavigateToMainMenu();
                });
            }
            else
            {
                SetDisabledAsLast(index);
                TryNavigateToMainMenu();
            }
        }
Пример #9
0
        private void LoadGameServer(IBridge gameBridge)
        {
            _game = new GameServer();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(_logger);
            serviceCollection.AddSingleton <IServerEngine>(this);

            if (gameBridge != null)
            {
                serviceCollection.AddSingleton(gameBridge);
            }

            serviceCollection.AddSingleton(_engine.EngineTime);
            serviceCollection.AddSingleton <IEngineModels>(_serverModels);
            serviceCollection.AddSingleton <IServerModels>(_serverModels);

            _game.Initialize(serviceCollection);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            _serverNetworking = serviceProvider.GetRequiredService <IServerNetworking>();

            _game.Startup(serviceProvider);

            //Listen servers have the client do this
            if (_engine.IsDedicatedServer)
            {
                _engine.ModelManager.SetLoaders(_game.GetModelLoaders());
            }
        }
Пример #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OnlineFriend" /> class.
 /// </summary>
 /// <param name="gameServer">The game server.</param>
 /// <param name="playerName">Name of the player.</param>
 public OnlineFriend(IGameServer gameServer, string playerName)
 {
     this.gameServer    = gameServer;
     this.PlayerName    = playerName;
     this.subscribers   = new HashSet <IObserver <OnlineFriend> >();
     this.subscriptions = new List <Unsubscriber>();
 }
Пример #11
0
        public Map(IGameServer server, int id)
        {
            Server  = server;
            MapleId = id;

            Characters  = new MapCharacters(this);
            Drops       = new MapDrops(this);
            Mobs        = new MapMobs(this);
            Npcs        = new MapNpcs(this);
            Footholds   = new MapFootholds();
            Seats       = new MapSeats(this);
            Portals     = new MapPortals(this);
            SpawnPoints = new MapSpawnPoints(this);
            PlayerShops = new MapPlayerShops(this);
            Summons     = new MapSummons(this);
            Mists       = new MapMists(this);

            var reference = CachedReference;

            reference.Footholds.ForEach(x => Footholds.Footholds.Add(new Foothold(x)));
            reference.Npcs.ForEach(x => Npcs.Add(new Npc(x)));
            reference.SpawnPoints.ForEach(x => SpawnPoints.Add(new SpawnPoint(x)));
            reference.Portals.ForEach(x => Portals.Add(new Portal(x)));

            Footholds.CalculateBounds();
            SpawnPoints.Spawn();
            FieldLimit = reference.FieldLimit;
        }
Пример #12
0
        public UserControl1(PencilColor[] pencils, IGameServer server, int columnId, Player currentPlayer)
        {
            InitializeComponent();

            this.pencils       = pencils;
            this.server        = server;
            this.columnId      = columnId;
            this.currentPlayer = currentPlayer;

            int available = 0;

            for (int i = 0; i < pencils.Length; i++)
            {
                PictureBox pic = new PictureBox()
                {
                    Image    = getPic(pencils[i]),
                    Location = new Point(0, i * 30 + 50),
                    Size     = new Size(100, 20)
                };

                this.Controls.Add(pic);

                if (pencils[i] == PencilColor.GREY)
                {
                    comboBox1.Items.Add(++available);
                }
            }

            comboBox1.SelectedItem = pencils.Length;
        }
Пример #13
0
        public Debugger([NotNull] IGameServer gameServer, [NotNull] ISession session)
        {
            this.gameServer = gameServer;
            this.session    = session;
            var state = session.Load <DebuggerState>(debuggerStateKey);

            if (state != null)
            {
                lastProgramStartInfos = state.ProgramStartInfos;
                if (state.GameState != null)
                {
                    try
                    {
                        game = gameServer.ResumeGame(state.GameState);
                    }
                    catch (Exception e)
                    {
                        Log.For(this).Error("Resume game failed", e);
                    }
                }
                if (state.Breakpoints != null)
                {
                    breakpoints.UnionWith(state.Breakpoints);
                }
            }
            if (lastProgramStartInfos == null)
            {
                lastProgramStartInfos = defaultProgramStartInfos;
            }
        }
Пример #14
0
        /// <summary>
        /// Registers the connected client to listen on the events on the specified map. Is called from the client.
        /// </summary>
        /// <param name="serverId">The server identifier.</param>
        /// <param name="mapId">The map identifier.</param>
        /// <remarks>
        /// This is a bit dirty... the AdminPanel should not have the reference to  GameLogic.
        /// Instead we need to extract some interfaces.
        /// TODO: It should also be possible to observe multiple maps through one connection.
        /// </remarks>
        public void Subscribe(byte serverId, ushort mapId)
        {
            IGameServer gameServer = this.servers.OfType <IGameServer>().FirstOrDefault(g => g.Id == serverId);

            if (gameServer == null)
            {
                throw new ArgumentException($"unknown server id {serverId}", nameof(serverId));
            }

            if (!FreeIds.TryDequeue(out ushort observerKey))
            {
                throw new OutOfObserverKeysException();
            }

            var clientProxy = this.Clients.Client(this.Context.ConnectionId);

            WorldObserverToHubAdapter observer = new WorldObserverToHubAdapter(observerKey, serverId, mapId, clientProxy);

            Observers.Add(this.Context.ConnectionId, observer);

            try
            {
                gameServer.RegisterMapObserver(mapId, observer);
            }
            catch (ArgumentException)
            {
                Observers.Remove(this.Context.ConnectionId);
                observer.Dispose();
                throw;
            }
        }
Пример #15
0
 public HelloResponse(IGameServer server, int userId)
 {
     ServerId   = server.Id;
     ServerPort = server.Port;
     ServerName = server.Name;
     UserId     = userId;
 }
Пример #16
0
        //        1. List<pos + DateTime (class)> // högre och högre tid på olika pos
        //        2. bild i ps, rita cirklar dra streck mellan dom..
        //        3. bygga på med vinklar (sist, till att börja med kör vi med position)
        public override void Initialize(GameContext context)
        {
            base.Initialize(context);

            snapShots = new List<Snapshot>();
            snapShots.Add(new Snapshot(TimeSpan.FromSeconds(0), new Vector2(487.0f, 585.0f)));
            snapShots.Add(new Snapshot(TimeSpan.FromSeconds(3), new Vector2(510.0f, 200.0f)));
            snapShots.Add(new Snapshot(TimeSpan.FromSeconds(7), new Vector2(775.0f, 326.0f)));
            snapShots.Add(new Snapshot(TimeSpan.FromSeconds(10), new Vector2(1142.0f, 103.0f)));

            this.spriteBatch = spriteBatch ?? new SpriteBatch(Context.Graphics.Device);

            time = "";
            interpolate = new Vector2();

            gameServer = ServiceLocator.Get<IGameServer>();
            gameClient = ServiceLocator.Get<IGameClient>();
            messageHandler = ServiceLocator.Get<IMessageHandler>();

            // Create the connection between the client and server
            gameServer.Start();
            gameClient.Connect();

            //sendTimer = new GameTimer(TimeSpan.FromMilliseconds(1000 / 20), SendClientSpatial);

            Context.Input.Keyboard.ClearMappings();
            Context.Input.Keyboard.AddMapping(Keys.F1);
            Context.Input.Keyboard.AddMapping(Keys.F2);
            Context.Input.Keyboard.AddMapping(Keys.F3);
        }
Пример #17
0
    public void Initialize()
    {
        gameServer = new GameServer();

        gridOne = Substitute.For <IGrid>();
        gridTwo = Substitute.For <IGrid>();
    }
Пример #18
0
        public void DoStart(IGameServer server, int gameId, int gameType, int mapId, GamePlayerInfo[] playerInfos,
                            string gameHash)
        {
            State               = EGameState.Loading;
            _gameServer         = server;
            Seed                = LRandom.Range(1, 100000);
            Tick                = 0;
            timeSinceLoaded     = 0;
            firstFrameTimeStamp = 0;
            RegisterMsgHandlers();
            Debug = new DebugInstance("Room" + GameId + ": ");
            var count = playerInfos.Length;

            GameType       = gameType;
            GameHash       = gameHash;
            GameId         = gameId;
            MaxPlayerCount = (byte)count;
            Name           = gameId.ToString();
            MapId          = mapId;
            Players        = new Player[count];
            for (byte i = 0; i < count; i++)
            {
                var user   = playerInfos[i];
                var player = CreatePlayer(user, i);
                Players[i] = player;
            }

            _userId2LocalId.Clear();
            TimeSinceCreate = LTime.timeSinceLevelLoad;
            for (byte i = 0; i < count; i++)
            {
                var player = Players[i];
                _userId2LocalId.Add(player.UserId, player.LocalId);
            }
        }
Пример #19
0
 /// <summary>
 /// Retrieve a list of online game servers.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='limit'>
 /// Maximum number of servers to retrieve.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <IList <GameServerInfo> > GetAsync(this IGameServer operations, int limit = 100, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.GetWithHttpMessagesAsync(limit, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Пример #20
0
        private static void CreateDefaultMap(Action <Error, MapInfo> completed)
        {
            MapRoot emptyMap = new MapRoot(8);

            IGameServer     server    = Dependencies.GameServer;
            IGlobalSettings gSettings = Dependencies.Settings;

            Guid    mapId   = Guid.NewGuid();
            MapInfo mapInfo = new MapInfo
            {
                Id             = mapId,
                Name           = "Default",
                MaxPlayers     = GameConstants.MaxPlayers,
                SupportedModes = GameMode.All
            };

            ProtobufSerializer serializer = new ProtobufSerializer();

            byte[]  bytes   = serializer.Serialize(emptyMap);
            MapData mapData = new MapData
            {
                Id    = mapInfo.Id,
                Bytes = bytes,
            };

            server.UploadMap(gSettings.ClientId, mapInfo, mapData, error => completed(error, mapInfo));
        }
Пример #21
0
        private void Awake()
        {
            m_gSettings    = Dependencies.Settings;
            m_gameState    = Dependencies.GameState;
            m_inputManager = Dependencies.InputManager;
            m_navigation   = Dependencies.Navigation;
            m_console      = Dependencies.Console;
            m_notification = Dependencies.Notification;
            m_gameServer   = Dependencies.GameServer;
            m_eventSystem  = Dependencies.EventSystemManager.GetEventSystem(m_localPlayerIndex);

            m_gameState.Completed       += OnGameCompleted;
            m_gameState.IsPausedChanged += OnIsPausedChanged;
            m_gameState.PlayerDefeated  += OnPlayerDefeated;

            m_menuPanel.IsOpenedChanged += OnMenuPanelIsOpenedChanged;
            m_menuPanel.Action          += OnMenuPanelAction;

            m_settingsPanel.IsOpenedChanged += OnSettingsIsOpenedChanged;
            m_settingsPanel.Action          += OnSettingsPanelAction;

            m_consolePanel.IsOpenedChanged += OnConsoleIsOpenedChanged;
            m_consolePanel.Action          += OnConsoleAction;

            m_resultsPanel.IsOpenedChanged += OnResultsIsOpenedChanged;
            m_resultsPanel.Action          += OnResultsPanelAction;
        }
Пример #22
0
    public void Initialize()
    {
        gameServer = new GameServer();

        gridOne = Substitute.For<IGrid>();
        gridTwo = Substitute.For<IGrid>();
    }
Пример #23
0
    void Awake()
    {
        //server = new FakeClientServerSimulator ();
        //((FakeClientServerSimulator)server).Start ();

        server = new DemoTcpClient();
    }
Пример #24
0
 public TestBiomeWorld(int randomSeed, IGameServer gameServer, ItemGeneratorDictionary itemGeneratorDictionary)
     : base(randomSeed, gameServer, itemGeneratorDictionary)
 {
     RequestedChunks   = new List <ChunkKey>();
     RequestedEntities = new List <ChunkKey>();
     RequestedTriggers = new List <ChunkKey>();
 }
Пример #25
0
    public void CanSetGoalScoreWhenInitialize()
    {
        gameServer = new VersusScoreAttackModeGameServer(100);

        gridOne = Substitute.For <IGrid>();
        gridTwo = Substitute.For <IGrid>();
    }
Пример #26
0
 public static IEntityHandle Npc(IGameServer server, IPosition pos, short id, string name)
 {
     var npcs = server.Services.ThrowOrGet<NpcFactory>();
     var p = npcs.Create(name, id);
     p.Get().GetTransform().Teleport(pos);
     return p;
 }
Пример #27
0
        public GameViewModel()
        {
            colours      = new ColourProvider().Colours;
            mapConverter = new MapConverter();

            CanvasWidth  = 800;
            CanvasHeight = 650;

            map = new List <DrawableField>();

            #region counter
            IsCounterRunning           = false;
            defaultColour              = new SolidColorBrush(Color.FromScRgb(1, 0, 0, 0));
            lastSecondsColour          = new SolidColorBrush(Color.FromScRgb(1, 1, 0, 0));
            counterSoundPlayer         = new SoundPlayer(Resources.lastseconds);
            actualRound                = 0;
            remainingSecondsByRound    = new Dictionary <int, int>();
            remainingSecondsByRound[0] = 0;
            #endregion

            nextTurnSoundPlayer = new SoundPlayer(Resources.nextturn);

            gameServer = ClientProxyManager.Instance;
            try
            {
                ClientProxyManager.Instance.RegisterGame(this);
            }
            catch (Exception)
            {
                MessageBox.Show("Connection lost.", "Hanksite", MessageBoxButton.OK);
                Application.Current.Shutdown();
                return;
            }
        }
Пример #28
0
        /// <summary>
        /// Registers the connected client to listen on the events on the specified map. Is called from the client.
        /// </summary>
        /// <param name="serverId">The server identifier.</param>
        /// <param name="mapId">The map identifier.</param>
        /// <remarks>
        /// This is a bit dirty... the AdminPanel should not have the reference to  GameLogic.
        /// Instead we need to extract some interfaces.
        /// </remarks>
        public void Listen(byte serverId, ushort mapId)
        {
            IGameServer gameServer = this.servers.OfType <IGameServer>().FirstOrDefault(g => g.Id == serverId);

            if (gameServer == null)
            {
                throw new ArgumentException($"unknown server id {serverId}", nameof(serverId));
            }

            if (!FreeIds.TryDequeue(out ushort observerKey))
            {
                throw new Exception("no free observer keys available");
            }

            WorldObserverToHubAdapter observer = new WorldObserverToHubAdapter(observerKey, serverId, mapId, this, this.Context.ConnectionId);

            Observers.Add(this.Context.ConnectionId, observer);

            try
            {
                gameServer.RegisterMapObserver(mapId, observer);
            }
            catch (ArgumentException)
            {
                Observers.Remove(this.Context.ConnectionId);
                observer.Dispose();
                throw;
            }
        }
    public void CanSetGoalScoreWhenInitialize()
    {
        gameServer = new VersusScoreAttackModeGameServer(100);

        gridOne = Substitute.For<IGrid>();
        gridTwo = Substitute.For<IGrid>();
    }
Пример #30
0
 /// <summary>
 /// Initializes client properties.
 /// </summary>
 private void Initialize()
 {
     GameServer            = new GameServer(this);
     BaseUri               = new System.Uri("https://localhost:44305");
     SerializationSettings = new JsonSerializerSettings
     {
         Formatting            = Newtonsoft.Json.Formatting.Indented,
         DateFormatHandling    = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
         DateTimeZoneHandling  = Newtonsoft.Json.DateTimeZoneHandling.Utc,
         NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
         ContractResolver      = new ReadOnlyJsonContractResolver(),
         Converters            = new  List <JsonConverter>
         {
             new Iso8601TimeSpanConverter()
         }
     };
     DeserializationSettings = new JsonSerializerSettings
     {
         DateFormatHandling    = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
         DateTimeZoneHandling  = Newtonsoft.Json.DateTimeZoneHandling.Utc,
         NullValueHandling     = Newtonsoft.Json.NullValueHandling.Ignore,
         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
         ContractResolver      = new ReadOnlyJsonContractResolver(),
         Converters            = new List <JsonConverter>
         {
             new Iso8601TimeSpanConverter()
         }
     };
     CustomInitialize();
 }
Пример #31
0
    public GameManagerSystem()
    {
        _games = new List<IGame>();
        //_gameServer = new GameServer();
        _gameServer = new VersusScoreAttackModeGameServer();

        InputManager.OnPauseKeyPressed += new InputManager.PauseKeyEvent(Pause);
    }
Пример #32
0
        public override void Initialize(GameContext context)
        {
            base.Initialize(context);

            globalSettings = ServiceLocator.Get<GlobalSettings>();
            gameServer = ServiceLocator.Get<IGameServer>();
            gameClient = ServiceLocator.Get<IGameClient>();
        }
Пример #33
0
 public GameServerListener(int port, IGameServer gs, Action <GameSocket> onSocket)
 {
     _gs       = gs;
     _listener = new TcpListener(System.Net.IPAddress.Any, port);
     _onSocket = onSocket;
     _listener.Start();
     Task.Factory.StartNew(Run, TaskCreationOptions.LongRunning);
 }
Пример #34
0
    public GameManagerSystem()
    {
        _games = new List <IGame>();
        //_gameServer = new GameServer();
        _gameServer = new VersusScoreAttackModeGameServer();

        InputManager.OnPauseKeyPressed += new InputManager.PauseKeyEvent(Pause);
    }
Пример #35
0
 private void Start()
 {
     m_notification     = Dependencies.Notification;
     m_remoteGameServer = Dependencies.RemoteGameServer;
     UpdateButtonState();
     m_remoteGameServer.ConnectionStateChanging += OnConnectionStateChanging;
     m_remoteGameServer.ConnectionStateChanged  += OnConnectionStateChanged;
 }
Пример #36
0
        public object Run(IGameServer gameServer, params object[] args)
        {
            IPlayerDAO dao    = gameServer.Persistence.GetPlayerDAO();
            Player     player = CreatePlayer();

            dao.InsertPlayer(player);
            return(true);
        }
Пример #37
0
 public GameForm()
 {
     InitializeComponent();
     InitGamePanels();
     _channelFactory = new DuplexChannelFactory<IGameServer>(this, "GameClientEP");
     _server = _channelFactory.CreateChannel();
     nameTextBox.Text = "";
 }
Пример #38
0
        public void SetUp()
        {
            theGameState = new StubGameState();
            theLocator = new InMemoryServiceLocator();
            theLogger = new NullLog();

            theSocket = new StubAsyncSocket();

            theLocator.Add<IAsyncSocket>(theSocket);

            theGameServer = new SimpleGameServer(theGameState, theLogger, theLocator);
        }
Пример #39
0
        public override void Initialize(GameContext context)
        {
            base.Initialize(context);

            stringBuilder = new StringBuilder(100, 500);

            gameServer = ServiceLocator.Get<IGameServer>();
            gameClient = ServiceLocator.Get<IGameClient>();

            // Create the connection between the client and server
            gameServer.Start();
            gameClient.Connect();

            startedLoading = false;
            hasRenderedContent = false;
        }
Пример #40
0
        internal static GameServerInfo Parse(IGameServer server, ushort ping, BufferReader reader)
        {
            var result = new GameServerInfo
            {
                Server = server,
                ProtocolVersion = reader.ReadByte(),
                Name = reader.ReadString(),
                Map = reader.ReadString(),
                Gamedir = reader.ReadString(),
                Game = reader.ReadString(),
                AppId = reader.ReadShort(),
                Players = reader.ReadByte(),
                MaxPlayers = reader.ReadByte(),
                Bots = reader.ReadByte(),
                Type = ReadType(reader),
                Environment = ReadEnvironment(reader),
                HasPassword = reader.ReadBool(),
                Vac = reader.ReadBool(),
                Version = reader.ReadString(),
                Ping = ping
            };

            return result;
        }
Пример #41
0
 public GameController(IGameServer server)
 {
     _server = server;
 }
Пример #42
0
 public void RegisterGameToTheGameServer(IGameServer gameServer)
 {
     _gameServer = gameServer;
     _gameServer.Register(_grid);
 }
Пример #43
0
        public override void AwakeFromNib()
        {
            base.AwakeFromNib();

            InitializeVitalsAndRTBars();

            Window.Title = "Outlander";

            _gameServer = _bootStrapper.Build();
            _services = _bootStrapper.ServiceLocator();

            var appSettings = _services.Get<AppSettings>();
            var homeDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Documents/Outlander");
            appSettings.HomeDirectory = homeDir;

            _services.Get<IAppDirectoriesBuilder>().Build();
            _services.Get<IAppSettingsLoader>().Load();

            UpdateImages();

            _commandProcessor = _services.Get<ICommandProcessor>();
            _scriptLog = _services.Get<IScriptLog>();
            _services.Get<IRoundtimeHandler>().Changed += (sender, e) => {
                SetRoundtime(e);
            };

            _highlightSettings = _services.Get<HighlightSettings>();
            _mainTextViewWrapper = new TextViewWrapper(MainTextView, _highlightSettings);

            _scriptLog.Info += (sender, e) => {
                string log;
                if(e.LineNumber > -1)
                {
                    log = "[{0}({1})]:  {2}\n".ToFormat(e.Name, e.LineNumber, e.Data);
                }
                else
                {
                    log = "[{0}]:  {1}\n".ToFormat(e.Name, e.Data);
                }

                BeginInvokeOnMainThread(()=> {

                    var hasLineFeed = MainTextView.TextStorage.Value.EndsWith("\n");

                    if(!hasLineFeed)
                        log = "\n" + log;

                    var tag = TextTag.For(log, "#0066CC");

                    _mainTextViewWrapper.Append(tag);
                });
            };

            _scriptLog.NotifyStarted += (sender, e) => {

                var log = "[{0}]: {1} - script started\n".ToFormat(e.Name, e.Started.ToString("G"));

                BeginInvokeOnMainThread(()=> {

                    var hasLineFeed = MainTextView.TextStorage.Value.EndsWith("\n");

                    if(!hasLineFeed)
                        log = "\n" + log;

                    var tag = TextTag.For(log, "ADFF2F");
                    _mainTextViewWrapper.Append(tag);
                });
            };

            _scriptLog.NotifyAborted += (sender, e) => {
                var log = "[{0}]: total runtime {1:hh\\:mm\\:ss} - {2} seconds\n".ToFormat(e.Name, e.Runtime, Math.Round(e.Runtime.TotalSeconds, 2));

                BeginInvokeOnMainThread(()=> {

                    var hasLineFeed = MainTextView.TextStorage.Value.EndsWith("\n");

                    if(!hasLineFeed)
                        log = "\n" + log;

                    var tag = TextTag.For(log, "ADFF2F");
                    _mainTextViewWrapper.Append(tag);
                });
            };

            var notifyLogger = new NotificationLogger();
            notifyLogger.OnError = (err) => {
                BeginInvokeOnMainThread(()=> {
                    LogSystem(err.Message + "\n\n");
                });
            };

            var compositeLogger = _services.Get<ILog>().As<CompositeLog>();
            compositeLogger.Add(notifyLogger);

            _gameServer.GameState.Tags = (tags) => {
                tags.Apply(t => {
                    t.As<AppTag>().IfNotNull(appInfo => {
                        BeginInvokeOnMainThread(() => {
                            Window.Title = string.Format("{0}: {1} - {2}", appInfo.Game, appInfo.Character, "Outlander");
                        });
                    });

                    t.As<StreamTag>().IfNotNull(streamTag => {
                        if(!string.IsNullOrWhiteSpace(streamTag.Id) && streamTag.Id.Equals("logons")) {

                            var text = "[{0}]{1}".ToFormat(DateTime.Now.ToString("HH:mm"), streamTag.Text);
                            var highlights = _services.Get<Highlights>().For(TextTag.For(text));

                            BeginInvokeOnMainThread(()=> {
                                highlights.Apply(h => {
                                    h.Mono = true;
                                    Append(h, ArrivalsTextView);
                                });
                            });
                        }

                        if(!string.IsNullOrWhiteSpace(streamTag.Id) && streamTag.Id.Equals("thoughts")) {

                            var text = "[{0}]: {1}".ToFormat(DateTime.Now.ToString("HH:mm"), streamTag.Text);
                            var highlights = _services.Get<Highlights>().For(TextTag.For(text));

                            BeginInvokeOnMainThread(()=> {
                                highlights.Apply(h => {
                                    Append(h, ThoughtsTextView);
                                });
                            });
                        }

                        if(!string.IsNullOrWhiteSpace(streamTag.Id) && streamTag.Id.Equals("death")) {

                            var text = "[{0}]{1}".ToFormat(DateTime.Now.ToString("HH:mm"), streamTag.Text);
                            var highlights = _services.Get<Highlights>().For(TextTag.For(text));

                            BeginInvokeOnMainThread(()=> {
                                highlights.Apply(h => {
                                    Append(h, DeathsTextView);
                                });
                            });
                        }
                    });

                    t.As<SpellTag>().IfNotNull(s => {
                        BeginInvokeOnMainThread(() => {
                            _spell = s.Spell;
                            _count = 0;
                            SpellLabel.StringValue = "S: {0}".ToFormat(s.Spell);

                            if(!string.Equals(_spell, "None"))
                            {
                                _gameServer.GameState.Set(ComponentKeys.SpellTime, "0");
                                _spellTimer.Start();
                            }
                            else
                            {
                                _spellTimer.Stop();
                                _gameServer.GameState.Set(ComponentKeys.SpellTime, "0");
                            }
                        });
                    });

                    t.As<VitalsTag>().IfNotNull(v => {
                        UpdateVitals();
                    });

                    var ids = new string[]
                    {
                        ComponentKeys.RoomTitle,
                        ComponentKeys.RoomDescription,
                        ComponentKeys.RoomObjects,
                        ComponentKeys.RoomPlayers,
                        ComponentKeys.RoomExists
                    };

                    t.As<ComponentTag>().IfNotNull(c => {
                        if(!ids.Contains(c.Id))
                            return;
                        var builder = new StringBuilder();
                        _gameServer.GameState.Get(ComponentKeys.RoomTitle).IfNotNullOrEmpty(s=>builder.AppendLine(s));
                        _gameServer.GameState.Get(ComponentKeys.RoomDescription).IfNotNullOrEmpty(s=>builder.AppendLine(s));
                        _gameServer.GameState.Get(ComponentKeys.RoomObjectsH).IfNotNullOrEmpty(s=>builder.AppendLine(s));
                        _gameServer.GameState.Get(ComponentKeys.RoomPlayers).IfNotNullOrEmpty(s=>builder.AppendLine(s));
                        _gameServer.GameState.Get(ComponentKeys.RoomExists).IfNotNullOrEmpty(s=>builder.AppendLine(s));

                        BeginInvokeOnMainThread(()=> {
                            LogRoom(builder.ToString(), RoomTextView);
                        });
                    });

                    BeginInvokeOnMainThread(()=> {
                        UpdateImages();

                        LeftHandLabel.StringValue = string.Format("L: {0}", _gameServer.GameState.Get(ComponentKeys.LeftHand));
                        RightHandLabel.StringValue = string.Format("R: {0}", _gameServer.GameState.Get(ComponentKeys.RightHand));
                    });

                    _services.Get<IAppSettingsLoader>().SaveVariables();
                });
            };

            _gameServer.GameState.Exp = (exp) => {

                _expTracker.Update(exp);

                var skills = _expTracker.SkillsWithExp().ToList();
                var tags = skills
                        .OrderBy(x => x.Name)
                        .Select(x =>
                        {
                            var color = x.IsNew ? _highlightSettings.Get(HighlightKeys.Whisper).Color : string.Empty;
                            return TextTag.For(x.Display() + "\n", color, true);
                        }).ToList();
                var now = DateTime.Now;
                tags.Add(TextTag.For("Last updated: {0:hh\\:mm\\:ss tt}\n".ToFormat(now), string.Empty, true));
                if(_expTracker.StartedTracking.HasValue)
                    tags.Add(TextTag.For("Tracking for: {0:hh\\:mm\\:ss}\n".ToFormat(now - _expTracker.StartedTracking.Value), string.Empty, true));

                BeginInvokeOnMainThread(()=> {
                    ReplaceText(tags, ExpTextView);
                });
            };

            _gameStream = _services.Get<IGameStream>();
            _gameStreamListener = new GameStreamListener(tag => {
                BeginInvokeOnMainThread(()=>{
                    if(tag.Filtered)
                        return;
                    Log(tag);
                });
            });
            _gameStreamListener.Subscribe(_gameStream);
        }
Пример #44
0
        /*
        /// <summary>
        /// Accept incoming connection for NPC-Control
        /// </summary>
        /// <param name="ar"></param>
        protected void NCControl_Accept(IAsyncResult ar)
        {
            // Accept Socket
            NCConnection Client = new NCConnection(this, (Socket)NCListen.EndAcceptSocket(ar));
            Client.ReceiveData();
            NCList.Add(Client);

            // Listen for incoming connections
            NCListen.BeginAcceptSocket(cNCAccept, NCListen);
        }
        */
        /// <summary>
        /// Run NPC Server
        /// </summary>
        public void RunServer()
        {
            // Run Timeouts
            /*
            foreach (KeyValuePair<String, ServerWeapon> wep in WeaponList)
            {
                ScriptObj obj = (ScriptObj)wep.Value.ScriptObject;
                if (obj != null)
                    obj.RunEvents();
            }

            // Level-Npcs
            lock (TimerLock)
            {
                foreach (KeyValuePair<String, GraalLevel> lvl in LevelList)
                {
                    foreach (KeyValuePair<int, GraalLevelNPC> npc in lvl.Value.NpcList)
                    {
                        ScriptObj obj = (ScriptObj)npc.Value.ScriptObject;
                        if (obj != null)
                            obj.RunEvents();
                    }
                }
            }

            while (Compiler.RunList.Count > 0)
            {
                IRefObject obj;
                lock (Compiler.RunList)
                    obj = Compiler.RunList.Dequeue();
                obj.Call("onCreated", null);
            }
            */
            this.form = Abstraction.GetInstance();

            this.form.Activate();
            this.form.WriteText("--- OpenGraal Instant Messenger / Remote Control ---");
            this.serverWindow = ServerWindow.GetInstance();
            // Default PM
            this.NCMsg = CString.tokenize("I am the Framework for\nthis game server. Almost\nall npc actions are controled\nby me.");

            // Create Compiler
            //Compiler = new GameCompiler(this);

            // Create Player Manager
            PlayerManager = new GraalPlayerList();

            // Connect to GServer
            GSConn = (IGameServer)new Connections.GraalServer();
            GSConn.RunServer();

            if (this.serverWindow.nickname != null && this.serverWindow.nickname != "")
                this.nickname = this.serverWindow.nickname;

            if (this.serverWindow.username != null && this.serverWindow.username != "")
                this.username = this.serverWindow.username;

            if (this.serverWindow.password != null && this.serverWindow.password != "")
                this.password = this.serverWindow.password;

            if (this.serverWindow.gserver != null && this.serverWindow.gserver != "")
                server = this.serverWindow.gserver;

            if (this.serverWindow.gport != null && this.serverWindow.gport != 0)
                this.port = this.serverWindow.gport;

            //GSConn.Disconnect();
            if (!GSConn.Connected)
            {
                this.form.WriteText("Not connected, connecting...");
                this.form.WriteText("Address:\t" + this.server);
                this.form.WriteText("Port:\t\t" + this.port.ToString());
                GSConn.Connect(this.server, this.port);

            }
            else
                this.form.WriteText("Already connected!");

            if (GSConn.Connected)
            {
                GSConn.SendLogin(this.username, this.password, this.nickname);
            }
        }
Пример #45
0
 /// <summary>
 /// Run NPC Server
 /// </summary>
 public void CloseServers()
 {
     this.GSConn.Disconnect();
     this.GSConn = null;
     //this.NCListen.Stop();
 }