Example #1
0
        public static void LoadMapSettings(Session.Global gs, Ruleset rules)
        {
            var devMode = rules.Actors["player"].TraitInfo<DeveloperModeInfo>();
            gs.AllowCheats = devMode.Enabled;

            var crateSpawner = rules.Actors["world"].TraitInfoOrDefault<CrateSpawnerInfo>();
            gs.Crates = crateSpawner != null && crateSpawner.Enabled;

            var shroud = rules.Actors["player"].TraitInfo<ShroudInfo>();
            gs.Fog = shroud.FogEnabled;
            gs.Shroud = !shroud.ExploredMapEnabled;

            var resources = rules.Actors["player"].TraitInfo<PlayerResourcesInfo>();
            gs.StartingCash = resources.DefaultCash;

            var startingUnits = rules.Actors["world"].TraitInfoOrDefault<SpawnMPUnitsInfo>();
            gs.StartingUnitsClass = startingUnits == null ? "none" : startingUnits.StartingUnitsClass;

            var mapBuildRadius = rules.Actors["world"].TraitInfoOrDefault<MapBuildRadiusInfo>();
            gs.AllyBuildRadius = mapBuildRadius != null && mapBuildRadius.AllyBuildRadiusEnabled;

            var mapCreeps = rules.Actors["world"].TraitInfoOrDefault<MapCreepsInfo>();
            gs.Creeps = mapCreeps != null && mapCreeps.Enabled;

            var mapOptions = rules.Actors["world"].TraitInfo<MapOptionsInfo>();
            gs.ShortGame = mapOptions.ShortGameEnabled;
            gs.TechLevel = mapOptions.TechLevel;
            gs.Difficulty = mapOptions.Difficulty ?? mapOptions.Difficulties.FirstOrDefault();
        }
Example #2
0
 public static Dictionary<CPos, SpawnOccupant> GetSpawnOccupants(Session lobbyInfo, MapPreview preview)
 {
     var spawns = preview.SpawnPoints;
     return lobbyInfo.Clients
         .Where(c => (c.SpawnPoint - 1 >= 0) && (c.SpawnPoint - 1 < spawns.Length))
         .ToDictionary(c => spawns[c.SpawnPoint - 1], c => new SpawnOccupant(c));
 }
Example #3
0
        public Replay(string filename)
        {
            Filename = filename;
            var lastFrame = 0;
            var hasSeenGameStart = false;
            var lobbyInfo = null as Session;

            using (var conn = new ReplayConnection(filename))
                conn.Receive((client, packet) =>
                    {
                        var frame = BitConverter.ToInt32(packet, 0);
                        if (packet.Length == 5 && packet[4] == 0xBF)
                            return;	// disconnect
                        else if (packet.Length >= 5 && packet[4] == 0x65)
                            return;	// sync
                        else if (frame == 0)
                        {
                            /* decode this to recover lobbyinfo, etc */
                            var orders = packet.ToOrderList(null);
                            foreach (var o in orders)
                                if (o.OrderString == "StartGame")
                                    hasSeenGameStart = true;
                                else if (o.OrderString == "SyncInfo" && !hasSeenGameStart)
                                    lobbyInfo = Session.Deserialize(o.TargetString);
                        }
                        else
                            lastFrame = Math.Max(lastFrame, frame);
                    });

            Duration = lastFrame * Game.NetTickScale;
            LobbyInfo = lobbyInfo;
        }
Example #4
0
		public static void ShowSlotDropDown(Ruleset rules, DropDownButtonWidget dropdown, Session.Slot slot,
			Session.Client client, OrderManager orderManager)
		{
			var options = new Dictionary<string, IEnumerable<SlotDropDownOption>>() {{"Slot", new List<SlotDropDownOption>()
			{
				new SlotDropDownOption("Open", "slot_open "+slot.PlayerReference, () => (!slot.Closed && client == null)),
				new SlotDropDownOption("Closed", "slot_close "+slot.PlayerReference, () => slot.Closed)
			}}};

			var bots = new List<SlotDropDownOption>();
			if (slot.AllowBots)
			{
				foreach (var b in rules.Actors["player"].Traits.WithInterface<IBotInfo>().Select(t => t.Name))
				{
					var bot = b;
					var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin);
					bots.Add(new SlotDropDownOption(bot,
						"slot_bot {0} {1} {2}".F(slot.PlayerReference, botController.Index, bot),
						() => client != null && client.Bot == bot));
				}
			}
			options.Add(bots.Any() ? "Bots" : "Bots Disabled", bots);

			Func<SlotDropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (o, itemTemplate) =>
			{
				var item = ScrollItemWidget.Setup(itemTemplate,
					o.Selected,
					() => orderManager.IssueOrder(Order.Command(o.Order)));
				item.Get<LabelWidget>("LABEL").GetText = () => o.Title;
				return item;
			};

			dropdown.ShowDropDown<SlotDropDownOption>("LABEL_DROPDOWN_TEMPLATE", 167, options, setupItem);
		}
Example #5
0
		static Player FindPlayerByClient(this World world, Session.Client c)
		{
			/* TODO: this is still a hack.
			 * the cases we're trying to avoid are the extra players on the host's client -- Neutral, other MapPlayers,..*/
			return world.Players.FirstOrDefault(
				p => (p.ClientIndex == c.Index && p.PlayerReference.Playable));
		}
Example #6
0
        public static void ShowSlotDropDown(DropDownButtonWidget dropdown, Session.Slot slot,
			Session.Client client, OrderManager orderManager)
        {
            var options = new List<SlotDropDownOption>()
            {
                new SlotDropDownOption("Open", "slot_open "+slot.PlayerReference, () => (!slot.Closed && client == null)),
                new SlotDropDownOption("Closed", "slot_close "+slot.PlayerReference, () => slot.Closed)
            };

            if (slot.AllowBots)
                foreach (var b in Rules.Info["player"].Traits.WithInterface<IBotInfo>().Select(t => t.Name))
                {
                    var bot = b;
                    options.Add(new SlotDropDownOption("Bot: {0}".F(bot),
                        "slot_bot {0} {1}".F(slot.PlayerReference, bot),
                        () => client != null && client.Bot == bot));
                }

            Func<SlotDropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (o, itemTemplate) =>
            {
                var item = ScrollItemWidget.Setup(itemTemplate,
                    o.Selected,
                    () => orderManager.IssueOrder(Order.Command(o.Order)));
                item.GetWidget<LabelWidget>("LABEL").GetText = () => o.Title;
                return item;
            };

            dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 150, options, setupItem);
        }
Example #7
0
		public SpawnOccupant(Session.Client client)
		{
			Color = client.Color;
			ClientIndex = client.Index;
			PlayerName = client.Name;
			Team = client.Team;
			Country = client.Country;
			SpawnPoint = client.SpawnPoint;
		}
Example #8
0
        public Player(World world, Session.Client client, PlayerReference pr)
        {
            string botType;

            World = world;
            InternalName = pr.Name;
            PlayerReference = pr;

            // Real player or host-created bot
            if (client != null)
            {
                ClientIndex = client.Index;
                Color = client.Color;
                PlayerName = client.Name;
                botType = client.Bot;
                Faction = ChooseFaction(world, client.Faction, !pr.LockFaction);
                DisplayFaction = ChooseDisplayFaction(world, client.Faction);
            }
            else
            {
                // Map player
                ClientIndex = 0; // Owned by the host (TODO: fix this)
                Color = pr.Color;
                PlayerName = pr.Name;
                NonCombatant = pr.NonCombatant;
                Playable = pr.Playable;
                Spectating = pr.Spectating;
                botType = pr.Bot;
                Faction = ChooseFaction(world, pr.Faction, false);
                DisplayFaction = ChooseDisplayFaction(world, pr.Faction);
            }

            PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) });
            Shroud = PlayerActor.Trait<Shroud>();

            fogVisibilities = PlayerActor.TraitsImplementing<IFogVisibilityModifier>().ToArray();

            // Enable the bot logic on the host
            IsBot = botType != null;
            if (IsBot && Game.IsHost)
            {
                var logic = PlayerActor.TraitsImplementing<IBot>().FirstOrDefault(b => b.Info.Name == botType);
                if (logic == null)
                    Log.Write("debug", "Invalid bot type: {0}", botType);
                else
                    logic.Activate(this);
            }

            stanceColors.Self = ChromeMetrics.Get<Color>("PlayerStanceColorSelf");
            stanceColors.Allies = ChromeMetrics.Get<Color>("PlayerStanceColorAllies");
            stanceColors.Enemies = ChromeMetrics.Get<Color>("PlayerStanceColorEnemies");
            stanceColors.Neutrals = ChromeMetrics.Get<Color>("PlayerStanceColorNeutrals");
        }
Example #9
0
        public static string LatencyDescription(Session.ClientPing ping)
        {
            if (ping == null)
                return "Unknown";

            if (ping.Latency < 0)
                return "Unknown";
            if (ping.Latency < 300)
                return "Good";
            if (ping.Latency < 600)
                return "Moderate";
            return "Poor";
        }
Example #10
0
		public static void SyncClientToPlayerReference(Session.Client c, PlayerReference pr)
		{
			if (pr == null)
				return;

			if (pr.LockFaction)
				c.Faction = pr.Faction;
			if (pr.LockSpawn)
				c.SpawnPoint = pr.Spawn;
			if (pr.LockTeam)
				c.Team = pr.Team;

			c.Color = pr.LockColor ? pr.Color : c.PreferredColor;
		}
Example #11
0
		public static void ShowTeamDropDown(DropDownButtonWidget dropdown, Session.Client client,
			OrderManager orderManager, int teamCount)
		{
			Func<int, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, itemTemplate) =>
			{
				var item = ScrollItemWidget.Setup(itemTemplate,
					() => client.Team == ii,
					() => orderManager.IssueOrder(Order.Command("team {0} {1}".F(client.Index, ii))));
				item.Get<LabelWidget>("LABEL").GetText = () => ii == 0 ? "-" : ii.ToString();
				return item;
			};

			var options = Exts.MakeArray(teamCount + 1, i => i).ToList();
			dropdown.ShowDropDown("TEAM_DROPDOWN_TEMPLATE", 150, options, setupItem);
		}
Example #12
0
        public static bool ValidateCommand(S server, Connection conn, Session.Client client, string cmd)
        {
            if (server.State == ServerState.GameStarted)
            {
                server.SendOrderTo(conn, "Message", "Cannot change state when game started. ({0})".F(cmd));
                return false;
            }
            else if (client.State == Session.ClientState.Ready && !(cmd.StartsWith("state") || cmd == "startgame"))
            {
                server.SendOrderTo(conn, "Message", "Cannot change state when marked as ready.");
                return false;
            }

            return true;
        }
Example #13
0
		public static void SyncClientToPlayerReference(Session.Client c, PlayerReference pr)
		{
			if (pr == null)
				return;
			if (pr.LockColor)
				c.Color = pr.Color;
			else
				c.Color = c.PreferredColor;
			if (pr.LockRace)
				c.Country = pr.Race;
			if (pr.LockSpawn)
				c.SpawnPoint = pr.Spawn;
			if (pr.LockTeam)
				c.Team = pr.Team;
		}
Example #14
0
        public static Color LatencyColor(Session.ClientPing ping)
        {
            if (ping == null)
                return Color.Gray;

            // Levels set relative to the default order lag of 3 net ticks (360ms)
            // TODO: Adjust this once dynamic lag is implemented
            if (ping.Latency < 0)
                return Color.Gray;
            if (ping.Latency < 300)
                return Color.LimeGreen;
            if (ping.Latency < 600)
                return Color.Orange;
            return Color.Red;
        }
Example #15
0
		static bool ValidateSlotCommand(S server, Connection conn, Session.Client client, string arg, bool requiresHost)
		{
			if (!server.LobbyInfo.Slots.ContainsKey(arg))
			{
				Log.Write("server", "Invalid slot: {0}", arg);
				return false;
			}

			if (requiresHost && !client.IsAdmin)
			{
				server.SendOrderTo(conn, "Message", "Only the host can do that.");
				return false;
			}

			return true;
		}
Example #16
0
        public Player(World world, Session.Client client, Session.Slot slot, PlayerReference pr)
        {
            World = world;
            InternalName = pr.Name;
            PlayerReference = pr;
            string botType = null;

            // Real player or host-created bot
            if (client != null)
            {
                ClientIndex = client.Index;
                Color = client.Color;
                PlayerName = client.Name;
                botType = client.Bot;
                Country = ChooseCountry(world, client.Race, !pr.LockRace);
                DisplayCountry = ChooseDisplayCountry(world, client.Race);
            }
            else
            {
                // Map player
                ClientIndex = 0; // Owned by the host (TODO: fix this)
                Color = pr.Color;
                PlayerName = pr.Name;
                NonCombatant = pr.NonCombatant;
                Playable = pr.Playable;
                Spectating = pr.Spectating;
                botType = pr.Bot;
                Country = ChooseCountry(world, pr.Race, false);
                DisplayCountry = ChooseDisplayCountry(world, pr.Race);
            }

            PlayerActor = world.CreateActor("Player", new TypeDictionary { new OwnerInit(this) });
            Shroud = PlayerActor.Trait<Shroud>();

            // Enable the bot logic on the host
            IsBot = botType != null;
            if (IsBot && Game.IsHost)
            {
                var logic = PlayerActor.TraitsImplementing<IBot>()
                            .FirstOrDefault(b => b.Info.Name == botType);
                if (logic == null)
                    Log.Write("debug", "Invalid bot type: {0}", botType);
                else
                    logic.Activate(this);
            }
        }
Example #17
0
		public void UpdateServerSettings(Session.Global settings)
		{
			if (Cheats.HasValue)
				settings.AllowCheats = Cheats.Value;
			if (Crates.HasValue)
				settings.Crates = Crates.Value;
			if (Fog.HasValue)
				settings.Fog = Fog.Value;
			if (Shroud.HasValue)
				settings.Shroud = Shroud.Value;
			if (AllyBuildRadius.HasValue)
				settings.AllyBuildRadius = AllyBuildRadius.Value;
			if (StartingCash.HasValue)
				settings.StartingCash = StartingCash.Value;
			if (FragileAlliances.HasValue)
				settings.FragileAlliances = FragileAlliances.Value;
		}
Example #18
0
        public static void ShowRaceDropDown(DropDownButtonWidget dropdown, Session.Client client,
			OrderManager orderManager, Dictionary<string, string> countryNames)
        {
            Func<string, ScrollItemWidget, ScrollItemWidget> setupItem = (race, itemTemplate) =>
            {
                var item = ScrollItemWidget.Setup(itemTemplate,
                    () => client.Country == race,
                    () => orderManager.IssueOrder(Order.Command("race {0} {1}".F(client.Index, race))));
                item.GetWidget<LabelWidget>("LABEL").GetText = () => countryNames[race];
                var flag = item.GetWidget<ImageWidget>("FLAG");
                flag.GetImageCollection = () => "flags";
                flag.GetImageName = () => race;
                return item;
            };

            dropdown.ShowDropDown("RACE_DROPDOWN_TEMPLATE", 150, countryNames.Keys.ToList(), setupItem);
        }
Example #19
0
        public static Session Deserialize(string data)
        {
            try
            {
                var session = new Session();

                var nodes = MiniYaml.FromString(data);
                foreach (var node in nodes)
                {
                    var strings = node.Key.Split('@');

                    switch (strings[0])
                    {
                        case "Client":
                            session.Clients.Add(Client.Deserialize(node.Value));
                            break;

                        case "ClientPing":
                            session.ClientPings.Add(ClientPing.Deserialize(node.Value));
                            break;

                        case "GlobalSettings":
                            session.GlobalSettings = Global.Deserialize(node.Value);
                            break;

                        case "Slot":
                            var s = Slot.Deserialize(node.Value);
                            session.Slots.Add(s.PlayerReference, s);
                            break;
                    }
                }

                return session;
            }
            catch (YamlException)
            {
                throw new YamlException("Session deserialized invalid MiniYaml:\n{0}".F(data));
            }
            catch (InvalidOperationException)
            {
                throw new YamlException("Session deserialized invalid MiniYaml:\n{0}".F(data));
            }
        }
Example #20
0
        public static void SetupNameWidget(OrderManager orderManager, Session.Client c, TextFieldWidget name)
        {
            name.Text = c.Name;
            name.OnEnterKey = () =>
            {
                name.Text = name.Text.Trim();
                if (name.Text.Length == 0)
                    name.Text = c.Name;

                name.LoseFocus();
                if (name.Text == c.Name)
                    return true;

                orderManager.IssueOrder(Order.Command("name " + name.Text));
                Game.Settings.Player.Name = name.Text;
                Game.Settings.Save();
                return true;
            };
            name.OnLoseFocus = () => name.OnEnterKey();
        }
Example #21
0
        public static void LoadMapSettings(S server, Session.Global gs, Ruleset rules)
        {
            var options = rules.Actors["player"].TraitInfos<ILobbyOptions>()
                .Concat(rules.Actors["world"].TraitInfos<ILobbyOptions>())
                .SelectMany(t => t.LobbyOptions(rules));

            foreach (var o in options)
            {
                var value = o.DefaultValue;
                var preferredValue = o.DefaultValue;
                Session.LobbyOptionState state;
                if (gs.LobbyOptions.TryGetValue(o.Id, out state))
                {
                    // Propagate old state on map change
                    if (!o.Locked)
                    {
                        if (o.Values.Keys.Contains(state.PreferredValue))
                            value = state.PreferredValue;
                        else if (o.Values.Keys.Contains(state.Value))
                            value = state.Value;
                    }

                    preferredValue = state.PreferredValue;
                }
                else
                    state = new Session.LobbyOptionState();

                state.Locked = o.Locked;
                state.Value = value;
                state.PreferredValue = preferredValue;
                gs.LobbyOptions[o.Id] = state;

                if (o.Id == "gamespeed")
                {
                    var speed = server.ModData.Manifest.Get<GameSpeeds>().Speeds[value];
                    gs.Timestep = speed.Timestep;
                    gs.OrderLatency = speed.OrderLatency;
                }
            }
        }
Example #22
0
        public static void ShowSpawnDropDown(DropDownButtonWidget dropdown, Session.Client client,
			OrderManager orderManager, IEnumerable<int> spawnPoints)
        {
            Func<int, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, itemTemplate) =>
            {
                var item = ScrollItemWidget.Setup(itemTemplate,
                    () => client.SpawnPoint == ii,
                    () => SetSpawnPoint(orderManager, client, ii));
                item.Get<LabelWidget>("LABEL").GetText = () => ii == 0 ? "-" : Convert.ToChar('A' - 1 + ii).ToString();
                return item;
            };

            dropdown.ShowDropDown("SPAWN_DROPDOWN_TEMPLATE", 150, spawnPoints, setupItem);
        }
Example #23
0
        public static void ShowFactionDropDown(DropDownButtonWidget dropdown, Session.Client client,
			OrderManager orderManager, Dictionary<string, LobbyFaction> factions)
        {
            Func<string, ScrollItemWidget, ScrollItemWidget> setupItem = (factionId, itemTemplate) =>
            {
                var item = ScrollItemWidget.Setup(itemTemplate,
                    () => client.Faction == factionId,
                    () => orderManager.IssueOrder(Order.Command("faction {0} {1}".F(client.Index, factionId))));
                var faction = factions[factionId];
                item.Get<LabelWidget>("LABEL").GetText = () => faction.Name;
                var flag = item.Get<ImageWidget>("FLAG");
                flag.GetImageCollection = () => "flags";
                flag.GetImageName = () => factionId;
                item.GetTooltipText = () => faction.Description;
                return item;
            };

            var options = factions.Where(f => f.Value.Selectable).GroupBy(f => f.Value.Side)
                .ToDictionary(g => g.Key ?? "", g => g.Select(f => f.Key));

            dropdown.ShowDropDown("FACTION_DROPDOWN_TEMPLATE", 150, options, setupItem);
        }
Example #24
0
        public static void ShowColorDropDown(DropDownButtonWidget color, Session.Client client,
			OrderManager orderManager, World world, ColorPreviewManagerWidget preview)
        {
            Action onExit = () =>
            {
                if (client.Bot == null)
                {
                    Game.Settings.Player.Color = preview.Color;
                    Game.Settings.Save();
                }

                color.RemovePanel();
                orderManager.IssueOrder(Order.Command("color {0} {1}".F(client.Index, preview.Color)));
            };

            Action<HSLColor> onChange = c => preview.Color = c;

            var colorChooser = Game.LoadWidget(world, "COLOR_CHOOSER", null, new WidgetArgs()
            {
                { "onChange", onChange },
                { "initialColor", client.Color }
            });

            color.AttachPanel(colorChooser, onExit);
        }
Example #25
0
 public static void SetupTeamWidget(Widget parent, Session.Slot s, Session.Client c)
 {
     parent.Get<LabelWidget>("TEAM").GetText = () => (c.Team == 0) ? "-" : c.Team.ToString();
 }
Example #26
0
 public static void SetupSpawnWidget(Widget parent, Session.Slot s, Session.Client c)
 {
     parent.Get<LabelWidget>("SPAWN").GetText = () => (c.SpawnPoint == 0) ? "-" : Convert.ToChar('A' - 1 + c.SpawnPoint).ToString();
 }
Example #27
0
        public static void SetupSlotWidget(Widget parent, Session.Slot s, Session.Client c)
        {
            var name = parent.Get<LabelWidget>("NAME");
            name.IsVisible = () => true;
            name.GetText = () => c != null ? c.Name : s.Closed ? "Closed" : "Open";

            // Ensure Slot selector (if present) is hidden
            var slot = parent.GetOrNull("SLOT_OPTIONS");
            if (slot != null)
                slot.IsVisible = () => false;
        }
Example #28
0
 public static void SetupReadyWidget(Widget parent, Session.Slot s, Session.Client c)
 {
     parent.Get<ImageWidget>("STATUS_IMAGE").IsVisible = () => c.IsReady || c.Bot != null;
 }
Example #29
0
 private static void SetSpawnPoint(OrderManager orderManager, Session.Client playerToMove, int selectedSpawn)
 {
     var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == selectedSpawn);
     if (selectedSpawn == 0 || !owned)
         orderManager.IssueOrder(Order.Command("spawn {0} {1}".F((playerToMove ?? orderManager.LocalClient).Index, selectedSpawn)));
 }
Example #30
0
        public static void ProcessOrder(OrderManager orderManager, World world, int clientId, Order order)
        {
            if (world != null)
            {
                if (!world.WorldActor.TraitsImplementing <IValidateOrder>().All(vo =>
                                                                                vo.OrderValidation(orderManager, world, clientId, order)))
                {
                    return;
                }
            }

            switch (order.OrderString)
            {
            case "Chat":
            {
                var client = orderManager.LobbyInfo.ClientWithIndex(clientId);
                if (client != null)
                {
                    var player = world != null?world.FindPlayerByClient(client) : null;

                    var suffix = (player != null && player.WinState == WinState.Lost) ? " (Dead)" : "";
                    suffix = client.IsObserver ? " (Spectator)" : suffix;
                    Game.AddChatLine(client.Color.RGB, client.Name + suffix, order.TargetString);
                }
                else
                {
                    Game.AddChatLine(Color.White, "(player {0})".F(clientId), order.TargetString);
                }
                break;
            }

            case "Message":                     // Server message
                Game.AddChatLine(Color.White, "Server", order.TargetString);
                break;

            case "Disconnected":                     /* reports that the target player disconnected */
            {
                var client = orderManager.LobbyInfo.ClientWithIndex(clientId);
                if (client != null)
                {
                    client.State = Session.ClientState.Disconnected;
                }
                break;
            }

            case "TeamChat":
            {
                var client = orderManager.LobbyInfo.ClientWithIndex(clientId);

                if (client != null)
                {
                    if (world == null)
                    {
                        if (orderManager.LocalClient != null && client.Team == orderManager.LocalClient.Team)
                        {
                            Game.AddChatLine(client.Color.RGB, client.Name + " (Team)",
                                             order.TargetString);
                        }
                    }
                    else
                    {
                        var player = world.FindPlayerByClient(client);
                        if (player == null)
                        {
                            return;
                        }

                        if (world.LocalPlayer != null && player.Stances[world.LocalPlayer] == Stance.Ally || player.WinState == WinState.Lost)
                        {
                            var suffix = player.WinState == WinState.Lost ? " (Dead)" : " (Team)";
                            Game.AddChatLine(client.Color.RGB, client.Name + suffix, order.TargetString);
                        }
                    }
                }
                break;
            }

            case "StartGame":
            {
                Game.AddChatLine(Color.White, "Server", "The game has started.");
                Game.StartGame(orderManager.LobbyInfo.GlobalSettings.Map, false);
                break;
            }

            case "PauseGame":
            {
                var client = orderManager.LobbyInfo.ClientWithIndex(clientId);
                if (client != null)
                {
                    var pause = order.TargetString == "Pause";
                    if (orderManager.world.Paused != pause && !world.LobbyInfo.IsSinglePlayer)
                    {
                        var pausetext = "The game is {0} by {1}".F(pause ? "paused" : "un-paused", client.Name);
                        Game.AddChatLine(Color.White, "", pausetext);
                    }

                    orderManager.world.Paused          = pause;
                    orderManager.world.PredictedPaused = pause;
                }
                break;
            }

            case "HandshakeRequest":
            {
                // TODO: Switch to the server's mod if we have it
                // Otherwise send the handshake with our current settings and let the server reject us
                var mod = Game.modData.Manifest.Mod;

                var info = new Session.Client()
                {
                    Name           = Game.Settings.Player.Name,
                    PreferredColor = Game.Settings.Player.Color,
                    Color          = Game.Settings.Player.Color,
                    Country        = "random",
                    SpawnPoint     = 0,
                    Team           = 0,
                    State          = Session.ClientState.Invalid
                };

                var response = new HandshakeResponse()
                {
                    Client   = info,
                    Mod      = mod.Id,
                    Version  = mod.Version,
                    Password = orderManager.Password
                };

                orderManager.IssueOrder(Order.HandshakeResponse(response.Serialize()));
                break;
            }

            case "ServerError":
            {
                orderManager.ServerError          = order.TargetString;
                orderManager.AuthenticationFailed = false;
                break;
            }

            case "AuthenticationError":
            {
                orderManager.ServerError          = order.TargetString;
                orderManager.AuthenticationFailed = true;
                break;
            }

            case "SyncInfo":
            {
                orderManager.LobbyInfo = Session.Deserialize(order.TargetString);
                SetOrderLag(orderManager);
                Game.SyncLobbyInfo();
                break;
            }

            case "SyncLobbyClients":
            {
                var clients = new List <Session.Client>();
                var nodes   = MiniYaml.FromString(order.TargetString);
                foreach (var node in nodes)
                {
                    var strings = node.Key.Split('@');
                    if (strings[0] == "Client")
                    {
                        clients.Add(Session.Client.Deserialize(node.Value));
                    }
                }

                orderManager.LobbyInfo.Clients = clients;
                Game.SyncLobbyInfo();
                break;
            }

            case "SyncLobbySlots":
            {
                var slots = new Dictionary <string, Session.Slot>();
                var nodes = MiniYaml.FromString(order.TargetString);
                foreach (var node in nodes)
                {
                    var strings = node.Key.Split('@');
                    if (strings[0] == "Slot")
                    {
                        var slot = Session.Slot.Deserialize(node.Value);
                        slots.Add(slot.PlayerReference, slot);
                    }
                }

                orderManager.LobbyInfo.Slots = slots;
                Game.SyncLobbyInfo();
                break;
            }

            case "SyncLobbyGlobalSettings":
            {
                var nodes = MiniYaml.FromString(order.TargetString);
                foreach (var node in nodes)
                {
                    var strings = node.Key.Split('@');
                    if (strings[0] == "GlobalSettings")
                    {
                        orderManager.LobbyInfo.GlobalSettings = Session.Global.Deserialize(node.Value);
                    }
                }

                SetOrderLag(orderManager);
                Game.SyncLobbyInfo();
                break;
            }

            case "SyncClientPings":
            {
                var pings = new List <Session.ClientPing>();
                var nodes = MiniYaml.FromString(order.TargetString);
                foreach (var node in nodes)
                {
                    var strings = node.Key.Split('@');
                    if (strings[0] == "ClientPing")
                    {
                        pings.Add(Session.ClientPing.Deserialize(node.Value));
                    }
                }

                orderManager.LobbyInfo.ClientPings = pings;
                break;
            }

            case "SetStance":
            {
                if (!Game.orderManager.LobbyInfo.GlobalSettings.FragileAlliances)
                {
                    return;
                }

                var targetPlayer = order.Player.World.Players.FirstOrDefault(p => p.InternalName == order.TargetString);
                var newStance    = (Stance)order.ExtraData;

                order.Player.SetStance(targetPlayer, newStance);

                Game.Debug("{0} has set diplomatic stance vs {1} to {2}",
                           order.Player.PlayerName, targetPlayer.PlayerName, newStance);

                // automatically declare war reciprocally
                if (newStance == Stance.Enemy && targetPlayer.Stances[order.Player] == Stance.Ally)
                {
                    targetPlayer.SetStance(order.Player, newStance);
                    Game.Debug("{0} has reciprocated", targetPlayer.PlayerName);
                }

                break;
            }

            case "Ping":
            {
                orderManager.IssueOrder(Order.Pong(order.TargetString));
                break;
            }

            default:
            {
                if (!order.IsImmediate)
                {
                    var self   = order.Subject;
                    var health = self.TraitOrDefault <Health>();
                    if (health == null || !health.IsDead)
                    {
                        foreach (var t in self.TraitsImplementing <IResolveOrder>())
                        {
                            t.ResolveOrder(self, order);
                        }
                    }
                }
                break;
            }
            }
        }
Example #31
0
 public static void SetupNameWidget(Widget parent, Session.Slot s, Session.Client c)
 {
     var name = parent.Get<LabelWidget>("NAME");
     var font = Game.Renderer.Fonts[name.Font];
     var label = WidgetUtils.TruncateText(c.Name, name.Bounds.Width, font);
     name.GetText = () => label;
 }