ScrollItemWidget BasicStats(Player player)
        {
            basicStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(basicPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            var res = player.PlayerActor.Trait <PlayerResources>();

            template.Get <LabelWidget>("CASH").GetText       = () => "$" + (res.DisplayCash + res.DisplayOre);
            template.Get <LabelWidget>("EARNED_MIN").GetText = () => AverageEarnedPerMinute(res.Earned);

            var powerRes = player.PlayerActor.Trait <PowerManager>();
            var power    = template.Get <LabelWidget>("POWER");

            power.GetText  = () => powerRes.PowerDrained + "/" + powerRes.PowerProvided;
            power.GetColor = () => GetPowerColor(powerRes.PowerState);

            var stats = player.PlayerActor.TraitOrDefault <PlayerStatistics>();

            if (stats == null)
            {
                return(template);
            }
            template.Get <LabelWidget>("KILLS").GetText       = () => (stats.UnitsKilled + stats.BuildingsKilled).ToString();
            template.Get <LabelWidget>("DEATHS").GetText      = () => (stats.UnitsDead + stats.BuildingsDead).ToString();
            template.Get <LabelWidget>("ACTIONS_MIN").GetText = () => AverageOrdersPerMinute(stats.OrderCount);

            return(template);
        }
        ScrollItemWidget EconomyStats(Player player)
        {
            economyStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(economyPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            var res   = player.PlayerActor.Trait <PlayerResources>();
            var stats = player.PlayerActor.TraitOrDefault <PlayerStatistics>();

            if (stats == null)
            {
                return(template);
            }

            template.Get <LabelWidget>("CASH").GetText            = () => "$" + (res.DisplayCash + res.DisplayOre);
            template.Get <LabelWidget>("EARNED_MIN").GetText      = () => AverageEarnedPerMinute(res.Earned);
            template.Get <LabelWidget>("EARNED_THIS_MIN").GetText = () => "$" + stats.EarnedThisMinute;
            template.Get <LabelWidget>("EARNED").GetText          = () => "$" + res.Earned;
            template.Get <LabelWidget>("SPENT").GetText           = () => "$" + res.Spent;

            var assets = template.Get <LabelWidget>("ASSETS");

            assets.GetText = () => "$" + world.Actors
                             .Where(a => a.Owner == player && !a.IsDead() && a.Info.Traits.WithInterface <ValuedInfo>().Any())
                             .Sum(a => a.Info.Traits.WithInterface <ValuedInfo>().First().Cost);

            var harvesters = template.Get <LabelWidget>("HARVESTERS");

            harvesters.GetText = () => world.Actors.Count(a => a.Owner == player && !a.IsDead() && a.HasTrait <Harvester>()).ToString();

            return(template);
        }
示例#3
0
        public static void SetupEditableFactionWidget(Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager, Dictionary <string, string> countryNames)
        {
            var dropdown = parent.Get <DropDownButtonWidget>("FACTION");

            dropdown.IsDisabled  = () => s.LockRace || orderManager.LocalClient.IsReady;
            dropdown.OnMouseDown = _ => LobbyUtils.ShowRaceDropDown(dropdown, c, orderManager, countryNames);
            SetupFactionWidget(dropdown, s, c, countryNames);
        }
示例#4
0
        public static void SetupEditableTeamWidget(Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager, int teamCount)
        {
            var dropdown = parent.Get <DropDownButtonWidget>("TEAM");

            dropdown.IsDisabled  = () => s.LockTeam || orderManager.LocalClient.IsReady;
            dropdown.OnMouseDown = _ => LobbyUtils.ShowTeamDropDown(dropdown, c, orderManager, teamCount);
            dropdown.GetText     = () => (c.Team == 0) ? "-" : c.Team.ToString();
        }
示例#5
0
        public static void SetupEditableColorWidget(Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager, ColorPreviewManagerWidget colorPreview)
        {
            var color = parent.Get <DropDownButtonWidget>("COLOR");

            color.IsDisabled  = () => (s != null && s.LockColor) || orderManager.LocalClient.IsReady;
            color.OnMouseDown = _ => LobbyUtils.ShowColorDropDown(color, c, orderManager, colorPreview);

            SetupColorWidget(color, s, c);
        }
        ScrollItemWidget ProductionStats(Player player)
        {
            productionStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(productionPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            template.Get <ObserverProductionIconsWidget>("PRODUCTION_ICONS").GetPlayer      = () => player;
            template.Get <ObserverSupportPowerIconsWidget>("SUPPORT_POWER_ICONS").GetPlayer = () => player;

            return(template);
        }
示例#7
0
        ScrollItemWidget DiplomaticStatus(Player player)
        {
            var playerTemplate = diplomacyPanel.Get <ScrollItemWidget>("PLAYER_TEMPLATE");
            var pt             = ScrollItemWidget.Setup(playerTemplate, () => false, () => { });

            pt.IgnoreMouseOver = true;
            LobbyUtils.AddPlayerFlagAndName(pt, player);
            pt.Get <LabelWidget>("THEIR_STANCE").GetText = () => player.Stances[world.LocalPlayer].ToString();
            var myStance = pt.Get <DropDownButtonWidget>("MY_STANCE");

            myStance.GetText     = () => world.LocalPlayer.Stances[player].ToString();
            myStance.IsDisabled  = () => !world.LobbyInfo.GlobalSettings.FragileAlliances;
            myStance.OnMouseDown = mi => ShowDropDown(player, myStance);
            return(pt);
        }
示例#8
0
        public static void SetupEditableSlotWidget(Widget parent, Session.Slot s, Session.Client c, OrderManager orderManager)
        {
            var slot = parent.Get <DropDownButtonWidget>("SLOT_OPTIONS");

            slot.IsVisible   = () => true;
            slot.IsDisabled  = () => orderManager.LocalClient.IsReady;
            slot.GetText     = () => c != null ? c.Name : s.Closed ? "Closed" : "Open";
            slot.OnMouseDown = _ => LobbyUtils.ShowSlotDropDown(slot, s, c, orderManager);

            // Ensure Name selector (if present) is hidden
            var name = parent.GetOrNull("NAME");

            if (name != null)
            {
                name.IsVisible = () => false;
            }
        }
示例#9
0
        public ClientTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, OrderManager orderManager, int clientIndex)
        {
            var admin     = widget.Get <LabelWidget>("ADMIN");
            var adminFont = Game.Renderer.Fonts[admin.Font];

            var latency     = widget.Get <LabelWidget>("LATENCY");
            var latencyFont = Game.Renderer.Fonts[latency.Font];

            var ip     = widget.Get <LabelWidget>("IP");
            var ipFont = Game.Renderer.Fonts[ip.Font];

            var ipOffset      = ip.Bounds.Y;
            var latencyOffset = latency.Bounds.Y;
            var tooltipHeight = widget.Bounds.Height;

            var margin = widget.Bounds.Width;

            tooltipContainer.IsVisible    = () => (orderManager.LobbyInfo.ClientWithIndex(clientIndex) != null);
            tooltipContainer.BeforeRender = () =>
            {
                var width = Math.Max(adminFont.Measure(admin.GetText()).X, Math.Max(ipFont.Measure(ip.GetText()).X, latencyFont.Measure(latency.GetText()).X));
                widget.Bounds.Width  = width + 2 * margin;
                latency.Bounds.Width = widget.Bounds.Width;
                ip.Bounds.Width      = widget.Bounds.Width;
                admin.Bounds.Width   = widget.Bounds.Width;

                ip.Bounds.Y          = ipOffset;
                latency.Bounds.Y     = latencyOffset;
                widget.Bounds.Height = tooltipHeight;

                if (admin.IsVisible())
                {
                    ip.Bounds.Y          += admin.Bounds.Height;
                    latency.Bounds.Y     += admin.Bounds.Height;
                    widget.Bounds.Height += admin.Bounds.Height;
                }
            };

            admin.IsVisible = () => orderManager.LobbyInfo.ClientWithIndex(clientIndex).IsAdmin;
            latency.GetText = () => "Latency: {0}".F(LobbyUtils.LatencyDescription(orderManager.LobbyInfo.ClientWithIndex(clientIndex).Latency));
            ip.GetText      = () => LobbyUtils.DescriptiveIpAddress(orderManager.LobbyInfo.ClientWithIndex(clientIndex).IpAddress);
        }
        ScrollItemWidget CombatStats(Player player)
        {
            combatStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(combatPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            var stats = player.PlayerActor.TraitOrDefault <PlayerStatistics>();

            if (stats == null)
            {
                return(template);
            }
            template.Get <LabelWidget>("CONTROL").GetText          = () => MapControl(stats.MapControl);
            template.Get <LabelWidget>("KILLS_COST").GetText       = () => "$" + stats.KillsCost;
            template.Get <LabelWidget>("DEATHS_COST").GetText      = () => "$" + stats.DeathsCost;
            template.Get <LabelWidget>("UNITS_KILLED").GetText     = () => stats.UnitsKilled.ToString();
            template.Get <LabelWidget>("UNITS_DEAD").GetText       = () => stats.UnitsDead.ToString();
            template.Get <LabelWidget>("BUILDINGS_KILLED").GetText = () => stats.BuildingsKilled.ToString();
            template.Get <LabelWidget>("BUILDINGS_DEAD").GetText   = () => stats.BuildingsDead.ToString();

            return(template);
        }
示例#11
0
        internal LobbyMapPreviewLogic(Widget widget, OrderManager orderManager, LobbyLogic lobby)
        {
            var available = widget.GetOrNull("MAP_AVAILABLE");

            if (available != null)
            {
                available.IsVisible = () => lobby.Map.Status == MapStatus.Available && lobby.Map.RuleStatus == MapRuleStatus.Cached;

                var preview = available.Get <MapPreviewWidget>("MAP_PREVIEW");
                preview.Preview        = () => lobby.Map;
                preview.OnMouseDown    = mi => LobbyUtils.SelectSpawnPoint(orderManager, preview, lobby.Map, mi);
                preview.SpawnOccupants = () => LobbyUtils.GetSpawnOccupants(orderManager.LobbyInfo, lobby.Map);

                var title = available.GetOrNull <LabelWidget>("MAP_TITLE");
                if (title != null)
                {
                    title.GetText = () => lobby.Map.Title;
                }

                var type = available.GetOrNull <LabelWidget>("MAP_TYPE");
                if (type != null)
                {
                    type.GetText = () => lobby.Map.Type;
                }

                var author = available.GetOrNull <LabelWidget>("MAP_AUTHOR");
                if (author != null)
                {
                    author.GetText = () => "Created by {0}".F(lobby.Map.Author);
                }
            }

            var invalid = widget.GetOrNull("MAP_INVALID");

            if (invalid != null)
            {
                invalid.IsVisible = () => lobby.Map.Status == MapStatus.Available && lobby.Map.RuleStatus == MapRuleStatus.Invalid;

                var preview = invalid.Get <MapPreviewWidget>("MAP_PREVIEW");
                preview.Preview        = () => lobby.Map;
                preview.OnMouseDown    = mi => LobbyUtils.SelectSpawnPoint(orderManager, preview, lobby.Map, mi);
                preview.SpawnOccupants = () => LobbyUtils.GetSpawnOccupants(orderManager.LobbyInfo, lobby.Map);

                var title = invalid.GetOrNull <LabelWidget>("MAP_TITLE");
                if (title != null)
                {
                    title.GetText = () => lobby.Map.Title;
                }

                var type = invalid.GetOrNull <LabelWidget>("MAP_TYPE");
                if (type != null)
                {
                    type.GetText = () => lobby.Map.Type;
                }
            }

            var download = widget.GetOrNull("MAP_DOWNLOADABLE");

            if (download != null)
            {
                download.IsVisible = () => lobby.Map.Status == MapStatus.DownloadAvailable;

                var preview = download.Get <MapPreviewWidget>("MAP_PREVIEW");
                preview.Preview        = () => lobby.Map;
                preview.OnMouseDown    = mi => LobbyUtils.SelectSpawnPoint(orderManager, preview, lobby.Map, mi);
                preview.SpawnOccupants = () => LobbyUtils.GetSpawnOccupants(orderManager.LobbyInfo, lobby.Map);

                var title = download.GetOrNull <LabelWidget>("MAP_TITLE");
                if (title != null)
                {
                    title.GetText = () => lobby.Map.Title;
                }

                var type = download.GetOrNull <LabelWidget>("MAP_TYPE");
                if (type != null)
                {
                    type.GetText = () => lobby.Map.Type;
                }

                var author = download.GetOrNull <LabelWidget>("MAP_AUTHOR");
                if (author != null)
                {
                    author.GetText = () => "Created by {0}".F(lobby.Map.Author);
                }

                var install = download.GetOrNull <ButtonWidget>("MAP_INSTALL");
                if (install != null)
                {
                    install.OnClick = () => lobby.Map.Install();
                }
            }

            var progress = widget.GetOrNull("MAP_PROGRESS");

            if (progress != null)
            {
                progress.IsVisible = () => (lobby.Map.Status != MapStatus.Available || lobby.Map.RuleStatus == MapRuleStatus.Unknown) && lobby.Map.Status != MapStatus.DownloadAvailable;

                var preview = progress.Get <MapPreviewWidget>("MAP_PREVIEW");
                preview.Preview        = () => lobby.Map;
                preview.OnMouseDown    = mi => LobbyUtils.SelectSpawnPoint(orderManager, preview, lobby.Map, mi);
                preview.SpawnOccupants = () => LobbyUtils.GetSpawnOccupants(orderManager.LobbyInfo, lobby.Map);

                var title = progress.GetOrNull <LabelWidget>("MAP_TITLE");
                if (title != null)
                {
                    title.GetText = () => lobby.Map.Title;
                }

                var type = progress.GetOrNull <LabelWidget>("MAP_TYPE");
                if (type != null)
                {
                    type.GetText = () => lobby.Map.Type;
                }

                var statusSearching = progress.GetOrNull("MAP_STATUS_SEARCHING");
                if (statusSearching != null)
                {
                    statusSearching.IsVisible = () => lobby.Map.Status == MapStatus.Searching;
                }

                var statusUnavailable = progress.GetOrNull("MAP_STATUS_UNAVAILABLE");
                if (statusUnavailable != null)
                {
                    statusUnavailable.IsVisible = () => lobby.Map.Status == MapStatus.Unavailable;
                }

                var statusError = progress.GetOrNull("MAP_STATUS_ERROR");
                if (statusError != null)
                {
                    statusError.IsVisible = () => lobby.Map.Status == MapStatus.DownloadError;
                }

                var statusDownloading = progress.GetOrNull <LabelWidget>("MAP_STATUS_DOWNLOADING");
                if (statusDownloading != null)
                {
                    statusDownloading.IsVisible = () => lobby.Map.Status == MapStatus.Downloading;
                    statusDownloading.GetText   = () =>
                    {
                        if (lobby.Map.DownloadBytes == 0)
                        {
                            return("Connecting...");
                        }

                        // Server does not provide the total file length
                        if (lobby.Map.DownloadPercentage == 0)
                        {
                            return("Downloading {0} kB".F(lobby.Map.DownloadBytes / 1024));
                        }

                        return("Downloading {0} kB ({1}%)".F(lobby.Map.DownloadBytes / 1024, lobby.Map.DownloadPercentage));
                    };
                }

                var retry = progress.GetOrNull <ButtonWidget>("MAP_RETRY");
                if (retry != null)
                {
                    retry.IsVisible = () => lobby.Map.Status == MapStatus.DownloadError || lobby.Map.Status == MapStatus.Unavailable;
                    retry.OnClick   = () =>
                    {
                        if (lobby.Map.Status == MapStatus.DownloadError)
                        {
                            lobby.Map.Install();
                        }
                        else if (lobby.Map.Status == MapStatus.Unavailable)
                        {
                            Game.modData.MapCache.QueryRemoteMapDetails(new [] { lobby.Map.Uid });
                        }
                    };

                    retry.GetText = () => lobby.Map.Status == MapStatus.DownloadError ? "Retry Install" : "Retry Search";
                }

                var progressbar = progress.GetOrNull <ProgressBarWidget>("MAP_PROGRESSBAR");
                if (progressbar != null)
                {
                    progressbar.IsIndeterminate = () => lobby.Map.DownloadPercentage == 0;
                    progressbar.GetPercentage   = () => lobby.Map.DownloadPercentage;
                    progressbar.IsVisible       = () => !retry.IsVisible();
                }
            }
        }
示例#12
0
        public void RefreshServerList(Widget panel, IEnumerable <GameServer> games)
        {
            var sl = panel.Get <ScrollPanelWidget>("SERVER_LIST");

            searchStatus = SearchStatus.Fetching;

            sl.RemoveChildren();
            currentServer = null;

            if (games == null)
            {
                searchStatus = SearchStatus.Failed;
                return;
            }

            if (games.Count() == 0)
            {
                searchStatus = SearchStatus.NoGames;
                return;
            }

            searchStatus  = SearchStatus.Hidden;
            currentServer = games.FirstOrDefault();

            foreach (var loop in games.OrderByDescending(g => g.CanJoin()).ThenByDescending(g => g.Players))
            {
                var game = loop;

                var canJoin = game.CanJoin();

                var item = ScrollItemWidget.Setup(serverTemplate, () => currentServer == game, () => currentServer = game, () => Join(game));

                var preview = item.Get <MapPreviewWidget>("MAP_PREVIEW");
                preview.Map       = () => GetMapPreview(game);
                preview.IsVisible = () => GetMapPreview(game) != null;

                var title = item.Get <LabelWidget>("TITLE");
                title.GetText = () => game.Name;

                // TODO: Use game.MapTitle once the server supports it
                var maptitle = item.Get <LabelWidget>("MAP");
                maptitle.GetText = () =>
                {
                    var map = Game.modData.FindMapByUid(game.Map);
                    return(map == null ? "Unknown Map" : map.Title);
                };

                // TODO: Use game.MaxPlayers once the server supports it
                var players = item.Get <LabelWidget>("PLAYERS");
                players.GetText = () => GetPlayersLabel(game);

                var state = item.Get <LabelWidget>("STATE");
                state.GetText = () => GetStateLabel(game);

                var ip = item.Get <LabelWidget>("IP");
                ip.GetText = () => game.Address;

                var version = item.Get <LabelWidget>("VERSION");
                version.GetText   = () => GenerateModsLabel(game);
                version.IsVisible = () => !game.CompatibleVersion();

                var location             = item.Get <LabelWidget>("LOCATION");
                var cachedServerLocation = LobbyUtils.LookupCountry(game.Address.Split(':')[0]);
                location.GetText   = () => cachedServerLocation;
                location.IsVisible = () => game.CompatibleVersion();

                if (!canJoin)
                {
                    title.GetColor    = () => Color.Gray;
                    maptitle.GetColor = () => Color.Gray;
                    players.GetColor  = () => Color.Gray;
                    state.GetColor    = () => Color.Gray;
                    ip.GetColor       = () => Color.Gray;
                    version.GetColor  = () => Color.Gray;
                    location.GetColor = () => Color.Gray;
                }

                if (!Filtered(game))
                {
                    sl.AddChild(item);
                }
            }
        }
示例#13
0
        public void RefreshServerListInner(IEnumerable <GameServer> games)
        {
            if (games == null)
            {
                return;
            }

            var rows = new List <Widget>();

            foreach (var loop in games.OrderByDescending(g => g.CanJoin()).ThenByDescending(g => g.Players))
            {
                var game = loop;
                if (game == null)
                {
                    continue;
                }

                var canJoin = game.CanJoin();

                var item = ScrollItemWidget.Setup(serverTemplate, () => currentServer == game, () => currentServer = game, () => Join(game));

                var map     = Game.modData.MapCache[game.Map];
                var preview = item.GetOrNull <MapPreviewWidget>("MAP_PREVIEW");
                if (preview != null)
                {
                    preview.Preview = () => map;
                }

                var title = item.GetOrNull <LabelWidget>("TITLE");
                if (title != null)
                {
                    title.GetText  = () => game.Name;
                    title.GetColor = () => canJoin ? title.TextColor : Color.Gray;
                }

                var maptitle = item.GetOrNull <LabelWidget>("MAP");
                if (title != null)
                {
                    maptitle.GetText  = () => map.Title;
                    maptitle.GetColor = () => canJoin ? maptitle.TextColor : Color.Gray;
                }

                var players = item.GetOrNull <LabelWidget>("PLAYERS");
                if (players != null)
                {
                    players.GetText  = () => "{0} / {1}".F(game.Players, map.PlayerCount);
                    players.GetColor = () => canJoin ? players.TextColor : Color.Gray;
                }

                var state = item.GetOrNull <LabelWidget>("STATE");
                if (state != null)
                {
                    state.GetText  = () => GetStateLabel(game);
                    state.GetColor = () => canJoin ? state.TextColor : Color.Gray;
                }

                var ip = item.GetOrNull <LabelWidget>("IP");
                if (ip != null)
                {
                    ip.GetText  = () => game.Address;
                    ip.GetColor = () => canJoin ? ip.TextColor : Color.Gray;
                }

                var version = item.GetOrNull <LabelWidget>("VERSION");
                if (version != null)
                {
                    version.GetText   = () => GenerateModLabel(game);
                    version.IsVisible = () => !game.CompatibleVersion();
                    version.GetColor  = () => canJoin ? version.TextColor : Color.Gray;
                }

                var location = item.GetOrNull <LabelWidget>("LOCATION");
                if (location != null)
                {
                    var cachedServerLocation = LobbyUtils.LookupCountry(game.Address.Split(':')[0]);
                    location.GetText   = () => cachedServerLocation;
                    location.IsVisible = () => game.CompatibleVersion();
                    location.GetColor  = () => canJoin ? location.TextColor : Color.Gray;
                }

                if (!Filtered(game))
                {
                    rows.Add(item);
                }
            }

            Game.RunAfterTick(() =>
            {
                serverList.RemoveChildren();
                currentServer = null;

                if (games == null)
                {
                    searchStatus = SearchStatus.Failed;
                    return;
                }

                if (!games.Any())
                {
                    searchStatus = SearchStatus.NoGames;
                    return;
                }

                currentServer = games.FirstOrDefault();
                searchStatus  = SearchStatus.Hidden;

                // Search for any unknown maps
                if (Game.Settings.Game.AllowDownloading)
                {
                    Game.modData.MapCache.QueryRemoteMapDetails(games.Where(g => !Filtered(g)).Select(g => g.Map));
                }

                foreach (var row in rows)
                {
                    serverList.AddChild(row);
                }
            });
        }
示例#14
0
        void UpdatePlayerList()
        {
            var idx = 0;

            foreach (var kv in orderManager.LobbyInfo.Slots)
            {
                var    key      = kv.Key;
                var    slot     = kv.Value;
                var    client   = orderManager.LobbyInfo.ClientInSlot(key);
                Widget template = null;

                // get template for possible reuse
                if (idx < Players.Children.Count)
                {
                    template = Players.Children[idx];
                }

                // Empty slot
                if (client == null)
                {
                    if (template == null || template.Id != EmptySlotTemplate.Id)
                    {
                        template = EmptySlotTemplate.Clone();
                    }

                    if (Game.IsHost)
                    {
                        LobbyUtils.SetupEditableSlotWidget(template, slot, client, orderManager);
                    }
                    else
                    {
                        LobbyUtils.SetupSlotWidget(template, slot, client);
                    }

                    var join = template.Get <ButtonWidget>("JOIN");
                    join.IsVisible  = () => !slot.Closed;
                    join.IsDisabled = () => orderManager.LocalClient.IsReady;
                    join.OnClick    = () => orderManager.IssueOrder(Order.Command("slot " + key));
                }

                // Editable player in slot
                else if ((client.Index == orderManager.LocalClient.Index) ||
                         (client.Bot != null && Game.IsHost))
                {
                    if (template == null || template.Id != EditablePlayerTemplate.Id)
                    {
                        template = EditablePlayerTemplate.Clone();
                    }

                    LobbyUtils.SetupClientWidget(template, slot, client, orderManager, client.Bot == null);

                    if (client.Bot != null)
                    {
                        LobbyUtils.SetupEditableSlotWidget(template, slot, client, orderManager);
                    }
                    else
                    {
                        LobbyUtils.SetupEditableNameWidget(template, slot, client, orderManager);
                    }

                    LobbyUtils.SetupEditableColorWidget(template, slot, client, orderManager, colorPreview);
                    LobbyUtils.SetupEditableFactionWidget(template, slot, client, orderManager, CountryNames);
                    LobbyUtils.SetupEditableTeamWidget(template, slot, client, orderManager, Map.GetSpawnPoints().Length);
                    LobbyUtils.SetupEditableReadyWidget(template, slot, client, orderManager);
                }
                else
                {                       // Non-editable player in slot
                    if (template == null || template.Id != NonEditablePlayerTemplate.Id)
                    {
                        template = NonEditablePlayerTemplate.Clone();
                    }

                    LobbyUtils.SetupClientWidget(template, slot, client, orderManager, client.Bot == null);
                    LobbyUtils.SetupNameWidget(template, slot, client);
                    LobbyUtils.SetupKickWidget(template, slot, client, orderManager, lobby,
                                               () => panel = PanelType.Kick, () => panel = PanelType.Players);
                    LobbyUtils.SetupColorWidget(template, slot, client);
                    LobbyUtils.SetupFactionWidget(template, slot, client, CountryNames);
                    LobbyUtils.SetupTeamWidget(template, slot, client);
                    LobbyUtils.SetupReadyWidget(template, slot, client);
                }

                template.IsVisible = () => true;

                if (idx >= Players.Children.Count)
                {
                    Players.AddChild(template);
                }
                else if (Players.Children[idx].Id != template.Id)
                {
                    Players.ReplaceChild(Players.Children[idx], template);
                }

                idx++;
            }

            // Add spectators
            foreach (var client in orderManager.LobbyInfo.Clients.Where(client => client.Slot == null))
            {
                Widget template = null;
                var    c        = client;

                // get template for possible reuse
                if (idx < Players.Children.Count)
                {
                    template = Players.Children[idx];
                }

                // Editable spectator
                if (c.Index == orderManager.LocalClient.Index)
                {
                    if (template == null || template.Id != EditableSpectatorTemplate.Id)
                    {
                        template = EditableSpectatorTemplate.Clone();
                    }

                    LobbyUtils.SetupEditableNameWidget(template, null, c, orderManager);
                }
                // Non-editable spectator
                else
                {
                    if (template == null || template.Id != NonEditableSpectatorTemplate.Id)
                    {
                        template = NonEditableSpectatorTemplate.Clone();
                    }

                    LobbyUtils.SetupNameWidget(template, null, client);
                    LobbyUtils.SetupKickWidget(template, null, client, orderManager, lobby,
                                               () => panel = PanelType.Kick, () => panel = PanelType.Players);
                }

                LobbyUtils.SetupClientWidget(template, null, c, orderManager, true);
                template.IsVisible = () => true;

                if (idx >= Players.Children.Count)
                {
                    Players.AddChild(template);
                }
                else if (Players.Children[idx].Id != template.Id)
                {
                    Players.ReplaceChild(Players.Children[idx], template);
                }

                idx++;
            }

            // Spectate button
            if (orderManager.LocalClient.Slot != null)
            {
                Widget spec = null;
                if (idx < Players.Children.Count)
                {
                    spec = Players.Children[idx];
                }
                if (spec == null || spec.Id != NewSpectatorTemplate.Id)
                {
                    spec = NewSpectatorTemplate.Clone();
                }

                var btn = spec.Get <ButtonWidget>("SPECTATE");
                btn.OnClick    = () => orderManager.IssueOrder(Order.Command("spectate"));
                btn.IsDisabled = () => orderManager.LocalClient.IsReady;
                spec.IsVisible = () => true;

                if (idx >= Players.Children.Count)
                {
                    Players.AddChild(spec);
                }
                else if (Players.Children[idx].Id != spec.Id)
                {
                    Players.ReplaceChild(Players.Children[idx], spec);
                }

                idx++;
            }

            while (Players.Children.Count > idx)
            {
                Players.RemoveChild(Players.Children[idx]);
            }
        }
示例#15
0
        void SelectReplay(ReplayMetadata replay)
        {
            selectedReplay = replay;
            selectedSpawns = (selectedReplay != null)
                                ? LobbyUtils.GetSpawnOccupants(selectedReplay.GameInfo.Players, selectedReplay.GameInfo.MapPreview)
                                : new Dictionary <CPos, SpawnOccupant>();

            if (replay == null)
            {
                return;
            }

            try
            {
                var players = replay.GameInfo.Players
                              .GroupBy(p => p.Team)
                              .OrderBy(g => g.Key);

                var teams   = new Dictionary <string, IEnumerable <GameInformation.Player> >();
                var noTeams = players.Count() == 1;
                foreach (var p in players)
                {
                    var label = noTeams ? "Players" : p.Key == 0 ? "No Team" : "Team {0}".F(p.Key);
                    teams.Add(label, p);
                }

                playerList.RemoveChildren();

                foreach (var kv in teams)
                {
                    var group = kv.Key;
                    if (group.Length > 0)
                    {
                        var header = ScrollItemWidget.Setup(playerHeader, () => true, () => { });
                        header.Get <LabelWidget>("LABEL").GetText = () => group;
                        playerList.AddChild(header);
                    }

                    foreach (var option in kv.Value)
                    {
                        var o = option;

                        var color = o.Color.RGB;

                        var item = ScrollItemWidget.Setup(playerTemplate, () => false, () => { });

                        var label = item.Get <LabelWidget>("LABEL");
                        label.GetText  = () => o.Name;
                        label.GetColor = () => color;

                        var flag = item.Get <ImageWidget>("FLAG");
                        flag.GetImageCollection = () => "flags";
                        flag.GetImageName       = () => o.FactionId;

                        playerList.AddChild(item);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Write("debug", "Exception while parsing replay: {0}", e);
                SelectReplay(null);
            }
        }
示例#16
0
        void UpdatePlayerList()
        {
            // This causes problems for people who are in the process of editing their names (the widgets vanish from beneath them)
            // Todo: handle this nicer
            Players.RemoveChildren();

            foreach (var kv in orderManager.LobbyInfo.Slots)
            {
                var    key    = kv.Key;
                var    slot   = kv.Value;
                var    client = orderManager.LobbyInfo.ClientInSlot(key);
                Widget template;

                // Empty slot
                if (client == null)
                {
                    template = EmptySlotTemplate.Clone();
                    Func <string> getText = () => slot.Closed ? "Closed" : "Open";
                    var           ready   = orderManager.LocalClient.IsReady;

                    if (Game.IsHost)
                    {
                        var name = template.GetWidget <DropDownButtonWidget>("NAME_HOST");
                        name.IsVisible   = () => true;
                        name.IsDisabled  = () => ready;
                        name.GetText     = getText;
                        name.OnMouseDown = _ => LobbyUtils.ShowSlotDropDown(name, slot, client, orderManager);
                    }
                    else
                    {
                        var name = template.GetWidget <LabelWidget>("NAME");
                        name.IsVisible = () => true;
                        name.GetText   = getText;
                    }

                    var join = template.GetWidget <ButtonWidget>("JOIN");
                    join.IsVisible  = () => !slot.Closed;
                    join.IsDisabled = () => ready;
                    join.OnClick    = () => orderManager.IssueOrder(Order.Command("slot " + key));
                }
                // Editable player in slot
                else if ((client.Index == orderManager.LocalClient.Index) ||
                         (client.Bot != null && Game.IsHost))
                {
                    template = EditablePlayerTemplate.Clone();
                    var botReady = client.Bot != null && Game.IsHost && orderManager.LocalClient.IsReady;
                    var ready    = botReady || client.IsReady;

                    if (client.Bot != null)
                    {
                        var name = template.GetWidget <DropDownButtonWidget>("BOT_DROPDOWN");
                        name.IsVisible   = () => true;
                        name.IsDisabled  = () => ready;
                        name.GetText     = () => client.Name;
                        name.OnMouseDown = _ => LobbyUtils.ShowSlotDropDown(name, slot, client, orderManager);
                    }
                    else
                    {
                        var name = template.GetWidget <TextFieldWidget>("NAME");
                        name.IsVisible  = () => true;
                        name.IsDisabled = () => ready;
                        LobbyUtils.SetupNameWidget(orderManager, client, name);
                    }

                    var color = template.GetWidget <DropDownButtonWidget>("COLOR");
                    color.IsDisabled  = () => slot.LockColor || ready;
                    color.OnMouseDown = _ => LobbyUtils.ShowColorDropDown(color, client, orderManager, PlayerPalettePreview);

                    var colorBlock = color.GetWidget <ColorBlockWidget>("COLORBLOCK");
                    colorBlock.GetColor = () => client.ColorRamp.GetColor(0);

                    var faction = template.GetWidget <DropDownButtonWidget>("FACTION");
                    faction.IsDisabled  = () => slot.LockRace || ready;
                    faction.OnMouseDown = _ => LobbyUtils.ShowRaceDropDown(faction, client, orderManager, CountryNames);

                    var factionname = faction.GetWidget <LabelWidget>("FACTIONNAME");
                    factionname.GetText = () => CountryNames[client.Country];
                    var factionflag = faction.GetWidget <ImageWidget>("FACTIONFLAG");
                    factionflag.GetImageName       = () => client.Country;
                    factionflag.GetImageCollection = () => "flags";

                    var team = template.GetWidget <DropDownButtonWidget>("TEAM");
                    team.IsDisabled  = () => slot.LockTeam || ready;
                    team.OnMouseDown = _ => LobbyUtils.ShowTeamDropDown(team, client, orderManager, Map);
                    team.GetText     = () => (client.Team == 0) ? "-" : client.Team.ToString();

                    if (client.Bot == null)
                    {
                        // local player
                        var status = template.GetWidget <CheckboxWidget>("STATUS_CHECKBOX");
                        status.IsChecked = () => ready;
                        status.IsVisible = () => true;
                        status.OnClick  += CycleReady;
                    }
                    else                     // Bot
                    {
                        template.GetWidget <ImageWidget>("STATUS_IMAGE").IsVisible = () => true;
                    }
                }
                else
                {                       // Non-editable player in slot
                    template = NonEditablePlayerTemplate.Clone();
                    template.GetWidget <LabelWidget>("NAME").GetText = () => client.Name;
                    var color = template.GetWidget <ColorBlockWidget>("COLOR");
                    color.GetColor = () => client.ColorRamp.GetColor(0);

                    var faction     = template.GetWidget <LabelWidget>("FACTION");
                    var factionname = faction.GetWidget <LabelWidget>("FACTIONNAME");
                    factionname.GetText = () => CountryNames[client.Country];
                    var factionflag = faction.GetWidget <ImageWidget>("FACTIONFLAG");
                    factionflag.GetImageName       = () => client.Country;
                    factionflag.GetImageCollection = () => "flags";

                    var team = template.GetWidget <LabelWidget>("TEAM");
                    team.GetText = () => (client.Team == 0) ? "-" : client.Team.ToString();

                    template.GetWidget <ImageWidget>("STATUS_IMAGE").IsVisible = () =>
                                                                                 client.Bot != null || client.IsReady;

                    var kickButton = template.GetWidget <ButtonWidget>("KICK");
                    kickButton.IsVisible  = () => Game.IsHost && client.Index != orderManager.LocalClient.Index;
                    kickButton.IsDisabled = () => orderManager.LocalClient.IsReady;
                    kickButton.OnClick    = () => orderManager.IssueOrder(Order.Command("kick " + client.Index));
                }

                template.IsVisible = () => true;
                Players.AddChild(template);
            }

            // Add spectators
            foreach (var client in orderManager.LobbyInfo.Clients.Where(client => client.Slot == null))
            {
                Widget template;
                var    c     = client;
                var    ready = c.IsReady;

                // Editable spectator
                if (c.Index == orderManager.LocalClient.Index)
                {
                    template = EditableSpectatorTemplate.Clone();
                    var name = template.GetWidget <TextFieldWidget>("NAME");
                    name.IsDisabled = () => ready;
                    LobbyUtils.SetupNameWidget(orderManager, c, name);

                    var color = template.GetWidget <DropDownButtonWidget>("COLOR");
                    color.IsDisabled  = () => ready;
                    color.OnMouseDown = _ => LobbyUtils.ShowColorDropDown(color, c, orderManager, PlayerPalettePreview);

                    var colorBlock = color.GetWidget <ColorBlockWidget>("COLORBLOCK");
                    colorBlock.GetColor = () => c.ColorRamp.GetColor(0);

                    var status = template.GetWidget <CheckboxWidget>("STATUS_CHECKBOX");
                    status.IsChecked = () => ready;
                    status.OnClick  += CycleReady;
                }
                // Non-editable spectator
                else
                {
                    template = NonEditableSpectatorTemplate.Clone();
                    template.GetWidget <LabelWidget>("NAME").GetText = () => c.Name;
                    var color = template.GetWidget <ColorBlockWidget>("COLOR");
                    color.GetColor = () => c.ColorRamp.GetColor(0);

                    template.GetWidget <ImageWidget>("STATUS_IMAGE").IsVisible = () => c.Bot != null || c.IsReady;

                    var kickButton = template.GetWidget <ButtonWidget>("KICK");
                    kickButton.IsVisible  = () => Game.IsHost && c.Index != orderManager.LocalClient.Index;
                    kickButton.IsDisabled = () => orderManager.LocalClient.IsReady;
                    kickButton.OnClick    = () => orderManager.IssueOrder(Order.Command("kick " + c.Index));
                }

                template.IsVisible = () => true;
                Players.AddChild(template);
            }

            // Spectate button
            if (orderManager.LocalClient.Slot != null)
            {
                var spec = NewSpectatorTemplate.Clone();
                var btn  = spec.GetWidget <ButtonWidget>("SPECTATE");
                btn.OnClick    = () => orderManager.IssueOrder(Order.Command("spectate"));
                btn.IsDisabled = () => orderManager.LocalClient.IsReady;
                spec.IsVisible = () => true;
                Players.AddChild(spec);
            }
        }
示例#17
0
        internal LobbyLogic(Widget widget, World world, OrderManager orderManager,
                            Action onExit, Action onStart, bool addBots)
        {
            var lobby = widget;

            this.orderManager = orderManager;
            this.OnGameStart  = () => { CloseWindow(); onStart(); };
            this.onExit       = onExit;

            Game.LobbyInfoChanged       += UpdateCurrentMap;
            Game.LobbyInfoChanged       += UpdatePlayerList;
            Game.BeforeGameStart        += OnGameStart;
            Game.AddChatLine            += AddChatLine;
            Game.ConnectionStateChanged += ConnectionStateChanged;

            UpdateCurrentMap();
            PlayerPalettePreview      = world.WorldActor.Trait <ColorPickerPaletteModifier>();
            PlayerPalettePreview.Ramp = Game.Settings.Player.ColorRamp;
            Players = lobby.GetWidget <ScrollPanelWidget>("PLAYERS");
            EditablePlayerTemplate       = Players.GetWidget("TEMPLATE_EDITABLE_PLAYER");
            NonEditablePlayerTemplate    = Players.GetWidget("TEMPLATE_NONEDITABLE_PLAYER");
            EmptySlotTemplate            = Players.GetWidget("TEMPLATE_EMPTY");
            EditableSpectatorTemplate    = Players.GetWidget("TEMPLATE_EDITABLE_SPECTATOR");
            NonEditableSpectatorTemplate = Players.GetWidget("TEMPLATE_NONEDITABLE_SPECTATOR");
            NewSpectatorTemplate         = Players.GetWidget("TEMPLATE_NEW_SPECTATOR");

            var mapPreview = lobby.GetWidget <MapPreviewWidget>("MAP_PREVIEW");

            mapPreview.IsVisible   = () => Map != null;
            mapPreview.Map         = () => Map;
            mapPreview.OnMouseDown = mi => LobbyUtils.SelectSpawnPoint(orderManager, mapPreview, Map, mi);
            mapPreview.SpawnColors = () => LobbyUtils.GetSpawnColors(orderManager, Map);

            var mapTitle = lobby.GetWidget <LabelWidget>("MAP_TITLE");

            if (mapTitle != null)
            {
                mapTitle.IsVisible = () => Map != null;
                mapTitle.GetText   = () => Map.Title;
            }

            CountryNames = Rules.Info["world"].Traits.WithInterface <CountryInfo>()
                           .Where(c => c.Selectable)
                           .ToDictionary(a => a.Race, a => a.Name);
            CountryNames.Add("random", "Any");

            var mapButton = lobby.GetWidget <ButtonWidget>("CHANGEMAP_BUTTON");

            mapButton.OnClick = () =>
            {
                var onSelect = new Action <Map>(m =>
                {
                    orderManager.IssueOrder(Order.Command("map " + m.Uid));
                    Game.Settings.Server.Map = m.Uid;
                    Game.Settings.Save();
                });

                Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", Map.Uid },
                    { "onExit", () => {} },
                    { "onSelect", onSelect }
                });
            };
            mapButton.IsVisible = () => mapButton.Visible && Game.IsHost;

            var disconnectButton = lobby.GetWidget <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = () => { CloseWindow(); onExit(); };

            var gameStarting = false;

            var allowCheats = lobby.GetWidget <CheckboxWidget>("ALLOWCHEATS_CHECKBOX");

            allowCheats.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats;
            allowCheats.IsDisabled = () => !Game.IsHost || gameStarting || orderManager.LocalClient == null ||
                                     orderManager.LocalClient.IsReady;
            allowCheats.OnClick = () => orderManager.IssueOrder(Order.Command(
                                                                    "allowcheats {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowCheats)));

            var startGameButton = lobby.GetWidget <ButtonWidget>("START_GAME_BUTTON");

            startGameButton.IsVisible  = () => Game.IsHost;
            startGameButton.IsDisabled = () => gameStarting;
            startGameButton.OnClick    = () =>
            {
                gameStarting = true;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            bool teamChat      = false;
            var  chatLabel     = lobby.GetWidget <LabelWidget>("LABEL_CHATTYPE");
            var  chatTextField = lobby.GetWidget <TextFieldWidget>("CHAT_TEXTFIELD");

            chatTextField.OnEnterKey = () =>
            {
                if (chatTextField.Text.Length == 0)
                {
                    return(true);
                }

                orderManager.IssueOrder(Order.Chat(teamChat, chatTextField.Text));
                chatTextField.Text = "";
                return(true);
            };

            chatTextField.OnTabKey = () =>
            {
                teamChat      ^= true;
                chatLabel.Text = (teamChat) ? "Team:" : "Chat:";
                return(true);
            };

            chatPanel    = lobby.GetWidget <ScrollPanelWidget>("CHAT_DISPLAY");
            chatTemplate = chatPanel.GetWidget("CHAT_TEMPLATE");
            chatPanel.RemoveChildren();

            var musicButton = lobby.GetWidget <ButtonWidget>("MUSIC_BUTTON");

            if (musicButton != null)
            {
                musicButton.OnClick = () => Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => {} }
                });
            }

            // Add a bot on the first lobbyinfo update
            if (addBots)
            {
                Game.LobbyInfoChanged += WidgetUtils.Once(() =>
                {
                    var slot = orderManager.LobbyInfo.FirstEmptySlot();
                    var bot  = Rules.Info["player"].Traits.WithInterface <IBotInfo>().Select(t => t.Name).FirstOrDefault();
                    if (slot != null && bot != null)
                    {
                        orderManager.IssueOrder(Order.Command("slot_bot {0} {1}".F(slot, bot)));
                    }
                });
            }
        }
示例#18
0
        public ObserverStatsLogic(World world, WorldRenderer worldRenderer, Widget widget, Action onExit)
        {
            this.world         = world;
            this.worldRenderer = worldRenderer;
            players            = world.Players.Where(p => !p.NonCombatant);

            basicStatsHeaders            = widget.Get <ContainerWidget>("BASIC_STATS_HEADERS");
            economyStatsHeaders          = widget.Get <ContainerWidget>("ECONOMY_STATS_HEADERS");
            productionStatsHeaders       = widget.Get <ContainerWidget>("PRODUCTION_STATS_HEADERS");
            combatStatsHeaders           = widget.Get <ContainerWidget>("COMBAT_STATS_HEADERS");
            earnedThisMinuteGraphHeaders = widget.Get <ContainerWidget>("EARNED_THIS_MIN_GRAPH_HEADERS");

            playerStatsPanel        = widget.Get <ScrollPanelWidget>("PLAYER_STATS_PANEL");
            playerStatsPanel.Layout = new GridLayout(playerStatsPanel);

            basicPlayerTemplate           = playerStatsPanel.Get <ScrollItemWidget>("BASIC_PLAYER_TEMPLATE");
            economyPlayerTemplate         = playerStatsPanel.Get <ScrollItemWidget>("ECONOMY_PLAYER_TEMPLATE");
            productionPlayerTemplate      = playerStatsPanel.Get <ScrollItemWidget>("PRODUCTION_PLAYER_TEMPLATE");
            combatPlayerTemplate          = playerStatsPanel.Get <ScrollItemWidget>("COMBAT_PLAYER_TEMPLATE");
            earnedThisMinuteGraphTemplate = playerStatsPanel.Get <ContainerWidget>("EARNED_THIS_MIN_GRAPH_TEMPLATE");

            teamTemplate = playerStatsPanel.Get <ScrollItemWidget>("TEAM_TEMPLATE");

            statsDropDown             = widget.Get <DropDownButtonWidget>("STATS_DROPDOWN");
            statsDropDown.GetText     = () => "Basic";
            statsDropDown.OnMouseDown = _ =>
            {
                var options = new List <StatsDropDownOption>
                {
                    new StatsDropDownOption
                    {
                        Title      = "Basic",
                        IsSelected = () => basicStatsHeaders.Visible,
                        OnClick    = () =>
                        {
                            ClearStats();
                            statsDropDown.GetText = () => "Basic";
                            DisplayStats(BasicStats);
                        }
                    },
                    new StatsDropDownOption
                    {
                        Title      = "Economy",
                        IsSelected = () => economyStatsHeaders.Visible,
                        OnClick    = () =>
                        {
                            ClearStats();
                            statsDropDown.GetText = () => "Economy";
                            DisplayStats(EconomyStats);
                        }
                    },
                    new StatsDropDownOption
                    {
                        Title      = "Production",
                        IsSelected = () => productionStatsHeaders.Visible,
                        OnClick    = () =>
                        {
                            ClearStats();
                            statsDropDown.GetText = () => "Production";
                            DisplayStats(ProductionStats);
                        }
                    },
                    new StatsDropDownOption
                    {
                        Title      = "Combat",
                        IsSelected = () => combatStatsHeaders.Visible,
                        OnClick    = () =>
                        {
                            ClearStats();
                            statsDropDown.GetText = () => "Combat";
                            DisplayStats(CombatStats);
                        }
                    },
                    new StatsDropDownOption
                    {
                        Title      = "Earnings (graph)",
                        IsSelected = () => earnedThisMinuteGraphHeaders.Visible,
                        OnClick    = () =>
                        {
                            ClearStats();
                            statsDropDown.GetText = () => "Earnings (graph)";
                            EarnedThisMinuteGraph();
                        }
                    }
                };
                Func <StatsDropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                {
                    var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                    item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                    return(item);
                };
                statsDropDown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 150, options, setupItem);
            };

            ClearStats();
            DisplayStats(BasicStats);

            var close = widget.GetOrNull <ButtonWidget>("CLOSE");

            if (close != null)
            {
                close.OnClick = () =>
                {
                    Ui.CloseWindow();
                    Ui.Root.RemoveChild(widget);
                    onExit();
                }
            }
            ;
        }

        void ClearStats()
        {
            playerStatsPanel.Children.Clear();
            basicStatsHeaders.Visible            = false;
            economyStatsHeaders.Visible          = false;
            productionStatsHeaders.Visible       = false;
            combatStatsHeaders.Visible           = false;
            earnedThisMinuteGraphHeaders.Visible = false;
        }

        void EarnedThisMinuteGraph()
        {
            earnedThisMinuteGraphHeaders.Visible = true;
            var template = earnedThisMinuteGraphTemplate.Clone();

            var graph = template.Get <LineGraphWidget>("EARNED_THIS_MIN_GRAPH");

            graph.GetSeries = () =>
                              players.Select(p => new LineGraphSeries(
                                                 p.PlayerName,
                                                 p.Color.RGB,
                                                 (p.PlayerActor.TraitOrDefault <PlayerStatistics>() ?? new PlayerStatistics(p.PlayerActor)).EarnedSamples.Select(s => (float)s)
                                                 ));

            playerStatsPanel.AddChild(template);
        }

        void DisplayStats(Func <Player, ScrollItemWidget> createItem)
        {
            var teams = players.GroupBy(p => (world.LobbyInfo.ClientWithIndex(p.ClientIndex) ?? new Session.Client()).Team).OrderBy(g => g.Key);

            foreach (var t in teams)
            {
                var team = t;
                var tt   = ScrollItemWidget.Setup(teamTemplate, () => false, () => { });
                tt.IgnoreMouseOver = true;
                tt.Get <LabelWidget>("TEAM").GetText = () => team.Key == 0 ? "No Team" : "Team " + team.Key;
                playerStatsPanel.AddChild(tt);
                foreach (var p in team)
                {
                    var player = p;
                    playerStatsPanel.AddChild(createItem(player));
                }
            }
        }

        ScrollItemWidget CombatStats(Player player)
        {
            combatStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(combatPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            var stats = player.PlayerActor.TraitOrDefault <PlayerStatistics>();

            if (stats == null)
            {
                return(template);
            }
            template.Get <LabelWidget>("CONTROL").GetText          = () => MapControl(stats.MapControl);
            template.Get <LabelWidget>("KILLS_COST").GetText       = () => "$" + stats.KillsCost;
            template.Get <LabelWidget>("DEATHS_COST").GetText      = () => "$" + stats.DeathsCost;
            template.Get <LabelWidget>("UNITS_KILLED").GetText     = () => stats.UnitsKilled.ToString();
            template.Get <LabelWidget>("UNITS_DEAD").GetText       = () => stats.UnitsDead.ToString();
            template.Get <LabelWidget>("BUILDINGS_KILLED").GetText = () => stats.BuildingsKilled.ToString();
            template.Get <LabelWidget>("BUILDINGS_DEAD").GetText   = () => stats.BuildingsDead.ToString();

            return(template);
        }

        ScrollItemWidget ProductionStats(Player player)
        {
            productionStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(productionPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            template.Get <ObserverProductionIconsWidget>("PRODUCTION_ICONS").GetPlayer      = () => player;
            template.Get <ObserverSupportPowerIconsWidget>("SUPPORT_POWER_ICONS").GetPlayer = () => player;

            return(template);
        }

        ScrollItemWidget EconomyStats(Player player)
        {
            economyStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(economyPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            var res   = player.PlayerActor.Trait <PlayerResources>();
            var stats = player.PlayerActor.TraitOrDefault <PlayerStatistics>();

            if (stats == null)
            {
                return(template);
            }

            template.Get <LabelWidget>("CASH").GetText            = () => "$" + (res.DisplayCash + res.DisplayResources);
            template.Get <LabelWidget>("EARNED_MIN").GetText      = () => AverageEarnedPerMinute(res.Earned);
            template.Get <LabelWidget>("EARNED_THIS_MIN").GetText = () => "$" + stats.EarnedThisMinute;
            template.Get <LabelWidget>("EARNED").GetText          = () => "$" + res.Earned;
            template.Get <LabelWidget>("SPENT").GetText           = () => "$" + res.Spent;

            var assets = template.Get <LabelWidget>("ASSETS");

            assets.GetText = () => "$" + world.Actors
                             .Where(a => a.Owner == player && !a.IsDead() && a.Info.Traits.WithInterface <ValuedInfo>().Any())
                             .Sum(a => a.Info.Traits.WithInterface <ValuedInfo>().First().Cost);

            var harvesters = template.Get <LabelWidget>("HARVESTERS");

            harvesters.GetText = () => world.Actors.Count(a => a.Owner == player && !a.IsDead() && a.HasTrait <Harvester>()).ToString();

            return(template);
        }

        ScrollItemWidget BasicStats(Player player)
        {
            basicStatsHeaders.Visible = true;
            var template = SetupPlayerScrollItemWidget(basicPlayerTemplate, player);

            LobbyUtils.AddPlayerFlagAndName(template, player);

            var res = player.PlayerActor.Trait <PlayerResources>();

            template.Get <LabelWidget>("CASH").GetText       = () => "$" + (res.DisplayCash + res.DisplayResources);
            template.Get <LabelWidget>("EARNED_MIN").GetText = () => AverageEarnedPerMinute(res.Earned);

            var powerRes = player.PlayerActor.Trait <PowerManager>();
            var power    = template.Get <LabelWidget>("POWER");

            power.GetText  = () => powerRes.PowerDrained + "/" + powerRes.PowerProvided;
            power.GetColor = () => GetPowerColor(powerRes.PowerState);

            var stats = player.PlayerActor.TraitOrDefault <PlayerStatistics>();

            if (stats == null)
            {
                return(template);
            }
            template.Get <LabelWidget>("KILLS").GetText       = () => (stats.UnitsKilled + stats.BuildingsKilled).ToString();
            template.Get <LabelWidget>("DEATHS").GetText      = () => (stats.UnitsDead + stats.BuildingsDead).ToString();
            template.Get <LabelWidget>("ACTIONS_MIN").GetText = () => AverageOrdersPerMinute(stats.OrderCount);

            return(template);
        }

        ScrollItemWidget SetupPlayerScrollItemWidget(ScrollItemWidget template, Player player)
        {
            return(ScrollItemWidget.Setup(template, () => false, () =>
            {
                var playerBase = world.Actors.FirstOrDefault(a => !a.IsDead() && a.HasTrait <BaseBuilding>() && a.Owner == player);
                if (playerBase != null)
                {
                    worldRenderer.Viewport.Center(playerBase.CenterPosition);
                }
            }));
        }
示例#19
0
        internal LobbyLogic(Widget widget, World world, OrderManager orderManager,
                            Action onExit, Action onStart, bool addBots)
        {
            var lobby = widget;

            this.orderManager = orderManager;
            this.OnGameStart  = () => { CloseWindow(); onStart(); };
            this.onExit       = onExit;

            Game.LobbyInfoChanged       += UpdateCurrentMap;
            Game.LobbyInfoChanged       += UpdatePlayerList;
            Game.BeforeGameStart        += OnGameStart;
            Game.AddChatLine            += AddChatLine;
            Game.ConnectionStateChanged += ConnectionStateChanged;

            var name = lobby.GetOrNull <LabelWidget>("SERVER_NAME");

            if (name != null)
            {
                name.GetText = () => orderManager.LobbyInfo.GlobalSettings.ServerName;
            }

            UpdateCurrentMap();
            Players = lobby.Get <ScrollPanelWidget>("PLAYERS");
            EditablePlayerTemplate       = Players.Get("TEMPLATE_EDITABLE_PLAYER");
            NonEditablePlayerTemplate    = Players.Get("TEMPLATE_NONEDITABLE_PLAYER");
            EmptySlotTemplate            = Players.Get("TEMPLATE_EMPTY");
            EditableSpectatorTemplate    = Players.Get("TEMPLATE_EDITABLE_SPECTATOR");
            NonEditableSpectatorTemplate = Players.Get("TEMPLATE_NONEDITABLE_SPECTATOR");
            NewSpectatorTemplate         = Players.Get("TEMPLATE_NEW_SPECTATOR");
            colorPreview       = lobby.Get <ColorPreviewManagerWidget>("COLOR_MANAGER");
            colorPreview.Color = Game.Settings.Player.Color;

            var mapPreview = lobby.Get <MapPreviewWidget>("MAP_PREVIEW");

            mapPreview.IsVisible    = () => Map != null;
            mapPreview.Map          = () => Map;
            mapPreview.OnMouseDown  = mi => LobbyUtils.SelectSpawnPoint(orderManager, mapPreview, Map, mi);
            mapPreview.SpawnClients = () => LobbyUtils.GetSpawnClients(orderManager, Map);

            var mapTitle = lobby.GetOrNull <LabelWidget>("MAP_TITLE");

            if (mapTitle != null)
            {
                mapTitle.IsVisible = () => Map != null;
                mapTitle.GetText   = () => Map.Title;
            }

            var mapType = lobby.GetOrNull <LabelWidget>("MAP_TYPE");

            if (mapType != null)
            {
                mapType.IsVisible = () => Map != null;
                mapType.GetText   = () => Map.Type;
            }

            var mapAuthor = lobby.GetOrNull <LabelWidget>("MAP_AUTHOR");

            if (mapAuthor != null)
            {
                mapAuthor.IsVisible = () => Map != null;
                mapAuthor.GetText   = () => "Created by {0}".F(Map.Author);
            }

            CountryNames = Rules.Info["world"].Traits.WithInterface <CountryInfo>()
                           .Where(c => c.Selectable)
                           .ToDictionary(a => a.Race, a => a.Name);
            CountryNames.Add("random", "Any");

            var gameStarting = false;

            var mapButton = lobby.Get <ButtonWidget>("CHANGEMAP_BUTTON");

            mapButton.OnClick = () =>
            {
                var onSelect = new Action <Map>(m =>
                {
                    orderManager.IssueOrder(Order.Command("map " + m.Uid));
                    Game.Settings.Server.Map = m.Uid;
                    Game.Settings.Save();
                });

                Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", Map.Uid },
                    { "onExit", () => {} },
                    { "onSelect", onSelect }
                });
            };
            mapButton.IsVisible = () => mapButton.Visible && Game.IsHost;

            var assignTeams = lobby.GetOrNull <DropDownButtonWidget>("ASSIGNTEAMS_DROPDOWNBUTTON");

            if (assignTeams != null)
            {
                assignTeams.IsVisible  = () => Game.IsHost;
                assignTeams.IsDisabled = () => gameStarting || orderManager.LobbyInfo.Clients.Count(c => c.Slot != null) < 2 ||
                                         orderManager.LocalClient == null || orderManager.LocalClient.IsReady;

                assignTeams.OnMouseDown = _ =>
                {
                    var options = Enumerable.Range(2, orderManager.LobbyInfo.Clients.Count(c => c.Slot != null).Clamp(2, 8) - 1).Select(d => new DropDownOption
                    {
                        Title      = "{0} Teams".F(d),
                        IsSelected = () => false,
                        OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams {0}".F(d.ToString())))
                    });
                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };
                    assignTeams.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem);
                };
            }

            var disconnectButton = lobby.Get <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = () => { CloseWindow(); onExit(); };

            var allowCheats = lobby.Get <CheckboxWidget>("ALLOWCHEATS_CHECKBOX");

            allowCheats.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats;
            allowCheats.IsDisabled = () => !Game.IsHost || gameStarting || orderManager.LocalClient == null ||
                                     orderManager.LocalClient.IsReady;
            allowCheats.OnClick = () => orderManager.IssueOrder(Order.Command(
                                                                    "allowcheats {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowCheats)));

            var crates = lobby.GetOrNull <CheckboxWidget>("CRATES_CHECKBOX");

            if (crates != null)
            {
                crates.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.Crates;
                crates.IsDisabled = () => !Game.IsHost || gameStarting || orderManager.LocalClient == null ||
                                    orderManager.LocalClient.IsReady;        // maybe disable the checkbox if a map forcefully removes CrateDrop?
                crates.OnClick = () => orderManager.IssueOrder(Order.Command(
                                                                   "crates {0}".F(!orderManager.LobbyInfo.GlobalSettings.Crates)));
            }

            var fragileAlliance = lobby.GetOrNull <CheckboxWidget>("FRAGILEALLIANCES_CHECKBOX");

            if (fragileAlliance != null)
            {
                fragileAlliance.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.FragileAlliances;
                fragileAlliance.IsDisabled = () => !Game.IsHost || gameStarting ||
                                             orderManager.LocalClient == null || orderManager.LocalClient.IsReady;
                fragileAlliance.OnClick = () => orderManager.IssueOrder(Order.Command(
                                                                            "fragilealliance {0}".F(!orderManager.LobbyInfo.GlobalSettings.FragileAlliances)));
            }
            ;


            var difficulty = lobby.GetOrNull <DropDownButtonWidget>("DIFFICULTY_DROPDOWNBUTTON");

            if (difficulty != null)
            {
                difficulty.IsVisible   = () => Map != null && Map.Difficulties != null && Map.Difficulties.Any();
                difficulty.IsDisabled  = () => !Game.IsHost || gameStarting || orderManager.LocalClient == null || orderManager.LocalClient.IsReady;
                difficulty.GetText     = () => orderManager.LobbyInfo.GlobalSettings.Difficulty;
                difficulty.OnMouseDown = _ =>
                {
                    var options = Map.Difficulties.Select(d => new DropDownOption
                    {
                        Title      = d,
                        IsSelected = () => orderManager.LobbyInfo.GlobalSettings.Difficulty == d,
                        OnClick    = () => orderManager.IssueOrder(Order.Command("difficulty {0}".F(d)))
                    });
                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };
                    difficulty.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem);
                };
            }

            var startGameButton = lobby.Get <ButtonWidget>("START_GAME_BUTTON");

            startGameButton.IsVisible  = () => Game.IsHost;
            startGameButton.IsDisabled = () => gameStarting ||
                                         orderManager.LobbyInfo.Slots.Any(sl => sl.Value.Required && orderManager.LobbyInfo.ClientInSlot(sl.Key) == null);
            startGameButton.OnClick = () =>
            {
                gameStarting = true;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            bool teamChat      = false;
            var  chatLabel     = lobby.Get <LabelWidget>("LABEL_CHATTYPE");
            var  chatTextField = lobby.Get <TextFieldWidget>("CHAT_TEXTFIELD");

            chatTextField.OnEnterKey = () =>
            {
                if (chatTextField.Text.Length == 0)
                {
                    return(true);
                }

                orderManager.IssueOrder(Order.Chat(teamChat, chatTextField.Text));
                chatTextField.Text = "";
                return(true);
            };

            chatTextField.OnTabKey = () =>
            {
                teamChat      ^= true;
                chatLabel.Text = (teamChat) ? "Team:" : "Chat:";
                return(true);
            };

            chatPanel    = lobby.Get <ScrollPanelWidget>("CHAT_DISPLAY");
            chatTemplate = chatPanel.Get("CHAT_TEMPLATE");
            chatPanel.RemoveChildren();

            var musicButton = lobby.GetOrNull <ButtonWidget>("MUSIC_BUTTON");

            if (musicButton != null)
            {
                musicButton.OnClick = () => Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => {} }
                });
            }

            // Add a bot on the first lobbyinfo update
            if (addBots)
            {
                Game.LobbyInfoChanged += WidgetUtils.Once(() =>
                {
                    var slot          = orderManager.LobbyInfo.FirstEmptySlot();
                    var bot           = Rules.Info["player"].Traits.WithInterface <IBotInfo>().Select(t => t.Name).FirstOrDefault();
                    var botController = orderManager.LobbyInfo.Clients.Where(c => c.IsAdmin).FirstOrDefault();
                    if (slot != null && bot != null)
                    {
                        orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot, botController.Index, bot)));
                    }
                });
            }
        }
示例#20
0
        public ClientTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, OrderManager orderManager, int clientIndex)
        {
            var admin     = widget.Get <LabelWidget>("ADMIN");
            var adminFont = Game.Renderer.Fonts[admin.Font];

            var latency     = widget.Get <LabelWidget>("LATENCY");
            var latencyFont = Game.Renderer.Fonts[latency.Font];

            var latencyPrefix     = widget.Get <LabelWidget>("LATENCY_PREFIX");
            var latencyPrefixFont = Game.Renderer.Fonts[latencyPrefix.Font];

            var ip     = widget.Get <LabelWidget>("IP");
            var ipFont = Game.Renderer.Fonts[ip.Font];

            var location     = widget.Get <LabelWidget>("LOCATION");
            var locationFont = Game.Renderer.Fonts[location.Font];

            var locationOffset = location.Bounds.Y;
            var ipOffset       = ip.Bounds.Y;
            var latencyOffset  = latency.Bounds.Y;
            var tooltipHeight  = widget.Bounds.Height;

            var margin = widget.Bounds.Width;

            tooltipContainer.IsVisible    = () => (orderManager.LobbyInfo.ClientWithIndex(clientIndex) != null);
            tooltipContainer.BeforeRender = () =>
            {
                var latencyPrefixSize = latencyPrefix.Bounds.X + latencyPrefixFont.Measure(latencyPrefix.GetText() + " ").X;
                var width             = Math.Max(locationFont.Measure(location.GetText()).X, (Math.Max(adminFont.Measure(admin.GetText()).X,
                                                                                                       Math.Max(ipFont.Measure(ip.GetText()).X, latencyPrefixSize + latencyFont.Measure(latency.GetText()).X))));
                widget.Bounds.Width   = width + 2 * margin;
                latency.Bounds.Width  = widget.Bounds.Width;
                ip.Bounds.Width       = widget.Bounds.Width;
                admin.Bounds.Width    = widget.Bounds.Width;
                location.Bounds.Width = widget.Bounds.Width;

                ip.Bounds.Y          = ipOffset;
                latency.Bounds.Y     = latencyOffset;
                location.Bounds.Y    = locationOffset;
                widget.Bounds.Height = tooltipHeight;

                if (admin.IsVisible())
                {
                    ip.Bounds.Y          += admin.Bounds.Height;
                    latency.Bounds.Y     += admin.Bounds.Height;
                    location.Bounds.Y    += admin.Bounds.Height;
                    widget.Bounds.Height += admin.Bounds.Height;
                }

                latencyPrefix.Bounds.Y = latency.Bounds.Y;
                latency.Bounds.X       = latencyPrefixSize;
            };

            admin.IsVisible  = () => orderManager.LobbyInfo.ClientWithIndex(clientIndex).IsAdmin;
            latency.GetText  = () => LobbyUtils.LatencyDescription(orderManager.LobbyInfo.ClientWithIndex(clientIndex).Latency);
            latency.GetColor = () => LobbyUtils.LatencyColor(orderManager.LobbyInfo.ClientWithIndex(clientIndex).Latency);
            var ipAddress = orderManager.LobbyInfo.ClientWithIndex(clientIndex).IpAddress;

            if ((ipAddress == null || ipAddress == "127.0.0.1") && UPnP.NatDevice != null)
            {
                ipAddress = UPnP.NatDevice.GetExternalIP().ToString();
            }
            var cachedDescriptiveIP = LobbyUtils.DescriptiveIpAddress(ipAddress);

            ip.GetText = () => cachedDescriptiveIP;
            var cachedCountryLookup = LobbyUtils.LookupCountry(ipAddress);

            location.GetText = () => cachedCountryLookup;
        }
示例#21
0
        internal LobbyLogic(Widget widget, World world, OrderManager orderManager,
                            Action onExit, Action onStart, bool addBots)
        {
            lobby             = widget;
            this.orderManager = orderManager;
            this.OnGameStart  = () => { CloseWindow(); onStart(); };
            this.onExit       = onExit;

            Game.LobbyInfoChanged       += UpdateCurrentMap;
            Game.LobbyInfoChanged       += UpdatePlayerList;
            Game.BeforeGameStart        += OnGameStart;
            Game.AddChatLine            += AddChatLine;
            Game.ConnectionStateChanged += ConnectionStateChanged;

            var name = lobby.GetOrNull <LabelWidget>("SERVER_NAME");

            if (name != null)
            {
                name.GetText = () => orderManager.LobbyInfo.GlobalSettings.ServerName;
            }

            UpdateCurrentMap();
            Players           = Ui.LoadWidget <ScrollPanelWidget>("LOBBY_PLAYER_BIN", lobby.Get("PLAYER_BIN_ROOT"), new WidgetArgs());
            Players.IsVisible = () => panel == PanelType.Players;

            EditablePlayerTemplate       = Players.Get("TEMPLATE_EDITABLE_PLAYER");
            NonEditablePlayerTemplate    = Players.Get("TEMPLATE_NONEDITABLE_PLAYER");
            EmptySlotTemplate            = Players.Get("TEMPLATE_EMPTY");
            EditableSpectatorTemplate    = Players.Get("TEMPLATE_EDITABLE_SPECTATOR");
            NonEditableSpectatorTemplate = Players.Get("TEMPLATE_NONEDITABLE_SPECTATOR");
            NewSpectatorTemplate         = Players.Get("TEMPLATE_NEW_SPECTATOR");
            colorPreview       = lobby.Get <ColorPreviewManagerWidget>("COLOR_MANAGER");
            colorPreview.Color = Game.Settings.Player.Color;

            var mapPreview = lobby.Get <MapPreviewWidget>("MAP_PREVIEW");

            mapPreview.IsVisible    = () => Map != null;
            mapPreview.Map          = () => Map;
            mapPreview.OnMouseDown  = mi => LobbyUtils.SelectSpawnPoint(orderManager, mapPreview, Map, mi);
            mapPreview.SpawnClients = () => LobbyUtils.GetSpawnClients(orderManager, Map);

            var mapTitle = lobby.GetOrNull <LabelWidget>("MAP_TITLE");

            if (mapTitle != null)
            {
                mapTitle.IsVisible = () => Map != null;
                mapTitle.GetText   = () => Map.Title;
            }

            var mapType = lobby.GetOrNull <LabelWidget>("MAP_TYPE");

            if (mapType != null)
            {
                mapType.IsVisible = () => Map != null;
                mapType.GetText   = () => Map.Type;
            }

            var mapAuthor = lobby.GetOrNull <LabelWidget>("MAP_AUTHOR");

            if (mapAuthor != null)
            {
                mapAuthor.IsVisible = () => Map != null;
                mapAuthor.GetText   = () => "Created by {0}".F(Map.Author);
            }

            CountryNames = Rules.Info["world"].Traits.WithInterface <CountryInfo>()
                           .Where(c => c.Selectable)
                           .ToDictionary(a => a.Race, a => a.Name);
            CountryNames.Add("random", "Any");

            var         gameStarting          = false;
            Func <bool> configurationDisabled = () => !Game.IsHost || gameStarting || panel == PanelType.Kick ||
                                                orderManager.LocalClient == null || orderManager.LocalClient.IsReady;

            var mapButton = lobby.GetOrNull <ButtonWidget>("CHANGEMAP_BUTTON");

            if (mapButton != null)
            {
                mapButton.IsDisabled = configurationDisabled;
                mapButton.OnClick    = () =>
                {
                    var onSelect = new Action <Map>(m =>
                    {
                        orderManager.IssueOrder(Order.Command("map " + m.Uid));
                        Game.Settings.Server.Map = m.Uid;
                        Game.Settings.Save();
                    });

                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", Map.Uid },
                        { "onExit", () => {} },
                        { "onSelect", onSelect }
                    });
                };
            }

            var slotsButton = lobby.GetOrNull <DropDownButtonWidget>("SLOTS_DROPDOWNBUTTON");

            if (slotsButton != null)
            {
                slotsButton.IsDisabled = () => configurationDisabled() || panel != PanelType.Players ||
                                         !orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots || !s.LockTeam);

                var aiModes = Rules.Info["player"].Traits.WithInterface <IBotInfo>().Select(t => t.Name);
                slotsButton.OnMouseDown = _ =>
                {
                    var options = new Dictionary <string, IEnumerable <DropDownOption> >();

                    var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin);
                    if (orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots))
                    {
                        var botOptions = new List <DropDownOption>()
                        {
                            new DropDownOption()
                            {
                                Title      = "Add",
                                IsSelected = () => false,
                                OnClick    = () =>
                                {
                                    foreach (var slot in orderManager.LobbyInfo.Slots)
                                    {
                                        var bot = aiModes.Random(Game.CosmeticRandom);
                                        var c   = orderManager.LobbyInfo.ClientInSlot(slot.Key);
                                        if (slot.Value.AllowBots == true && (c == null || c.Bot != null))
                                        {
                                            orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot.Key, botController.Index, bot)));
                                        }
                                    }
                                }
                            }
                        };

                        if (orderManager.LobbyInfo.Clients.Any(c => c.Bot != null))
                        {
                            botOptions.Add(new DropDownOption()
                            {
                                Title      = "Remove",
                                IsSelected = () => false,
                                OnClick    = () =>
                                {
                                    foreach (var slot in orderManager.LobbyInfo.Slots)
                                    {
                                        var c = orderManager.LobbyInfo.ClientInSlot(slot.Key);
                                        if (c != null && c.Bot != null)
                                        {
                                            orderManager.IssueOrder(Order.Command("slot_open " + slot.Value.PlayerReference));
                                        }
                                    }
                                }
                            });
                        }

                        options.Add("Configure Bots", botOptions);
                    }

                    var teamCount = (orderManager.LobbyInfo.Slots.Count(s => !s.Value.LockTeam && orderManager.LobbyInfo.ClientInSlot(s.Key) != null) + 1) / 2;
                    if (teamCount >= 1)
                    {
                        var teamOptions = Enumerable.Range(2, teamCount - 1).Reverse().Select(d => new DropDownOption
                        {
                            Title      = "{0} Teams".F(d),
                            IsSelected = () => false,
                            OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams {0}".F(d.ToString())))
                        }).ToList();

                        if (orderManager.LobbyInfo.Slots.Any(s => s.Value.AllowBots))
                        {
                            teamOptions.Add(new DropDownOption
                            {
                                Title      = "Humans vs Bots",
                                IsSelected = () => false,
                                OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams 1"))
                            });
                        }

                        teamOptions.Add(new DropDownOption
                        {
                            Title      = "Free for all",
                            IsSelected = () => false,
                            OnClick    = () => orderManager.IssueOrder(Order.Command("assignteams 0"))
                        });

                        options.Add("Configure Teams", teamOptions);
                    }

                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };
                    slotsButton.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 175, options, setupItem);
                };
            }

            var optionsBin = Ui.LoadWidget("LOBBY_OPTIONS_BIN", lobby, new WidgetArgs());

            optionsBin.IsVisible = () => panel == PanelType.Options;

            var optionsButton = lobby.Get <ButtonWidget>("OPTIONS_BUTTON");

            optionsButton.IsDisabled = () => panel == PanelType.Kick;
            optionsButton.GetText    = () => panel == PanelType.Options ? "Players" : "Options";
            optionsButton.OnClick    = () => panel = (panel == PanelType.Options) ? PanelType.Players : PanelType.Options;

            var startGameButton = lobby.GetOrNull <ButtonWidget>("START_GAME_BUTTON");

            if (startGameButton != null)
            {
                startGameButton.IsDisabled = () => configurationDisabled() ||
                                             orderManager.LobbyInfo.Slots.Any(sl => sl.Value.Required && orderManager.LobbyInfo.ClientInSlot(sl.Key) == null);
                startGameButton.OnClick = () =>
                {
                    gameStarting = true;
                    orderManager.IssueOrder(Order.Command("startgame"));
                };
            }

            // Options panel
            var allowCheats = optionsBin.GetOrNull <CheckboxWidget>("ALLOWCHEATS_CHECKBOX");

            if (allowCheats != null)
            {
                allowCheats.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats;
                allowCheats.IsDisabled = () => Map.Options.Cheats.HasValue || configurationDisabled();
                allowCheats.OnClick    = () => orderManager.IssueOrder(Order.Command(
                                                                           "allowcheats {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowCheats)));
            }

            var crates = optionsBin.GetOrNull <CheckboxWidget>("CRATES_CHECKBOX");

            if (crates != null)
            {
                crates.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.Crates;
                crates.IsDisabled = () => Map.Options.Crates.HasValue || configurationDisabled();
                crates.OnClick    = () => orderManager.IssueOrder(Order.Command(
                                                                      "crates {0}".F(!orderManager.LobbyInfo.GlobalSettings.Crates)));
            }

            var allybuildradius = optionsBin.GetOrNull <CheckboxWidget>("ALLYBUILDRADIUS_CHECKBOX");

            if (allybuildradius != null)
            {
                allybuildradius.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.AllyBuildRadius;
                allybuildradius.IsDisabled = () => Map.Options.AllyBuildRadius.HasValue || configurationDisabled();
                allybuildradius.OnClick    = () => orderManager.IssueOrder(Order.Command(
                                                                               "allybuildradius {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllyBuildRadius)));
            }

            var fragileAlliance = optionsBin.GetOrNull <CheckboxWidget>("FRAGILEALLIANCES_CHECKBOX");

            if (fragileAlliance != null)
            {
                fragileAlliance.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.FragileAlliances;
                fragileAlliance.IsDisabled = () => Map.Options.FragileAlliances.HasValue || configurationDisabled();
                fragileAlliance.OnClick    = () => orderManager.IssueOrder(Order.Command(
                                                                               "fragilealliance {0}".F(!orderManager.LobbyInfo.GlobalSettings.FragileAlliances)));
            }

            var difficulty = optionsBin.GetOrNull <DropDownButtonWidget>("DIFFICULTY_DROPDOWNBUTTON");

            if (difficulty != null)
            {
                difficulty.IsVisible   = () => Map.Options.Difficulties.Any();
                difficulty.IsDisabled  = configurationDisabled;
                difficulty.GetText     = () => orderManager.LobbyInfo.GlobalSettings.Difficulty;
                difficulty.OnMouseDown = _ =>
                {
                    var options = Map.Options.Difficulties.Select(d => new DropDownOption
                    {
                        Title      = d,
                        IsSelected = () => orderManager.LobbyInfo.GlobalSettings.Difficulty == d,
                        OnClick    = () => orderManager.IssueOrder(Order.Command("difficulty {0}".F(d)))
                    });
                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };
                    difficulty.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem);
                };

                optionsBin.Get <LabelWidget>("DIFFICULTY_DESC").IsVisible = difficulty.IsVisible;
            }

            var startingUnits = optionsBin.GetOrNull <DropDownButtonWidget>("STARTINGUNITS_DROPDOWNBUTTON");

            if (startingUnits != null)
            {
                var classNames = new Dictionary <string, string>()
                {
                    { "none", "MCV Only" },
                    { "light", "Light Support" },
                    { "heavy", "Heavy Support" },
                };

                Func <string, string> className = c => classNames.ContainsKey(c) ? classNames[c] : c;
                var classes = Rules.Info["world"].Traits.WithInterface <MPStartUnitsInfo>()
                              .Select(a => a.Class).Distinct();

                startingUnits.IsDisabled  = () => !Map.Options.ConfigurableStartingUnits || configurationDisabled();
                startingUnits.GetText     = () => !Map.Options.ConfigurableStartingUnits ? "Not Available" : className(orderManager.LobbyInfo.GlobalSettings.StartingUnitsClass);
                startingUnits.OnMouseDown = _ =>
                {
                    var options = classes.Select(c => new DropDownOption
                    {
                        Title      = className(c),
                        IsSelected = () => orderManager.LobbyInfo.GlobalSettings.StartingUnitsClass == c,
                        OnClick    = () => orderManager.IssueOrder(Order.Command("startingunits {0}".F(c)))
                    });

                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };

                    startingUnits.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem);
                };

                optionsBin.Get <LabelWidget>("STARTINGUNITS_DESC").IsVisible = startingUnits.IsVisible;
            }

            var startingCash = optionsBin.GetOrNull <DropDownButtonWidget>("STARTINGCASH_DROPDOWNBUTTON");

            if (startingCash != null)
            {
                startingCash.IsDisabled  = () => Map.Options.StartingCash.HasValue || configurationDisabled();
                startingCash.GetText     = () => Map.Options.StartingCash.HasValue ? "Not Available" : "${0}".F(orderManager.LobbyInfo.GlobalSettings.StartingCash);
                startingCash.OnMouseDown = _ =>
                {
                    var options = Rules.Info["player"].Traits.Get <PlayerResourcesInfo>().SelectableCash.Select(c => new DropDownOption
                    {
                        Title      = "${0}".F(c),
                        IsSelected = () => orderManager.LobbyInfo.GlobalSettings.StartingCash == c,
                        OnClick    = () => orderManager.IssueOrder(Order.Command("startingcash {0}".F(c)))
                    });

                    Func <DropDownOption, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
                    {
                        var item = ScrollItemWidget.Setup(template, option.IsSelected, option.OnClick);
                        item.Get <LabelWidget>("LABEL").GetText = () => option.Title;
                        return(item);
                    };

                    startingCash.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", options.Count() * 30, options, setupItem);
                };
            }

            var enableShroud = optionsBin.GetOrNull <CheckboxWidget>("SHROUD_CHECKBOX");

            if (enableShroud != null)
            {
                enableShroud.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.Shroud;
                enableShroud.IsDisabled = () => Map.Options.Shroud.HasValue || configurationDisabled();
                enableShroud.OnClick    = () => orderManager.IssueOrder(Order.Command(
                                                                            "shroud {0}".F(!orderManager.LobbyInfo.GlobalSettings.Shroud)));
            }

            var enableFog = optionsBin.GetOrNull <CheckboxWidget>("FOG_CHECKBOX");

            if (enableFog != null)
            {
                enableFog.IsChecked  = () => orderManager.LobbyInfo.GlobalSettings.Fog;
                enableFog.IsDisabled = () => Map.Options.Fog.HasValue || configurationDisabled();
                enableFog.OnClick    = () => orderManager.IssueOrder(Order.Command(
                                                                         "fog {0}".F(!orderManager.LobbyInfo.GlobalSettings.Fog)));
            }

            var disconnectButton = lobby.Get <ButtonWidget>("DISCONNECT_BUTTON");

            disconnectButton.OnClick = () => { CloseWindow(); onExit(); };

            bool teamChat      = false;
            var  chatLabel     = lobby.Get <LabelWidget>("LABEL_CHATTYPE");
            var  chatTextField = lobby.Get <TextFieldWidget>("CHAT_TEXTFIELD");

            chatTextField.OnEnterKey = () =>
            {
                if (chatTextField.Text.Length == 0)
                {
                    return(true);
                }

                orderManager.IssueOrder(Order.Chat(teamChat, chatTextField.Text));
                chatTextField.Text = "";
                return(true);
            };

            chatTextField.OnTabKey = () =>
            {
                teamChat      ^= true;
                chatLabel.Text = (teamChat) ? "Team:" : "Chat:";
                return(true);
            };

            chatPanel    = lobby.Get <ScrollPanelWidget>("CHAT_DISPLAY");
            chatTemplate = chatPanel.Get("CHAT_TEMPLATE");
            chatPanel.RemoveChildren();

            var musicButton = lobby.GetOrNull <ButtonWidget>("MUSIC_BUTTON");

            if (musicButton != null)
            {
                musicButton.OnClick = () => Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => {} }
                });
            }

            // Add a bot on the first lobbyinfo update
            if (addBots)
            {
                Game.LobbyInfoChanged += WidgetUtils.Once(() =>
                {
                    var slot          = orderManager.LobbyInfo.FirstEmptySlot();
                    var bot           = Rules.Info["player"].Traits.WithInterface <IBotInfo>().Select(t => t.Name).FirstOrDefault();
                    var botController = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.IsAdmin);
                    if (slot != null && bot != null)
                    {
                        orderManager.IssueOrder(Order.Command("slot_bot {0} {1} {2}".F(slot, botController.Index, bot)));
                    }
                });
            }
        }
示例#22
0
        public DiplomacyLogic(Widget widget, Action onExit, World world)
        {
            this.world = world;

            diplomacyPanel = widget.Get <ScrollPanelWidget>("DIPLOMACY_PANEL");

            LayoutPlayers();

            var close = widget.GetOrNull <ButtonWidget>("CLOSE");

            if (close != null)
            {
                close.OnClick = () =>
                {
                    Ui.CloseWindow();
                    Ui.Root.RemoveChild(widget);
                    onExit();
                }
            }
            ;
        }

        void LayoutPlayers()
        {
            var teamTemplate = diplomacyPanel.Get <ScrollItemWidget>("TEAM_TEMPLATE");
            var players      = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant);
            var teams        = players.GroupBy(p => (world.LobbyInfo.ClientWithIndex(p.ClientIndex) ?? new Session.Client()).Team).OrderBy(g => g.Key);

            foreach (var t in teams)
            {
                var team = t;
                var tt   = ScrollItemWidget.Setup(teamTemplate, () => false, () => { });
                tt.IgnoreMouseOver = true;
                tt.Get <LabelWidget>("TEAM").GetText = () => team.Key == 0 ? "No Team" : "Team " + team.Key;
                diplomacyPanel.AddChild(tt);
                foreach (var p in team)
                {
                    var player = p;
                    diplomacyPanel.AddChild(DiplomaticStatus(player));
                }
            }
        }

        ScrollItemWidget DiplomaticStatus(Player player)
        {
            var playerTemplate = diplomacyPanel.Get <ScrollItemWidget>("PLAYER_TEMPLATE");
            var pt             = ScrollItemWidget.Setup(playerTemplate, () => false, () => { });

            pt.IgnoreMouseOver = true;
            LobbyUtils.AddPlayerFlagAndName(pt, player);
            pt.Get <LabelWidget>("THEIR_STANCE").GetText = () => player.Stances[world.LocalPlayer].ToString();
            var myStance = pt.Get <DropDownButtonWidget>("MY_STANCE");

            myStance.GetText     = () => world.LocalPlayer.Stances[player].ToString();
            myStance.IsDisabled  = () => !world.LobbyInfo.GlobalSettings.FragileAlliances;
            myStance.OnMouseDown = mi => ShowDropDown(player, myStance);
            return(pt);
        }

        void ShowDropDown(Player p, DropDownButtonWidget dropdown)
        {
            var stances = Enum <Stance> .GetValues();

            Func <Stance, ScrollItemWidget, ScrollItemWidget> setupItem = (s, template) =>
            {
                var item = ScrollItemWidget.Setup(template,
                                                  () => s == world.LocalPlayer.Stances[p],
                                                  () => SetStance(dropdown, p, s));

                item.Get <LabelWidget>("LABEL").GetText = () => s.ToString();
                return(item);
            };

            dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 150, stances, setupItem);
        }

        void SetStance(ButtonWidget bw, Player p, Stance ss)
        {
            if (!p.World.LobbyInfo.GlobalSettings.FragileAlliances)
            {
                return;                 // stance changes are banned
            }
            world.IssueOrder(new Order("SetStance", world.LocalPlayer.PlayerActor, false)
            {
                ExtraData    = (uint)ss,
                TargetString = p.InternalName,
            });

            bw.Text = ss.ToString();
        }
    }