Beispiel #1
0
		public TileSelectorLogic(Widget widget, WorldRenderer worldRenderer, Ruleset modRules)
		{
			var tileset = modRules.TileSets[worldRenderer.World.Map.Tileset];

			editor = widget.Parent.Get<EditorViewportControllerWidget>("MAP_EDITOR");
			panel = widget.Get<ScrollPanelWidget>("TILETEMPLATE_LIST");
			itemTemplate = panel.Get<ScrollItemWidget>("TILEPREVIEW_TEMPLATE");
			panel.Layout = new GridLayout(panel);

			var tileCategorySelector = widget.Get<DropDownButtonWidget>("TILE_CATEGORY");
			var categories = tileset.EditorTemplateOrder;
			Func<string, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
			{
				var item = ScrollItemWidget.Setup(template,
					() => tileCategorySelector.Text == option,
					() => { tileCategorySelector.Text = option; IntializeTilePreview(widget, worldRenderer, tileset, option); });

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

			tileCategorySelector.OnClick = () =>
				tileCategorySelector.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 270, categories, setupItem);

			tileCategorySelector.Text = categories.First();
			IntializeTilePreview(widget, worldRenderer, tileset, categories.First());
		}
Beispiel #2
0
        public DiplomacyLogic(Widget widget, Action onExit, World world)
        {
            this.world = world;

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

            LayoutPlayers();
        }
 void AddReplay(ScrollPanelWidget list, string filename, ScrollItemWidget template)
 {
     var item = ScrollItemWidget.Setup(template,
         () => currentReplay != null && currentReplay.Filename == filename,
         () => SelectReplay(filename));
     var f = Path.GetFileName(filename);
     item.Get<LabelWidget>("TITLE").GetText = () => f;
     list.AddChild(item);
 }
Beispiel #4
0
        public ModContentLogic(Widget widget, Manifest mod, ModContent content, Action onCancel)
        {
            this.content = content;

            var panel = widget.Get("CONTENT_PANEL");

            var modFileSystem = new FileSystem.FileSystem(Game.Mods);
            modFileSystem.LoadFromManifest(mod);

            var sourceYaml = MiniYaml.Load(modFileSystem, content.Sources, null);
            foreach (var s in sourceYaml)
                sources.Add(s.Key, new ModContent.ModSource(s.Value));

            var downloadYaml = MiniYaml.Load(modFileSystem, content.Downloads, null);
            foreach (var d in downloadYaml)
                downloads.Add(d.Key, new ModContent.ModDownload(d.Value));

            modFileSystem.UnmountAll();

            scrollPanel = panel.Get<ScrollPanelWidget>("PACKAGES");
            template = scrollPanel.Get<ContainerWidget>("PACKAGE_TEMPLATE");

            var headerTemplate = panel.Get<LabelWidget>("HEADER_TEMPLATE");
            var headerLines = !string.IsNullOrEmpty(content.HeaderMessage) ? content.HeaderMessage.Replace("\\n", "\n").Split('\n') : new string[0];
            var headerHeight = 0;
            foreach (var l in headerLines)
            {
                var line = (LabelWidget)headerTemplate.Clone();
                line.GetText = () => l;
                line.Bounds.Y += headerHeight;
                panel.AddChild(line);

                headerHeight += headerTemplate.Bounds.Height;
            }

            panel.Bounds.Height += headerHeight;
            panel.Bounds.Y -= headerHeight / 2;
            scrollPanel.Bounds.Y += headerHeight;

            var discButton = panel.Get<ButtonWidget>("CHECK_DISC_BUTTON");
            discButton.Bounds.Y += headerHeight;
            discButton.IsVisible = () => discAvailable;

            discButton.OnClick = () => Ui.OpenWindow("DISC_INSTALL_PANEL", new WidgetArgs
            {
                { "afterInstall", () => { } },
                { "sources", sources },
                { "content", content }
            });

            var backButton = panel.Get<ButtonWidget>("BACK_BUTTON");
            backButton.Bounds.Y += headerHeight;
            backButton.OnClick = () => { Ui.CloseWindow(); onCancel(); };

            PopulateContentList();
            Game.RunAfterTick(Ui.ResetTooltips);
        }
Beispiel #5
0
        internal MapChooserLogic(Widget widget, string initialMap, Action onExit, Action<Map> onSelect)
        {
            map = Game.modData.AvailableMaps[WidgetUtils.ChooseInitialMap(initialMap)];

            widget.Get<ButtonWidget>("BUTTON_OK").OnClick = () => { Ui.CloseWindow(); onSelect(map); };
            widget.Get<ButtonWidget>("BUTTON_CANCEL").OnClick = () => { Ui.CloseWindow(); onExit(); };

            scrollpanel = widget.Get<ScrollPanelWidget>("MAP_LIST");
            scrollpanel.ScrollVelocity = 40f;
            scrollpanel.Layout = new GridLayout(scrollpanel);

            itemTemplate = scrollpanel.Get<ScrollItemWidget>("MAP_TEMPLATE");

            var gameModeDropdown = widget.GetOrNull<DropDownButtonWidget>("GAMEMODE_FILTER");
            if (gameModeDropdown != null)
            {
                var selectableMaps = Game.modData.AvailableMaps.Where(m => m.Value.Selectable).ToList();
                var gameModes = selectableMaps
                    .GroupBy(m => m.Value.Type)
                    .Select(g => Pair.New(g.Key, g.Count())).ToList();

                // 'all game types' extra item
                gameModes.Insert(0, Pair.New(null as string, selectableMaps.Count()));

                Func<Pair<string, int>, string> showItem =
                    x => "{0} ({1})".F(x.First ?? "All Game Types", x.Second);

                Func<Pair<string, int>, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, template) =>
                {
                    var item = ScrollItemWidget.Setup(template,
                        () => gameMode == ii.First,
                        () => { gameMode = ii.First; EnumerateMaps(onSelect); });
                    item.Get<LabelWidget>("LABEL").GetText = () => showItem(ii);
                    return item;
                };

                gameModeDropdown.OnClick = () =>
                    gameModeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, gameModes, setupItem);

                gameModeDropdown.GetText = () => showItem(gameModes.First(m => m.First == gameMode));
            }

            var randomMapButton = widget.GetOrNull<ButtonWidget>("RANDOMMAP_BUTTON");
            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var kv = visibleMaps.Random(Game.CosmeticRandom);
                    map = kv.Value;
                    scrollpanel.ScrollToItem(kv.Key);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Count == 0;
            }

            EnumerateMaps(onSelect);
        }
Beispiel #6
0
        public ReplayBrowserLogic(Widget widget, ModData modData, Action onExit, Action onStart)
        {
            panel = widget;

            this.modData = modData;
            this.onStart = onStart;
            Game.BeforeGameStart += OnGameStart;

            playerList = panel.Get<ScrollPanelWidget>("PLAYER_LIST");
            playerHeader = playerList.Get<ScrollItemWidget>("HEADER");
            playerTemplate = playerList.Get<ScrollItemWidget>("TEMPLATE");
            playerList.RemoveChildren();

            panel.Get<ButtonWidget>("CANCEL_BUTTON").OnClick = () => { cancelLoadingReplays = true; Ui.CloseWindow(); onExit(); };

            replayList = panel.Get<ScrollPanelWidget>("REPLAY_LIST");
            var template = panel.Get<ScrollItemWidget>("REPLAY_TEMPLATE");

            var mod = modData.Manifest;
            var dir = Platform.ResolvePath("^", "Replays", mod.Id, mod.Metadata.Version);

            if (Directory.Exists(dir))
                ThreadPool.QueueUserWorkItem(_ => LoadReplays(dir, template));

            var watch = panel.Get<ButtonWidget>("WATCH_BUTTON");
            watch.IsDisabled = () => selectedReplay == null || selectedReplay.GameInfo.MapPreview.Status != MapStatus.Available;
            watch.OnClick = () => { WatchReplay(); };

            panel.Get("REPLAY_INFO").IsVisible = () => selectedReplay != null;

            var preview = panel.Get<MapPreviewWidget>("MAP_PREVIEW");
            preview.SpawnOccupants = () => selectedSpawns;
            preview.Preview = () => selectedReplay != null ? selectedReplay.GameInfo.MapPreview : null;

            var titleLabel = panel.GetOrNull<LabelWidget>("MAP_TITLE");
            if (titleLabel != null)
            {
                titleLabel.IsVisible = () => selectedReplay != null;

                var font = Game.Renderer.Fonts[titleLabel.Font];
                var title = new CachedTransform<MapPreview, string>(m => WidgetUtils.TruncateText(m.Title, titleLabel.Bounds.Width, font));
                titleLabel.GetText = () => title.Update(selectedReplay.GameInfo.MapPreview);
            }

            var type = panel.GetOrNull<LabelWidget>("MAP_TYPE");
            if (type != null)
            {
                var mapType = new CachedTransform<MapPreview, string>(m => m.Categories.FirstOrDefault() ?? "");
                type.GetText = () => mapType.Update(selectedReplay.GameInfo.MapPreview);
            }

            panel.Get<LabelWidget>("DURATION").GetText = () => WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds);

            SetupFilters();
            SetupManagement();
        }
Beispiel #7
0
        public LayerSelectorLogic(Widget widget, WorldRenderer worldRenderer)
        {
            this.worldRenderer = worldRenderer;
            editor = widget.Parent.Get<EditorViewportControllerWidget>("MAP_EDITOR");

            layerTemplateList = widget.Get<ScrollPanelWidget>("LAYERTEMPLATE_LIST");
            layerTemplateList.Layout = new GridLayout(layerTemplateList);
            layerPreviewTemplate = layerTemplateList.Get<ScrollItemWidget>("LAYERPREVIEW_TEMPLATE");

            IntializeLayerPreview(widget);
        }
Beispiel #8
0
        public MusicPlayerLogic(Widget widget, Ruleset modRules, Action onExit)
        {
            this.modRules = modRules;

            var panel = widget.Get("MUSIC_PANEL");

            musicList = panel.Get<ScrollPanelWidget>("MUSIC_LIST");
            itemTemplate = musicList.Get<ScrollItemWidget>("MUSIC_TEMPLATE");

            BuildMusicTable();

            Func<bool> noMusic = () => !installed;
            panel.Get("NO_MUSIC_LABEL").IsVisible = noMusic;

            var playButton = panel.Get<ButtonWidget>("BUTTON_PLAY");
            playButton.OnClick = Play;
            playButton.IsDisabled = noMusic;
            playButton.IsVisible = () => !Sound.MusicPlaying;

            var pauseButton = panel.Get<ButtonWidget>("BUTTON_PAUSE");
            pauseButton.OnClick = Sound.PauseMusic;
            pauseButton.IsDisabled = noMusic;
            pauseButton.IsVisible = () => Sound.MusicPlaying;

            var stopButton = panel.Get<ButtonWidget>("BUTTON_STOP");
            stopButton.OnClick = Sound.StopMusic;
            stopButton.IsDisabled = noMusic;

            var nextButton = panel.Get<ButtonWidget>("BUTTON_NEXT");
            nextButton.OnClick = () => { currentSong = GetNextSong(); Play(); };
            nextButton.IsDisabled = noMusic;

            var prevButton = panel.Get<ButtonWidget>("BUTTON_PREV");
            prevButton.OnClick = () => { currentSong = GetPrevSong(); Play(); };
            prevButton.IsDisabled = noMusic;

            var shuffleCheckbox = panel.Get<CheckboxWidget>("SHUFFLE");
            shuffleCheckbox.IsChecked = () => Game.Settings.Sound.Shuffle;
            shuffleCheckbox.OnClick = () => Game.Settings.Sound.Shuffle ^= true;

            var repeatCheckbox = panel.Get<CheckboxWidget>("REPEAT");
            repeatCheckbox.IsChecked = () => Game.Settings.Sound.Repeat;
            repeatCheckbox.OnClick = () => Game.Settings.Sound.Repeat ^= true;

            panel.Get<LabelWidget>("TIME_LABEL").GetText = () => (currentSong == null) ? "" :
                "{0:D2}:{1:D2} / {2:D2}:{3:D2}".F((int)Sound.MusicSeekPosition / 60, (int)Sound.MusicSeekPosition % 60,
                    currentSong.Length / 60, currentSong.Length % 60);

            var musicSlider = panel.Get<SliderWidget>("MUSIC_SLIDER");
            musicSlider.OnChange += x => Sound.MusicVolume = x;
            musicSlider.Value = Sound.MusicVolume;

            panel.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => { Game.Settings.Save(); Ui.CloseWindow(); onExit(); };
        }
Beispiel #9
0
        public GlobalChatLogic(Widget widget)
        {
            historyPanel = widget.Get<ScrollPanelWidget>("HISTORY_PANEL");
            historyTemplate = historyPanel.Get<LabelWidget>("HISTORY_TEMPLATE");
            nicknamePanel = widget.Get<ScrollPanelWidget>("NICKNAME_PANEL");
            nicknameTemplate = nicknamePanel.Get("NICKNAME_TEMPLATE");

            historyPanel.Bind(Game.GlobalChat.History, MakeHistoryWidget, HistoryWidgetEquals, true);
            nicknamePanel.Bind(Game.GlobalChat.Users, MakeUserWidget, UserWidgetEquals, false);

            inputBox = widget.Get<TextFieldWidget>("CHAT_TEXTFIELD");
            inputBox.IsDisabled = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Joined;
            inputBox.OnEnterKey = EnterPressed;

            // Set a random default nick
            if (Game.Settings.Chat.Nickname == new ChatSettings().Nickname)
                Game.Settings.Chat.Nickname += Game.CosmeticRandom.Next(100, 999);

            var nicknameBox = widget.Get<TextFieldWidget>("NICKNAME_TEXTFIELD");
            nicknameBox.Text = Game.GlobalChat.SanitizedName(Game.Settings.Chat.Nickname);
            nicknameBox.OnTextEdited = () =>
            {
                nicknameBox.Text = Game.GlobalChat.SanitizedName(nicknameBox.Text);
            };

            var connectPanel = widget.Get("GLOBALCHAT_CONNECT_PANEL");
            connectPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus == ChatConnectionStatus.Disconnected;

            var disconnectButton = widget.Get<ButtonWidget>("DISCONNECT_BUTTON");
            disconnectButton.OnClick = Game.GlobalChat.Disconnect;

            var connectAutomaticallyCheckBox = connectPanel.Get<CheckboxWidget>("CONNECT_AUTOMATICALLY_CHECKBOX");
            connectAutomaticallyCheckBox.IsChecked = () => Game.Settings.Chat.ConnectAutomatically;
            connectAutomaticallyCheckBox.OnClick = () => { Game.Settings.Chat.ConnectAutomatically ^= true; Game.Settings.Save(); };

            var connectButton = connectPanel.Get<ButtonWidget>("CONNECT_BUTTON");
            connectButton.IsDisabled = () => !Game.GlobalChat.IsValidNickname(nicknameBox.Text);
            connectButton.OnClick = () =>
            {
                Game.Settings.Chat.Nickname = nicknameBox.Text;
                Game.Settings.Save();
                Game.GlobalChat.Connect();
            };

            var mainPanel = widget.Get("GLOBALCHAT_MAIN_PANEL");
            mainPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Disconnected;

            mainPanel.Get<LabelWidget>("CHANNEL_TOPIC").GetText = () => Game.GlobalChat.Topic;

            if (Game.Settings.Chat.ConnectAutomatically && Game.GlobalChat.IsValidNickname(Game.Settings.Chat.Nickname))
                Game.GlobalChat.Connect();
        }
Beispiel #10
0
        public MissionBrowserLogic(Widget widget, Action onStart, Action onExit)
        {
            this.onStart = onStart;

            var missionList = widget.Get<ScrollPanelWidget>("MISSION_LIST");
            var template = widget.Get<ScrollItemWidget>("MISSION_TEMPLATE");

            widget.Get("MISSION_INFO").IsVisible = () => selectedMapPreview != null;

            var previewWidget = widget.Get<MapPreviewWidget>("MISSION_PREVIEW");
            previewWidget.Preview = () => selectedMapPreview;

            descriptionPanel = widget.Get<ScrollPanelWidget>("MISSION_DESCRIPTION_PANEL");
            description = widget.Get<LabelWidget>("MISSION_DESCRIPTION");
            descriptionFont = Game.Renderer.Fonts[description.Font];

            var yaml = new MiniYaml(null, Game.modData.Manifest.Missions.Select(MiniYaml.FromFile).Aggregate(MiniYaml.MergeLiberal)).NodesDict;

            var missionMapPaths = yaml["Missions"].Nodes.Select(n => Path.GetFullPath(n.Key));

            var maps = Game.modData.MapCache
                .Where(p => p.Status == MapStatus.Available && missionMapPaths.Contains(Path.GetFullPath(p.Map.Path)))
                .Select(p => p.Map);

            missionList.RemoveChildren();
            foreach (var m in maps)
            {
                var map = m;

                var item = ScrollItemWidget.Setup(template,
                    () => selectedMapPreview != null && selectedMapPreview.Uid == map.Uid,
                    () => SelectMap(map),
                    StartMission);

                item.Get<LabelWidget>("TITLE").GetText = () => map.Title;
                missionList.AddChild(item);
            }

            if (maps.Any())
                SelectMap(maps.First());

            widget.Get<ButtonWidget>("STARTGAME_BUTTON").OnClick = StartMission;

            widget.Get<ButtonWidget>("BACK_BUTTON").OnClick = () =>
            {
                Game.Disconnect();
                Ui.CloseWindow();
                onExit();
            };
        }
Beispiel #11
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();
				};
		}
Beispiel #12
0
        public ActorSelectorLogic(Widget widget, World world, WorldRenderer worldRenderer)
        {
            mapRules = world.Map.Rules;
            this.world = world;
            this.worldRenderer = worldRenderer;

            editor = widget.Parent.Get<EditorViewportControllerWidget>("MAP_EDITOR");
            ownersDropDown = widget.Get<DropDownButtonWidget>("OWNERS_DROPDOWN");

            panel = widget.Get<ScrollPanelWidget>("ACTORTEMPLATE_LIST");
            itemTemplate = panel.Get<ScrollItemWidget>("ACTORPREVIEW_TEMPLATE");
            panel.Layout = new GridLayout(panel);

            var editorLayer = world.WorldActor.Trait<EditorActorLayer>();

            selectedOwner = editorLayer.Players.Players.Values.First();
            Func<PlayerReference, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
            {
                var item = ScrollItemWidget.Setup(template, () => selectedOwner == option, () =>
                {
                    selectedOwner = option;

                    ownersDropDown.Text = selectedOwner.Name;
                    ownersDropDown.TextColor = selectedOwner.Color.RGB;

                    IntializeActorPreviews();
                });

                item.Get<LabelWidget>("LABEL").GetText = () => option.Name;
                item.GetColor = () => option.Color.RGB;

                return item;
            };

            ownersDropDown.OnClick = () =>
            {
                var owners = editorLayer.Players.Players.Values.OrderBy(p => p.Name);
                ownersDropDown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 270, owners, setupItem);
            };

            ownersDropDown.Text = selectedOwner.Name;
            ownersDropDown.TextColor = selectedOwner.Color.RGB;

            IntializeActorPreviews();
        }
Beispiel #13
0
        internal MapChooserLogic([ObjectCreator.Param] Widget widget,
			[ObjectCreator.Param] string initialMap,
			[ObjectCreator.Param] Action onExit,
			[ObjectCreator.Param] Action<Map> onSelect)
        {
            map = Game.modData.AvailableMaps[WidgetUtils.ChooseInitialMap(initialMap)];

            widget.GetWidget<ButtonWidget>("BUTTON_OK").OnClick = () => { Widget.CloseWindow(); onSelect(map); };
            widget.GetWidget<ButtonWidget>("BUTTON_CANCEL").OnClick = () => { Widget.CloseWindow(); onExit(); };

            scrollpanel = widget.GetWidget<ScrollPanelWidget>("MAP_LIST");
            itemTemplate = scrollpanel.GetWidget<ScrollItemWidget>("MAP_TEMPLATE");

            var gameModeDropdown = widget.GetWidget<DropDownButtonWidget>("GAMEMODE_FILTER");
            if (gameModeDropdown != null)
            {
                var selectableMaps = Game.modData.AvailableMaps.Where(m => m.Value.Selectable);
                var gameModes = selectableMaps
                    .GroupBy(m => m.Value.Type)
                    .Select(g => Pair.New(g.Key, g.Count())).ToList();

                // 'all game types' extra item
                gameModes.Insert( 0, Pair.New( null as string, selectableMaps.Count() ) );

                Func<Pair<string,int>, string> showItem =
                    x => "{0} ({1})".F( x.First ?? "All Game Types", x.Second );

                Func<Pair<string,int>, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, template) =>
                {
                    var item = ScrollItemWidget.Setup(template,
                        () => gameMode == ii.First,
                        () => { gameMode = ii.First; EnumerateMaps(); });
                    item.GetWidget<LabelWidget>("LABEL").GetText = () => showItem(ii);
                    return item;
                };

                gameModeDropdown.OnClick = () =>
                    gameModeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, gameModes, setupItem);

                gameModeDropdown.GetText = () => showItem(gameModes.First(m => m.First == gameMode));
            }

            EnumerateMaps();
        }
        void PopulateObjectivesList(MissionObjectives mo, ScrollPanelWidget parent, ContainerWidget template)
        {
            parent.RemoveChildren();

            foreach (var o in mo.Objectives.OrderBy(o => o.Type))
            {
                var objective = o; // Work around the loop closure issue in older versions of C#
                var widget = template.Clone();

                var label = widget.Get<LabelWidget>("OBJECTIVE_TYPE");
                label.GetText = () => objective.Type == ObjectiveType.Primary ? "Primary" : "Secondary";

                var checkbox = widget.Get<CheckboxWidget>("OBJECTIVE_STATUS");
                checkbox.IsChecked = () => objective.State != ObjectiveState.Incomplete;
                checkbox.GetCheckType = () => objective.State == ObjectiveState.Completed ? "checked" : "crossed";
                checkbox.GetText = () => objective.Description;

                parent.AddChild(widget);
            }
        }
        public MusicPlayerLogic(Widget widget, Ruleset modRules, World world, Action onExit)
        {
            var panel = widget.Get("MUSIC_PANEL");

            musicList = panel.Get<ScrollPanelWidget>("MUSIC_LIST");
            itemTemplate = musicList.Get<ScrollItemWidget>("MUSIC_TEMPLATE");
            musicPlaylist = world.WorldActor.Trait<MusicPlaylist>();

            BuildMusicTable();

            Func<bool> noMusic = () => !musicPlaylist.IsMusicAvailable;
            panel.Get("NO_MUSIC_LABEL").IsVisible = noMusic;

            var playButton = panel.Get<ButtonWidget>("BUTTON_PLAY");
            playButton.OnClick = Play;
            playButton.IsDisabled = noMusic;
            playButton.IsVisible = () => !Sound.MusicPlaying;

            var pauseButton = panel.Get<ButtonWidget>("BUTTON_PAUSE");
            pauseButton.OnClick = Sound.PauseMusic;
            pauseButton.IsDisabled = noMusic;
            pauseButton.IsVisible = () => Sound.MusicPlaying;

            var stopButton = panel.Get<ButtonWidget>("BUTTON_STOP");
            stopButton.OnClick = () => { musicPlaylist.Stop(); };
            stopButton.IsDisabled = noMusic;

            var nextButton = panel.Get<ButtonWidget>("BUTTON_NEXT");
            nextButton.OnClick = () => { currentSong = musicPlaylist.GetNextSong(); Play(); };
            nextButton.IsDisabled = noMusic;

            var prevButton = panel.Get<ButtonWidget>("BUTTON_PREV");
            prevButton.OnClick = () => { currentSong = musicPlaylist.GetPrevSong(); Play(); };
            prevButton.IsDisabled = noMusic;

            var shuffleCheckbox = panel.Get<CheckboxWidget>("SHUFFLE");
            shuffleCheckbox.IsChecked = () => Game.Settings.Sound.Shuffle;
            shuffleCheckbox.OnClick = () => Game.Settings.Sound.Shuffle ^= true;

            var repeatCheckbox = panel.Get<CheckboxWidget>("REPEAT");
            repeatCheckbox.IsChecked = () => Game.Settings.Sound.Repeat;
            repeatCheckbox.OnClick = () => Game.Settings.Sound.Repeat ^= true;

            panel.Get<LabelWidget>("TIME_LABEL").GetText = () => (currentSong == null) ? "" :
                "{0:D2}:{1:D2} / {2:D2}:{3:D2}".F((int)Sound.MusicSeekPosition / 60, (int)Sound.MusicSeekPosition % 60,
                    currentSong.Length / 60, currentSong.Length % 60);

            var musicSlider = panel.Get<SliderWidget>("MUSIC_SLIDER");
            musicSlider.OnChange += x => Sound.MusicVolume = x;
            musicSlider.Value = Sound.MusicVolume;

            var installButton = widget.GetOrNull<ButtonWidget>("INSTALL_BUTTON");
            if (installButton != null)
            {
                installButton.IsDisabled = () => world == null || world.Type != WorldType.Shellmap;
                var args = new string[] { "Install.Music=true" };
                installButton.OnClick = () =>
                    Game.RunAfterTick(() =>
                        Game.InitializeMod(Game.Settings.Game.Mod, new Arguments(args)));

                var installData = Game.ModData.Manifest.Get<ContentInstaller>();
                installButton.IsVisible = () => modRules.InstalledMusic.ToArray().Length <= installData.ShippedSoundtracks;
            }

            var songWatcher = widget.GetOrNull<LogicTickerWidget>("SONG_WATCHER");
            if (songWatcher != null)
            {
                songWatcher.OnTick = () =>
                {
                    if (Sound.CurrentMusic == null || currentSong == Sound.CurrentMusic)
                        return;

                    currentSong = Sound.CurrentMusic;
                };
            }

            panel.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => { Game.Settings.Save(); Ui.CloseWindow(); onExit(); };
        }
Beispiel #16
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();
				};
		}
Beispiel #17
0
        void AddAsset(ScrollPanelWidget list, string filepath, ScrollItemWidget template)
        {
            var filename = Path.GetFileName(filepath);
            var item = ScrollItemWidget.Setup(template,
                () => currentFilename == filename,
                () => { LoadAsset(filename); });
            item.Get<LabelWidget>("TITLE").GetText = () => filepath;
            item.IsVisible = () =>
            {
                bool visible;
                if (assetVisByName.TryGetValue(filepath, out visible))
                    return visible;

                visible = FilterAsset(filepath);
                assetVisByName.Add(filepath, visible);
                return visible;
            };

            list.AddChild(item);
        }
Beispiel #18
0
		public MainMenuLogic(Widget widget, World world)
		{
			rootMenu = widget;
			rootMenu.Get<LabelWidget>("VERSION_LABEL").Text = Game.modData.Manifest.Mod.Version;

			// Menu buttons
			var mainMenu = widget.Get("MAIN_MENU");
			mainMenu.IsVisible = () => menuType == MenuType.Main;

			mainMenu.Get<ButtonWidget>("SINGLEPLAYER_BUTTON").OnClick = () => menuType = MenuType.Singleplayer;

			mainMenu.Get<ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = () =>
			{
				menuType = MenuType.None;
				Ui.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs
				{
					{ "onStart", RemoveShellmapUI },
					{ "onExit", () => menuType = MenuType.Main }
				});
			};

			mainMenu.Get<ButtonWidget>("MODS_BUTTON").OnClick = () =>
			{
				Game.Settings.Game.PreviousMod = Game.modData.Manifest.Mod.Id;
				Game.InitializeMod("modchooser", null);
			};

			mainMenu.Get<ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
			{
				menuType = MenuType.None;
				Game.OpenWindow("SETTINGS_PANEL", new WidgetArgs
				{
					{ "onExit", () => menuType = MenuType.Main }
				});
			};

			mainMenu.Get<ButtonWidget>("EXTRAS_BUTTON").OnClick = () => menuType = MenuType.Extras;

			mainMenu.Get<ButtonWidget>("QUIT_BUTTON").OnClick = Game.Exit;

			// Singleplayer menu
			var singleplayerMenu = widget.Get("SINGLEPLAYER_MENU");
			singleplayerMenu.IsVisible = () => menuType == MenuType.Singleplayer;

			var missionsButton = singleplayerMenu.Get<ButtonWidget>("MISSIONS_BUTTON");
			missionsButton.OnClick = () =>
			{
				menuType = MenuType.None;
				Ui.OpenWindow("MISSIONBROWSER_PANEL", new WidgetArgs
				{
					{ "onExit", () => menuType = MenuType.Singleplayer },
					{ "onStart", RemoveShellmapUI }
				});
			};
			missionsButton.Disabled = !Game.modData.Manifest.Missions.Any();

			singleplayerMenu.Get<ButtonWidget>("SKIRMISH_BUTTON").OnClick = StartSkirmishGame;

			singleplayerMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Main;

			// Extras menu
			var extrasMenu = widget.Get("EXTRAS_MENU");
			extrasMenu.IsVisible = () => menuType == MenuType.Extras;

			extrasMenu.Get<ButtonWidget>("REPLAYS_BUTTON").OnClick = () =>
			{
				menuType = MenuType.None;
				Ui.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs
				{
					{ "onExit", () => menuType = MenuType.Extras },
					{ "onStart", RemoveShellmapUI }
				});
			};

			extrasMenu.Get<ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
			{
				menuType = MenuType.None;
				Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
				{
					{ "onExit", () => menuType = MenuType.Extras },
				});
			};

			var assetBrowserButton = extrasMenu.GetOrNull<ButtonWidget>("ASSETBROWSER_BUTTON");
			if (assetBrowserButton != null)
				assetBrowserButton.OnClick = () =>
				{
					menuType = MenuType.None;
					Game.OpenWindow("ASSETBROWSER_PANEL", new WidgetArgs
					{
						{ "onExit", () => menuType = MenuType.Extras },
					});
				};

			extrasMenu.Get<ButtonWidget>("CREDITS_BUTTON").OnClick = () =>
			{
				menuType = MenuType.None;
				Ui.OpenWindow("CREDITS_PANEL", new WidgetArgs
				{
					{ "onExit", () => menuType = MenuType.Extras },
				});
			};

			extrasMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Main;

			var newsBG = widget.GetOrNull("NEWS_BG");
			if (newsBG != null)
			{
				newsBG.IsVisible = () => Game.Settings.Game.FetchNews && menuType != MenuType.None;

				newsPanel = Ui.LoadWidget<ScrollPanelWidget>("NEWS_PANEL", null, new WidgetArgs());
				newsTemplate = newsPanel.Get("NEWS_ITEM_TEMPLATE");
				newsPanel.RemoveChild(newsTemplate);

				newsStatus = newsPanel.Get<LabelWidget>("NEWS_STATUS");
				SetNewsStatus("Loading news");

				var cacheFile = Path.Combine(Platform.SupportDir, "news.yaml");
				var currentNews = ParseNews(cacheFile);
				if (currentNews != null)
					DisplayNews(currentNews);

				// Only query for new stories once per day
				var cacheValid = currentNews != null && DateTime.Today.ToUniversalTime() <= Game.Settings.Game.NewsFetchedDate;
				if (!cacheValid)
					new Download(Game.Settings.Game.NewsUrl, cacheFile, e => { }, (e, c) => NewsDownloadComplete(e, c, cacheFile, currentNews));

				var newsButton = newsBG.GetOrNull<DropDownButtonWidget>("NEWS_BUTTON");
				newsButton.OnClick = () =>
				{
					newsButton.AttachPanel(newsPanel);
					newsHighlighted = false;
				};

				newsButton.IsHighlighted = () => newsHighlighted && Game.LocalTick % 50 < 25;
			}
		}
        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.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");

            var mapPreview = lobby.Get<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.GetOrNull<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.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 disconnectButton = lobby.Get<ButtonWidget>("DISCONNECT_BUTTON");
            disconnectButton.OnClick = () => { CloseWindow(); onExit(); };

            var gameStarting = false;

            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 startGameButton = lobby.Get<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.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();
                    if (slot != null && bot != null)
                        orderManager.IssueOrder(Order.Command("slot_bot {0} {1}".F(slot, bot)));
                });
        }
Beispiel #20
0
        public MainMenuLogic(Widget widget, World world)
        {
            rootMenu = widget;
            rootMenu.Get<LabelWidget>("VERSION_LABEL").Text = Game.ModData.Manifest.Mod.Version;

            // Menu buttons
            var mainMenu = widget.Get("MAIN_MENU");
            mainMenu.IsVisible = () => menuType == MenuType.Main;

            mainMenu.Get<ButtonWidget>("SINGLEPLAYER_BUTTON").OnClick = () => menuType = MenuType.Singleplayer;

            mainMenu.Get<ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs
                {
                    { "onStart", RemoveShellmapUI },
                    { "onExit", () => menuType = MenuType.Main },
                    { "directConnectHost", null },
                    { "directConnectPort", 0 },
                });
            };

            mainMenu.Get<ButtonWidget>("MODS_BUTTON").OnClick = () =>
            {
                Game.Settings.Game.PreviousMod = Game.ModData.Manifest.Mod.Id;
                Game.InitializeMod("modchooser", null);
            };

            mainMenu.Get<ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Main }
                });
            };

            mainMenu.Get<ButtonWidget>("EXTRAS_BUTTON").OnClick = () => menuType = MenuType.Extras;

            mainMenu.Get<ButtonWidget>("QUIT_BUTTON").OnClick = Game.Exit;

            // Singleplayer menu
            var singleplayerMenu = widget.Get("SINGLEPLAYER_MENU");
            singleplayerMenu.IsVisible = () => menuType == MenuType.Singleplayer;

            var missionsButton = singleplayerMenu.Get<ButtonWidget>("MISSIONS_BUTTON");
            missionsButton.OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("MISSIONBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Singleplayer },
                    { "onStart", RemoveShellmapUI }
                });
            };

            var hasCampaign = Game.ModData.Manifest.Missions.Any();
            var hasMissions = Game.ModData.MapCache
                .Any(p => p.Status == MapStatus.Available && p.Map.Visibility.HasFlag(MapVisibility.MissionSelector));

            missionsButton.Disabled = !hasCampaign && !hasMissions;

            singleplayerMenu.Get<ButtonWidget>("SKIRMISH_BUTTON").OnClick = StartSkirmishGame;

            singleplayerMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Main;

            // Extras menu
            var extrasMenu = widget.Get("EXTRAS_MENU");
            extrasMenu.IsVisible = () => menuType == MenuType.Extras;

            extrasMenu.Get<ButtonWidget>("REPLAYS_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Extras },
                    { "onStart", RemoveShellmapUI }
                });
            };

            extrasMenu.Get<ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Extras },
                    { "world", world }
                });
            };

            extrasMenu.Get<ButtonWidget>("MAP_EDITOR_BUTTON").OnClick = () => menuType = MenuType.MapEditor;

            var assetBrowserButton = extrasMenu.GetOrNull<ButtonWidget>("ASSETBROWSER_BUTTON");
            if (assetBrowserButton != null)
                assetBrowserButton.OnClick = () =>
                {
                    menuType = MenuType.None;
                    Game.OpenWindow("ASSETBROWSER_PANEL", new WidgetArgs
                    {
                        { "onExit", () => menuType = MenuType.Extras },
                    });
                };

            extrasMenu.Get<ButtonWidget>("CREDITS_BUTTON").OnClick = () =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("CREDITS_PANEL", new WidgetArgs
                {
                    { "onExit", () => menuType = MenuType.Extras },
                });
            };

            extrasMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Main;

            // Map editor menu
            var mapEditorMenu = widget.Get("MAP_EDITOR_MENU");
            mapEditorMenu.IsVisible = () => menuType == MenuType.MapEditor;

            var onSelect = new Action<string>(uid =>
            {
                RemoveShellmapUI();
                LoadMapIntoEditor(Game.ModData.MapCache[uid].Map);
            });

            var newMapButton = widget.Get<ButtonWidget>("NEW_MAP_BUTTON");
            newMapButton.OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("NEW_MAP_BG", new WidgetArgs()
                {
                    { "onSelect", onSelect },
                    { "onExit", () => menuType = MenuType.MapEditor }
                });
            };

            var loadMapButton = widget.Get<ButtonWidget>("LOAD_MAP_BUTTON");
            loadMapButton.OnClick = () =>
            {
                menuType = MenuType.None;
                Game.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", null },
                    { "initialTab", MapClassification.User },
                    { "onExit", () => menuType = MenuType.MapEditor },
                    { "onSelect", onSelect },
                    { "filter", MapVisibility.Lobby | MapVisibility.Shellmap | MapVisibility.MissionSelector },
                });
            };

            mapEditorMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => menuType = MenuType.Extras;

            var newsBG = widget.GetOrNull("NEWS_BG");
            if (newsBG != null)
            {
                newsBG.IsVisible = () => Game.Settings.Game.FetchNews && menuType != MenuType.None;

                newsPanel = Ui.LoadWidget<ScrollPanelWidget>("NEWS_PANEL", null, new WidgetArgs());
                newsTemplate = newsPanel.Get("NEWS_ITEM_TEMPLATE");
                newsPanel.RemoveChild(newsTemplate);

                newsStatus = newsPanel.Get<LabelWidget>("NEWS_STATUS");
                SetNewsStatus("Loading news");

                var cacheFile = Platform.ResolvePath("^", "news.yaml");
                var currentNews = ParseNews(cacheFile);
                if (currentNews != null)
                    DisplayNews(currentNews);

                // Only query for new stories once per day
                var cacheValid = currentNews != null && DateTime.Today.ToUniversalTime() <= Game.Settings.Game.NewsFetchedDate;
                if (!cacheValid)
                    new Download(Game.Settings.Game.NewsUrl, cacheFile, e => { }, (e, c) => NewsDownloadComplete(e, c, cacheFile, currentNews));

                var newsButton = newsBG.GetOrNull<DropDownButtonWidget>("NEWS_BUTTON");
                newsButton.OnClick = () =>
                {
                    newsButton.AttachPanel(newsPanel);
                    newsHighlighted = false;
                };

                newsButton.IsHighlighted = () => newsHighlighted && Game.LocalTick % 50 < 25;
            }

            Game.OnRemoteDirectConnect += (host, port) =>
            {
                menuType = MenuType.None;
                Ui.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs
                {
                    { "onStart", RemoveShellmapUI },
                    { "onExit", () => menuType = MenuType.Main },
                    { "directConnectHost", host },
                    { "directConnectPort", port },
                });
            };
        }
Beispiel #21
0
        internal CncLobbyLogic([ObjectCreator.Param( "widget" )] Widget lobby,
		                       [ObjectCreator.Param] World world, // Shellmap world
		                       [ObjectCreator.Param] OrderManager orderManager,
		                       [ObjectCreator.Param] Action onExit,
		                       [ObjectCreator.Param] Action onStart,
		                       [ObjectCreator.Param] bool addBots)
        {
            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<CncColorPickerPaletteModifier>();
            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 =>
            {
                var map = mapPreview.Map();
                if (map == null || mi.Button != MouseButton.Left
                    || orderManager.LocalClient.State == Session.ClientState.Ready)
                    return;

                var p = map.SpawnPoints
                    .Select((sp, i) => Pair.New(mapPreview.ConvertToPreview(map, sp), i))
                    .Where(a => (a.First - mi.Location).LengthSquared < 64)
                    .Select(a => a.Second + 1)
                    .FirstOrDefault();

                var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == p);
                if (p == 0 || !owned)
                    orderManager.IssueOrder(Order.Command("spawn {0} {1}".F(orderManager.LocalClient.Index, p)));
            };

            var mapTitle = lobby.GetWidget<LabelWidget>("MAP_TITLE");
            mapTitle.IsVisible = () => Map != null;
            mapTitle.GetText = () => Map.Title;

            mapPreview.SpawnColors = () =>
            {
                var spawns = Map.SpawnPoints;
                var sc = new Dictionary<int2, Color>();

                for (int i = 1; i <= spawns.Count(); i++)
                {
                    var client = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.SpawnPoint == i);
                    if (client == null)
                        continue;
                    sc.Add(spawns.ElementAt(i - 1), client.ColorRamp.GetColor(0));
                }
                return sc;
            };

            CountryNames = Rules.Info["world"].Traits.WithInterface<CountryInfo>()
                .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();
                });

                Widget.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.State == Session.ClientState.Ready;
            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();

            lobby.GetWidget<ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                Widget.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)));
                });
        }
Beispiel #22
0
 public GridLayout(ScrollPanelWidget w)
 {
     widget = w;
 }
Beispiel #23
0
        internal LobbyLogic(Widget widget, WorldRenderer worldRenderer, OrderManager orderManager,
			Action onExit, Action onStart, bool skirmishMode, Ruleset modRules)
        {
            lobby = widget;
            this.orderManager = orderManager;
            this.onStart = onStart;
            this.onExit = onExit;
            this.skirmishMode = skirmishMode;
            this.modRules = modRules;
            shellmapWorld = worldRenderer.World;

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

            var name = lobby.GetOrNull<LabelWidget>("SERVER_NAME");
            if (name != null)
                name.GetText = () => orderManager.LobbyInfo.GlobalSettings.ServerName;

            Ui.LoadWidget("LOBBY_MAP_PREVIEW", lobby.Get("MAP_PREVIEW_ROOT"), new WidgetArgs
            {
                { "orderManager", orderManager },
                { "lobby", this }
            });

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

            var playerBinHeaders = lobby.GetOrNull<ContainerWidget>("LABEL_CONTAINER");
            if (playerBinHeaders != null)
                playerBinHeaders.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;

            foreach (var f in modRules.Actors["world"].Traits.WithInterface<FactionInfo>())
                factions.Add(f.InternalName, new LobbyFaction { Selectable = f.Selectable, Name = f.Name, Side = f.Side, Description = f.Description });

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

            var mapButton = lobby.GetOrNull<ButtonWidget>("CHANGEMAP_BUTTON");
            if (mapButton != null)
            {
                mapButton.IsDisabled = () => gameStarting || panel == PanelType.Kick || panel == PanelType.ForceStart ||
                    orderManager.LocalClient == null || orderManager.LocalClient.IsReady;
                mapButton.OnClick = () =>
                {
                    var onSelect = new Action<string>(uid =>
                    {
                        // Don't select the same map again
                        if (uid == Map.Uid)
                            return;

                        orderManager.IssueOrder(Order.Command("map " + uid));
                        Game.Settings.Server.Map = uid;
                        Game.Settings.Save();
                    });

                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", Map.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", DoNothing },
                        { "onSelect", Game.IsHost ? onSelect : null },
                        { "filter", MapVisibility.Lobby },
                    });
                };
            }

            var slotsButton = lobby.GetOrNull<DropDownButtonWidget>("SLOTS_DROPDOWNBUTTON");
            if (slotsButton != null)
            {
                slotsButton.IsDisabled = () => configurationDisabled() || panel != PanelType.Players ||
                    Map.RuleStatus != MapRuleStatus.Cached || !orderManager.LobbyInfo.Slots.Values.Any(s => s.AllowBots || !s.LockTeam);

                var botNames = modRules.Actors["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 = botNames.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 = () => Map.RuleStatus != MapRuleStatus.Cached || panel == PanelType.Kick || panel == PanelType.ForceStart;
            optionsButton.GetText = () => panel == PanelType.Options ? "Players" : "Options";
            optionsButton.OnClick = () => panel = (panel == PanelType.Options) ? PanelType.Players : PanelType.Options;

            // Force start panel
            Action startGame = () =>
            {
                gameStarting = true;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            var startGameButton = lobby.GetOrNull<ButtonWidget>("START_GAME_BUTTON");
            if (startGameButton != null)
            {
                startGameButton.IsDisabled = () => configurationDisabled() || Map.RuleStatus != MapRuleStatus.Cached ||
                    orderManager.LobbyInfo.Slots.Any(sl => sl.Value.Required && orderManager.LobbyInfo.ClientInSlot(sl.Key) == null);
                startGameButton.OnClick = () =>
                {
                    Func<KeyValuePair<string, Session.Slot>, bool> notReady = sl =>
                    {
                        var cl = orderManager.LobbyInfo.ClientInSlot(sl.Key);

                        // Bots and admins don't count
                        return cl != null && !cl.IsAdmin && cl.Bot == null && !cl.IsReady;
                    };

                    if (orderManager.LobbyInfo.Slots.Any(notReady))
                        panel = PanelType.ForceStart;
                    else
                        startGame();
                };
            }

            var forceStartBin = Ui.LoadWidget("FORCE_START_DIALOG", lobby, new WidgetArgs());
            forceStartBin.IsVisible = () => panel == PanelType.ForceStart;
            forceStartBin.Get("KICK_WARNING").IsVisible = () => orderManager.LobbyInfo.Clients.Any(c => c.IsInvalid);
            forceStartBin.Get<ButtonWidget>("OK_BUTTON").OnClick = startGame;
            forceStartBin.Get<ButtonWidget>("CANCEL_BUTTON").OnClick = () => panel = PanelType.Players;

            // Options panel
            var allowCheats = optionsBin.GetOrNull<CheckboxWidget>("ALLOWCHEATS_CHECKBOX");
            if (allowCheats != null)
            {
                allowCheats.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats;
                allowCheats.IsDisabled = () => Map.Status != MapStatus.Available || Map.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.Status != MapStatus.Available || Map.Map.Options.Crates.HasValue || configurationDisabled();
                crates.OnClick = () => orderManager.IssueOrder(Order.Command(
                    "crates {0}".F(!orderManager.LobbyInfo.GlobalSettings.Crates)));
            }

            var creeps = optionsBin.GetOrNull<CheckboxWidget>("CREEPS_CHECKBOX");
            if (creeps != null)
            {
                creeps.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.Creeps;
                creeps.IsDisabled = () => Map.Status != MapStatus.Available || Map.Map.Options.Creeps.HasValue || configurationDisabled();
                creeps.OnClick = () => orderManager.IssueOrder(Order.Command(
                    "creeps {0}".F(!orderManager.LobbyInfo.GlobalSettings.Creeps)));
            }

            var allybuildradius = optionsBin.GetOrNull<CheckboxWidget>("ALLYBUILDRADIUS_CHECKBOX");
            if (allybuildradius != null)
            {
                allybuildradius.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.AllyBuildRadius;
                allybuildradius.IsDisabled = () => Map.Status != MapStatus.Available || Map.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.Status != MapStatus.Available || Map.Map.Options.FragileAlliances.HasValue || configurationDisabled();
                fragileAlliance.OnClick = () => orderManager.IssueOrder(Order.Command(
                    "fragilealliance {0}".F(!orderManager.LobbyInfo.GlobalSettings.FragileAlliances)));
            }

            var shortGame = optionsBin.GetOrNull<CheckboxWidget>("SHORTGAME_CHECKBOX");
            if (shortGame != null)
            {
                shortGame.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.ShortGame;
                shortGame.IsDisabled = () => Map.Status != MapStatus.Available || Map.Map.Options.ShortGame.HasValue || configurationDisabled();
                shortGame.OnClick = () => orderManager.IssueOrder(Order.Command(
                    "shortgame {0}".F(!orderManager.LobbyInfo.GlobalSettings.ShortGame)));
            }

            var difficulty = optionsBin.GetOrNull<DropDownButtonWidget>("DIFFICULTY_DROPDOWNBUTTON");
            if (difficulty != null)
            {
                difficulty.IsVisible = () => Map.Status == MapStatus.Available && Map.Map.Options.Difficulties.Any();
                difficulty.IsDisabled = () => Map.Status != MapStatus.Available || configurationDisabled();
                difficulty.GetText = () => orderManager.LobbyInfo.GlobalSettings.Difficulty;
                difficulty.OnMouseDown = _ =>
                {
                    var options = Map.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 startUnitsInfo = modRules.Actors["world"].Traits.WithInterface<MPStartUnitsInfo>();
                var classes = startUnitsInfo.Select(a => a.Class).Distinct();
                Func<string, string> className = c =>
                {
                    var selectedClass = startUnitsInfo.Where(s => s.Class == c).Select(u => u.ClassName).FirstOrDefault();
                    return selectedClass != null ? selectedClass : c;
                };

                startingUnits.IsDisabled = () => Map.Status != MapStatus.Available ||
                    !Map.Map.Options.ConfigurableStartingUnits || configurationDisabled();
                startingUnits.GetText = () => Map.Status != MapStatus.Available ||
                    !Map.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.Status != MapStatus.Available ||
                    Map.Map.Options.StartingCash.HasValue || configurationDisabled();
                startingCash.GetText = () => Map.Status != MapStatus.Available ||
                    Map.Map.Options.StartingCash.HasValue ? "Not Available" : "${0}".F(orderManager.LobbyInfo.GlobalSettings.StartingCash);
                startingCash.OnMouseDown = _ =>
                {
                    var options = modRules.Actors["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 techLevel = optionsBin.GetOrNull<DropDownButtonWidget>("TECHLEVEL_DROPDOWNBUTTON");
            if (techLevel != null)
            {
                var techTraits = modRules.Actors["player"].Traits.WithInterface<ProvidesTechPrerequisiteInfo>().ToList();
                techLevel.IsVisible = () => techTraits.Count > 0;

                var techLevelDescription = optionsBin.GetOrNull<LabelWidget>("TECHLEVEL_DESC");
                if (techLevelDescription != null)
                    techLevelDescription.IsVisible = () => techTraits.Count > 0;

                techLevel.IsDisabled = () => Map.Status != MapStatus.Available ||
                    Map.Map.Options.TechLevel != null || configurationDisabled() || techTraits.Count <= 1;
                techLevel.GetText = () => Map.Status != MapStatus.Available ||
                    Map.Map.Options.TechLevel != null ? "Not Available" : "{0}".F(orderManager.LobbyInfo.GlobalSettings.TechLevel);
                techLevel.OnMouseDown = _ =>
                {
                    var options = techTraits.Select(c => new DropDownOption
                    {
                        Title = "{0}".F(c.Name),
                        IsSelected = () => orderManager.LobbyInfo.GlobalSettings.TechLevel == c.Name,
                        OnClick = () => orderManager.IssueOrder(Order.Command("techlevel {0}".F(c.Name)))
                    });

                    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;
                    };

                    techLevel.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.Status != MapStatus.Available || Map.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.Status != MapStatus.Available || Map.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(); };

            if (skirmishMode)
                disconnectButton.Text = "Back";

            chatLabel = lobby.Get<LabelWidget>("LABEL_CHATTYPE");
            var chatTextField = lobby.Get<TextFieldWidget>("CHAT_TEXTFIELD");
            chatTextField.TakeKeyboardFocus();
            chatTextField.OnEnterKey = () =>
            {
                if (chatTextField.Text.Length == 0)
                    return true;

                // Always scroll to bottom when we've typed something
                chatPanel.ScrollToBottom();

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

            chatTextField.OnTabKey = () =>
            {
                var previousText = chatTextField.Text;
                chatTextField.Text = tabCompletion.Complete(chatTextField.Text);
                chatTextField.CursorPosition = chatTextField.Text.Length;

                if (chatTextField.Text == previousText)
                    return SwitchTeamChat();
                else
                    return true;
            };

            chatTextField.OnEscKey = () => { chatTextField.Text = ""; 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", DoNothing },
                    { "world", worldRenderer.World }
                });

            var settingsButton = lobby.GetOrNull<ButtonWidget>("SETTINGS_BUTTON");
            if (settingsButton != null)
            {
                settingsButton.OnClick = () => Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", DoNothing },
                    { "worldRenderer", worldRenderer }
                });
            }

            // Add a bot on the first lobbyinfo update
            if (skirmishMode)
            {
                Game.LobbyInfoChanged += WidgetUtils.Once(() =>
                {
                    var slot = orderManager.LobbyInfo.FirstEmptyBotSlot();
                    var bot = modRules.Actors["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)));
                });
            }
        }
Beispiel #24
0
        public MainMenuLogic(Widget widget, World world, ModData modData)
        {
            rootMenu = widget;
            rootMenu.Get<LabelWidget>("VERSION_LABEL").Text = modData.Manifest.Metadata.Version;

            // Menu buttons
            var mainMenu = widget.Get("MAIN_MENU");
            mainMenu.IsVisible = () => menuType == MenuType.Main;

            mainMenu.Get<ButtonWidget>("SINGLEPLAYER_BUTTON").OnClick = () => SwitchMenu(MenuType.Singleplayer);

            mainMenu.Get<ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("MULTIPLAYER_PANEL", new WidgetArgs
                {
                    { "onStart", RemoveShellmapUI },
                    { "onExit", () => SwitchMenu(MenuType.Main) },
                    { "directConnectHost", null },
                    { "directConnectPort", 0 },
                });
            };

            mainMenu.Get<ButtonWidget>("MODS_BUTTON").OnClick = () =>
            {
                // Switching mods changes the world state (by disposing it),
                // so we can't do this inside the input handler.
                Game.RunAfterTick(() =>
                {
                    Game.Settings.Game.PreviousMod = modData.Manifest.Id;
                    Game.InitializeMod("modchooser", null);
                });
            };

            mainMenu.Get<ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("SETTINGS_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Main) }
                });
            };

            mainMenu.Get<ButtonWidget>("EXTRAS_BUTTON").OnClick = () => SwitchMenu(MenuType.Extras);

            mainMenu.Get<ButtonWidget>("QUIT_BUTTON").OnClick = Game.Exit;

            // Singleplayer menu
            var singleplayerMenu = widget.Get("SINGLEPLAYER_MENU");
            singleplayerMenu.IsVisible = () => menuType == MenuType.Singleplayer;

            var missionsButton = singleplayerMenu.Get<ButtonWidget>("MISSIONS_BUTTON");
            missionsButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("MISSIONBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Singleplayer) },
                    { "onStart", RemoveShellmapUI }
                });
            };

            var hasCampaign = modData.Manifest.Missions.Any();
            var hasMissions = modData.MapCache
                .Any(p => p.Status == MapStatus.Available && p.Visibility.HasFlag(MapVisibility.MissionSelector));

            missionsButton.Disabled = !hasCampaign && !hasMissions;

            singleplayerMenu.Get<ButtonWidget>("SKIRMISH_BUTTON").OnClick = StartSkirmishGame;

            singleplayerMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Main);

            // Extras menu
            var extrasMenu = widget.Get("EXTRAS_MENU");
            extrasMenu.IsVisible = () => menuType == MenuType.Extras;

            extrasMenu.Get<ButtonWidget>("REPLAYS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                    { "onStart", RemoveShellmapUI }
                });
            };

            extrasMenu.Get<ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                    { "world", world }
                });
            };

            extrasMenu.Get<ButtonWidget>("MAP_EDITOR_BUTTON").OnClick = () => SwitchMenu(MenuType.MapEditor);

            var assetBrowserButton = extrasMenu.GetOrNull<ButtonWidget>("ASSETBROWSER_BUTTON");
            if (assetBrowserButton != null)
                assetBrowserButton.OnClick = () =>
                {
                    SwitchMenu(MenuType.None);
                    Game.OpenWindow("ASSETBROWSER_PANEL", new WidgetArgs
                    {
                        { "onExit", () => SwitchMenu(MenuType.Extras) },
                    });
                };

            extrasMenu.Get<ButtonWidget>("CREDITS_BUTTON").OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Ui.OpenWindow("CREDITS_PANEL", new WidgetArgs
                {
                    { "onExit", () => SwitchMenu(MenuType.Extras) },
                });
            };

            extrasMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Main);

            // Map editor menu
            var mapEditorMenu = widget.Get("MAP_EDITOR_MENU");
            mapEditorMenu.IsVisible = () => menuType == MenuType.MapEditor;

            // Loading into the map editor
            Game.BeforeGameStart += RemoveShellmapUI;

            var onSelect = new Action<string>(uid => LoadMapIntoEditor(modData.MapCache[uid].Uid));

            var newMapButton = widget.Get<ButtonWidget>("NEW_MAP_BUTTON");
            newMapButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("NEW_MAP_BG", new WidgetArgs()
                {
                    { "onSelect", onSelect },
                    { "onExit", () => SwitchMenu(MenuType.MapEditor) }
                });
            };

            var loadMapButton = widget.Get<ButtonWidget>("LOAD_MAP_BUTTON");
            loadMapButton.OnClick = () =>
            {
                SwitchMenu(MenuType.None);
                Game.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                {
                    { "initialMap", null },
                    { "initialTab", MapClassification.User },
                    { "onExit", () => SwitchMenu(MenuType.MapEditor) },
                    { "onSelect", onSelect },
                    { "filter", MapVisibility.Lobby | MapVisibility.Shellmap | MapVisibility.MissionSelector },
                });
            };

            mapEditorMenu.Get<ButtonWidget>("BACK_BUTTON").OnClick = () => SwitchMenu(MenuType.Extras);

            var newsBG = widget.GetOrNull("NEWS_BG");
            if (newsBG != null)
            {
                newsBG.IsVisible = () => Game.Settings.Game.FetchNews && menuType != MenuType.None && menuType != MenuType.SystemInfoPrompt;

                newsPanel = Ui.LoadWidget<ScrollPanelWidget>("NEWS_PANEL", null, new WidgetArgs());
                newsTemplate = newsPanel.Get("NEWS_ITEM_TEMPLATE");
                newsPanel.RemoveChild(newsTemplate);

                newsStatus = newsPanel.Get<LabelWidget>("NEWS_STATUS");
                SetNewsStatus("Loading news");
            }

            Game.OnRemoteDirectConnect += OnRemoteDirectConnect;

            // System information opt-out prompt
            var sysInfoPrompt = widget.Get("SYSTEM_INFO_PROMPT");
            sysInfoPrompt.IsVisible = () => menuType == MenuType.SystemInfoPrompt;
            if (Game.Settings.Debug.SystemInformationVersionPrompt < SystemInformationVersion)
            {
                menuType = MenuType.SystemInfoPrompt;

                var sysInfoCheckbox = sysInfoPrompt.Get<CheckboxWidget>("SYSINFO_CHECKBOX");
                sysInfoCheckbox.IsChecked = () => Game.Settings.Debug.SendSystemInformation;
                sysInfoCheckbox.OnClick = () => Game.Settings.Debug.SendSystemInformation ^= true;

                var sysInfoData = sysInfoPrompt.Get<ScrollPanelWidget>("SYSINFO_DATA");
                var template = sysInfoData.Get<LabelWidget>("DATA_TEMPLATE");
                sysInfoData.RemoveChildren();

                foreach (var info in GetSystemInformation().Values)
                {
                    var label = template.Clone() as LabelWidget;
                    var text = info.First + ": " + info.Second;
                    label.GetText = () => text;
                    sysInfoData.AddChild(label);
                }

                sysInfoPrompt.Get<ButtonWidget>("BACK_BUTTON").OnClick = () =>
                {
                    Game.Settings.Debug.SystemInformationVersionPrompt = SystemInformationVersion;
                    Game.Settings.Save();
                    SwitchMenu(MenuType.Main);
                    LoadAndDisplayNews(newsBG);
                };
            }
            else
                LoadAndDisplayNews(newsBG);
        }
Beispiel #25
0
        public AssetBrowserLogic(Widget widget, Action onExit, World world)
        {
            this.world = world;

            panel = widget;
            assetSource = GlobalFileSystem.MountedFolders.First();

            var ticker = panel.GetOrNull<LogicTickerWidget>("ANIMATION_TICKER");
            if (ticker != null)
            {
                ticker.OnTick = () =>
                {
                    if (animateFrames)
                        SelectNextFrame();
                };
            }

            var sourceDropdown = panel.GetOrNull<DropDownButtonWidget>("SOURCE_SELECTOR");
            if (sourceDropdown != null)
            {
                sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown);
                sourceDropdown.GetText = () =>
                {
                    var name = assetSource != null ? Platform.UnresolvePath(assetSource.Name) : "All Packages";
                    if (name.Length > 15)
                        name = "..." + name.Substring(name.Length - 15);

                    return name;
                };
            }

            var spriteWidget = panel.GetOrNull<SpriteWidget>("SPRITE");
            if (spriteWidget != null)
            {
                spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null;
                currentPalette = spriteWidget.Palette;
                spriteWidget.GetPalette = () => currentPalette;
                spriteWidget.IsVisible = () => !isVideoLoaded;
            }

            var playerWidget = panel.GetOrNull<VqaPlayerWidget>("PLAYER");
            if (playerWidget != null)
                playerWidget.IsVisible = () => isVideoLoaded;

            var paletteDropDown = panel.GetOrNull<DropDownButtonWidget>("PALETTE_SELECTOR");
            if (paletteDropDown != null)
            {
                paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world);
                paletteDropDown.GetText = () => currentPalette;
            }

            var colorPreview = panel.GetOrNull<ColorPreviewManagerWidget>("COLOR_MANAGER");
            if (colorPreview != null)
                colorPreview.Color = Game.Settings.Player.Color;

            var colorDropdown = panel.GetOrNull<DropDownButtonWidget>("COLOR");
            if (colorDropdown != null)
            {
                colorDropdown.IsDisabled = () => currentPalette != colorPreview.PaletteName;
                colorDropdown.OnMouseDown = _ => ShowColorDropDown(colorDropdown, colorPreview, world);
                panel.Get<ColorBlockWidget>("COLORBLOCK").GetColor = () => Game.Settings.Player.Color.RGB;
            }

            filenameInput = panel.Get<TextFieldWidget>("FILENAME_INPUT");
            filenameInput.OnTextEdited = () => ApplyFilter(filenameInput.Text);

            var frameContainer = panel.GetOrNull("FRAME_SELECTOR");
            if (frameContainer != null)
                frameContainer.IsVisible = () => (currentSprites != null && currentSprites.Length > 1) || (player != null && player.Video != null && player.Video.Frames > 1);

            frameSlider = panel.Get<SliderWidget>("FRAME_SLIDER");
            if (frameSlider != null)
            {
                frameSlider.OnChange += x =>
                {
                    if (!isVideoLoaded)
                        currentFrame = (int)Math.Round(x);
                };

                frameSlider.GetValue = () => isVideoLoaded ? player.Video.CurrentFrame : currentFrame;
                frameSlider.IsDisabled = () => isVideoLoaded;
            }

            var frameText = panel.GetOrNull<LabelWidget>("FRAME_COUNT");
            if (frameText != null)
            {
                frameText.GetText = () =>
                    isVideoLoaded ?
                    "{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) :
                    "{0} / {1}".F(currentFrame + 1, currentSprites.Length);
            }

            var playButton = panel.GetOrNull<ButtonWidget>("BUTTON_PLAY");
            if (playButton != null)
            {
                playButton.OnClick = () =>
                {
                    if (isVideoLoaded)
                        player.Play();
                    else
                        animateFrames = true;
                };

                playButton.IsVisible = () => isVideoLoaded ? player.Paused : !animateFrames;
            }

            var pauseButton = panel.GetOrNull<ButtonWidget>("BUTTON_PAUSE");
            if (pauseButton != null)
            {
                pauseButton.OnClick = () =>
                {
                    if (isVideoLoaded)
                        player.Pause();
                    else
                        animateFrames = false;
                };

                pauseButton.IsVisible = () => isVideoLoaded ? !player.Paused : animateFrames;
            }

            var stopButton = panel.GetOrNull<ButtonWidget>("BUTTON_STOP");
            if (stopButton != null)
            {
                stopButton.OnClick = () =>
                {
                    if (isVideoLoaded)
                        player.Stop();
                    else
                    {
                        frameSlider.Value = 0;
                        currentFrame = 0;
                        animateFrames = false;
                    }
                };
            }

            var nextButton = panel.GetOrNull<ButtonWidget>("BUTTON_NEXT");
            if (nextButton != null)
            {
                nextButton.OnClick = () =>
                {
                    if (!isVideoLoaded)
                        nextButton.OnClick = SelectNextFrame;
                };

                nextButton.IsVisible = () => !isVideoLoaded;
            }

            var prevButton = panel.GetOrNull<ButtonWidget>("BUTTON_PREV");
            if (prevButton != null)
            {
                prevButton.OnClick = () =>
                {
                    if (!isVideoLoaded)
                        SelectPreviousFrame();
                };

                prevButton.IsVisible = () => !isVideoLoaded;
            }

            assetList = panel.Get<ScrollPanelWidget>("ASSET_LIST");
            template = panel.Get<ScrollItemWidget>("ASSET_TEMPLATE");
            PopulateAssetList();

            var closeButton = panel.GetOrNull<ButtonWidget>("CLOSE_BUTTON");
            if (closeButton != null)
                closeButton.OnClick = () =>
                {
                    if (isVideoLoaded)
                        player.Stop();
                    Ui.CloseWindow();
                    onExit();
                };
        }
Beispiel #26
0
        internal LobbyLogic([ObjectCreator.Param( "widget" )] Widget lobby,
		                    [ObjectCreator.Param] OrderManager orderManager,
		                    [ObjectCreator.Param] WorldRenderer worldRenderer)
        {
            this.orderManager = orderManager;
            this.worldRenderer = worldRenderer;
            this.lobby = lobby;
            Game.BeforeGameStart += CloseWindow;
            Game.LobbyInfoChanged += UpdateCurrentMap;
            Game.LobbyInfoChanged += UpdatePlayerList;
            UpdateCurrentMap();

            CurrentColorPreview = Game.Settings.Player.ColorRamp;

            Players = lobby.GetWidget<ScrollPanelWidget>("PLAYERS");
            LocalPlayerTemplate = Players.GetWidget("TEMPLATE_LOCAL");
            RemotePlayerTemplate = Players.GetWidget("TEMPLATE_REMOTE");
            EmptySlotTemplate = Players.GetWidget("TEMPLATE_EMPTY");
            EmptySlotTemplateHost = Players.GetWidget("TEMPLATE_EMPTY_HOST");
            LocalSpectatorTemplate = Players.GetWidget("TEMPLATE_LOCAL_SPECTATOR");
            RemoteSpectatorTemplate = Players.GetWidget("TEMPLATE_REMOTE_SPECTATOR");
            NewSpectatorTemplate = Players.GetWidget("TEMPLATE_NEW_SPECTATOR");

            var mapPreview = lobby.GetWidget<MapPreviewWidget>("LOBBY_MAP_PREVIEW");
            mapPreview.Map = () => Map;
            mapPreview.OnMouseDown = mi =>
            {
                var map = mapPreview.Map();
                if (map == null || mi.Button != MouseButton.Left
                    || orderManager.LocalClient.State == Session.ClientState.Ready)
                    return;

                var p = map.SpawnPoints
                    .Select((sp, i) => Pair.New(mapPreview.ConvertToPreview(map, sp), i))
                    .Where(a => (a.First - mi.Location).LengthSquared < 64)
                    .Select(a => a.Second + 1)
                    .FirstOrDefault();

                var owned = orderManager.LobbyInfo.Clients.Any(c => c.SpawnPoint == p);
                if (p == 0 || !owned)
                    orderManager.IssueOrder(Order.Command("spawn {0} {1}".F(orderManager.LocalClient.Index, p)));
            };

            mapPreview.SpawnColors = () =>
            {
                var spawns = Map.SpawnPoints;
                var sc = new Dictionary<int2, Color>();

                for (int i = 1; i <= spawns.Count(); i++)
                {
                    var client = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.SpawnPoint == i);
                    if (client == null)
                        continue;
                    sc.Add(spawns.ElementAt(i - 1), client.ColorRamp.GetColor(0));
                }
                return sc;
            };

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

            var mapButton = lobby.GetWidget<ButtonWidget>("CHANGEMAP_BUTTON");
            mapButton.OnClick = () =>
            {
                Widget.OpenWindow("MAP_CHOOSER", new WidgetArgs()
                {
                    { "orderManager", orderManager },
                    { "mapName", MapUid }
                });
            };

            mapButton.IsVisible = () => mapButton.Visible && Game.IsHost;

            var disconnectButton = lobby.GetWidget<ButtonWidget>("DISCONNECT_BUTTON");
            disconnectButton.OnClick = () =>
            {
                CloseWindow();
                Game.Disconnect();
                Game.LoadShellMap();
                Widget.OpenWindow("MAINMENU_BG");
            };

            var allowCheats = lobby.GetWidget<CheckboxWidget>("ALLOWCHEATS_CHECKBOX");
            allowCheats.IsChecked = () => orderManager.LobbyInfo.GlobalSettings.AllowCheats;
            allowCheats.OnClick = () =>
            {
                if (Game.IsHost)
                    orderManager.IssueOrder(Order.Command(
                        "allowcheats {0}".F(!orderManager.LobbyInfo.GlobalSettings.AllowCheats)));
            };

            var startGameButton = lobby.GetWidget<ButtonWidget>("START_GAME_BUTTON");
            startGameButton.OnClick = () =>
            {
                mapButton.Visible = false;
                disconnectButton.Visible = false;
                orderManager.IssueOrder(Order.Command("startgame"));
            };

            // Todo: Only show if the map requirements are met for player slots
            startGameButton.IsVisible = () => Game.IsHost;

            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;

                var order = (teamChat) ? Order.TeamChat(chatTextField.Text) : Order.Chat(chatTextField.Text);
                orderManager.IssueOrder(order);
                chatTextField.Text = "";
                return true;
            };

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

            Game.AddChatLine += AddChatLine;
        }
Beispiel #27
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)));
                });
        }
Beispiel #28
0
        public IngameChatLogic(Widget widget, OrderManager orderManager, World world, Ruleset modRules)
        {
            this.modRules = modRules;

            chatTraits = world.WorldActor.TraitsImplementing<INotifyChat>().ToList();

            var players = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant && !p.IsBot);
            var disableTeamChat = world.LocalPlayer == null || world.LobbyInfo.IsSinglePlayer || !players.Any(p => p.IsAlliedWith(world.LocalPlayer));
            teamChat = !disableTeamChat;

            var chatPanel = (ContainerWidget)widget;
            chatOverlay = chatPanel.Get<ContainerWidget>("CHAT_OVERLAY");
            chatOverlayDisplay = chatOverlay.Get<ChatDisplayWidget>("CHAT_DISPLAY");
            chatOverlay.Visible = false;

            chatChrome = chatPanel.Get<ContainerWidget>("CHAT_CHROME");
            chatChrome.Visible = true;

            var chatMode = chatChrome.Get<ButtonWidget>("CHAT_MODE");
            chatMode.GetText = () => teamChat ? "Team" : "All";
            chatMode.OnClick = () => teamChat ^= true;
            chatMode.IsDisabled = () => disableTeamChat;

            chatText = chatChrome.Get<TextFieldWidget>("CHAT_TEXTFIELD");
            chatText.OnTabKey = () =>
            {
                if (!disableTeamChat)
                    teamChat ^= true;
                return true;
            };
            chatText.OnEnterKey = () =>
            {
                var team = teamChat && !disableTeamChat;
                if (chatText.Text != "")
                    orderManager.IssueOrder(Order.Chat(team, chatText.Text.Trim()));

                CloseChat();
                return true;
            };

            chatText.OnEscKey = () => { CloseChat(); return true; };

            var chatClose = chatChrome.Get<ButtonWidget>("CHAT_CLOSE");
            chatClose.OnClick += () => CloseChat();

            chatPanel.OnKeyPress = (e) =>
            {
                if (e.Event == KeyInputEvent.Up)
                    return false;

                if (!chatChrome.IsVisible() && (e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER))
                {
                    OpenChat();
                    return true;
                }

                return false;
            };

            chatScrollPanel = chatChrome.Get<ScrollPanelWidget>("CHAT_SCROLLPANEL");
            chatTemplate = chatScrollPanel.Get<ContainerWidget>("CHAT_TEMPLATE");
            chatScrollPanel.RemoveChildren();

            Game.AddChatLine += AddChatLine;
            Game.BeforeGameStart += UnregisterEvents;

            CloseChat();
        }
Beispiel #29
0
        public InstallFromDiscLogic(Widget widget, ModContent content, Dictionary<string, ModContent.ModSource> sources, Action afterInstall)
        {
            this.content = content;
            this.sources = sources;

            Log.AddChannel("install", "install.log");

            // this.afterInstall = afterInstall;
            panel = widget.Get("DISC_INSTALL_PANEL");

            titleLabel = panel.Get<LabelWidget>("TITLE");

            primaryButton = panel.Get<ButtonWidget>("PRIMARY_BUTTON");
            secondaryButton = panel.Get<ButtonWidget>("SECONDARY_BUTTON");

            // Progress view
            progressContainer = panel.Get("PROGRESS");
            progressContainer.IsVisible = () => visible == Mode.Progress;
            progressBar = panel.Get<ProgressBarWidget>("PROGRESS_BAR");
            progressLabel = panel.Get<LabelWidget>("PROGRESS_MESSAGE");
            progressLabel.IsVisible = () => visible == Mode.Progress;

            // Message view
            messageContainer = panel.Get("MESSAGE");
            messageContainer.IsVisible = () => visible == Mode.Message;
            messageLabel = messageContainer.Get<LabelWidget>("MESSAGE_MESSAGE");

            // List view
            listContainer = panel.Get("LIST");
            listContainer.IsVisible = () => visible == Mode.List;

            listPanel = listContainer.Get<ScrollPanelWidget>("LIST_PANEL");
            listHeaderTemplate = listPanel.Get("LIST_HEADER_TEMPLATE");
            listTemplate = listPanel.Get<LabelWidget>("LIST_TEMPLATE");
            listPanel.RemoveChildren();

            listLabel = listContainer.Get<LabelWidget>("LIST_MESSAGE");

            DetectContentDisks();
        }
        public IngameChatLogic(Widget widget, OrderManager orderManager, World world)
        {
            World = world;
            var chatPanel = (ContainerWidget) widget;

            ChatOverlay = chatPanel.Get<ContainerWidget>("CHAT_OVERLAY");
            ChatOverlayDisplay = ChatOverlay.Get<ChatDisplayWidget>("CHAT_DISPLAY");
            ChatOverlay.Visible = false;

            ChatChrome = chatPanel.Get<ContainerWidget>("CHAT_CHROME");
            ChatChrome.Visible = true;

            var chatMode = ChatChrome.Get<ButtonWidget>("CHAT_MODE");
            chatMode.GetText = () => TeamChat ? "Team" : "All";
            chatMode.OnClick = () => TeamChat = !TeamChat;

            ChatText = ChatChrome.Get<TextFieldWidget>("CHAT_TEXTFIELD");
            ChatText.OnTabKey = () => { TeamChat = !TeamChat; return true; };
            ChatText.OnEnterKey = () =>
            {
                ChatText.Text = ChatText.Text.Trim();
                if (ChatText.Text != "")
                    orderManager.IssueOrder(Order.Chat(TeamChat, ChatText.Text));
                CloseChat();
                return true;
            };
            ChatText.OnEscKey = () => {CloseChat(); return true; };

            var chatClose = ChatChrome.Get<ButtonWidget>("CHAT_CLOSE");
            chatClose.OnClick += () => CloseChat();

            chatPanel.OnKeyPress = (e) =>
            {
                if (e.Event == KeyInputEvent.Up) return false;
                if (!IsOpen && (e.KeyName == "enter" || e.KeyName == "return") )
                {

                    var shift = e.Modifiers.HasModifier(Modifiers.Shift);
                    var toggle = Game.Settings.Game.TeamChatToggle ;
                    TeamChat = (!toggle && shift) || ( toggle &&  (TeamChat ^ shift) );
                    OpenChat();
                    return true;
                }

                return false;
            };

            ChatScrollPanel = ChatChrome.Get<ScrollPanelWidget>("CHAT_SCROLLPANEL");
            ChatTemplate = ChatScrollPanel.Get<ContainerWidget>("CHAT_TEMPLATE");

            Game.AddChatLine += AddChatLine;
            Game.BeforeGameStart += UnregisterEvents;

            CloseChat();
            ChatOverlayDisplay.AddLine(Color.White, null, "Use RETURN key to open chat window...");
        }
Beispiel #31
0
		public MissionBrowserLogic(Widget widget, World world, Action onStart, Action onExit)
		{
			this.onStart = onStart;

			missionList = widget.Get<ScrollPanelWidget>("MISSION_LIST");

			headerTemplate = widget.Get<ScrollItemWidget>("HEADER");
			template = widget.Get<ScrollItemWidget>("TEMPLATE");

			var title = widget.GetOrNull<LabelWidget>("MISSIONBROWSER_TITLE");
			if (title != null)
				title.GetText = () => playingVideo != PlayingVideo.None ? selectedMapPreview.Title : title.Text;

			widget.Get("MISSION_INFO").IsVisible = () => selectedMapPreview != null;

			var previewWidget = widget.Get<MapPreviewWidget>("MISSION_PREVIEW");
			previewWidget.Preview = () => selectedMapPreview;
			previewWidget.IsVisible = () => playingVideo == PlayingVideo.None;

			videoPlayer = widget.Get<VqaPlayerWidget>("MISSION_VIDEO");
			widget.Get("MISSION_BIN").IsVisible = () => playingVideo != PlayingVideo.None;
			fullscreenVideoPlayer = Ui.LoadWidget<BackgroundWidget>("FULLSCREEN_PLAYER", Ui.Root, new WidgetArgs { { "world", world } });

			descriptionPanel = widget.Get<ScrollPanelWidget>("MISSION_DESCRIPTION_PANEL");

			description = descriptionPanel.Get<LabelWidget>("MISSION_DESCRIPTION");
			descriptionFont = Game.Renderer.Fonts[description.Font];

			difficultyButton = widget.Get<DropDownButtonWidget>("DIFFICULTY_DROPDOWNBUTTON");
			gameSpeedButton = widget.GetOrNull<DropDownButtonWidget>("GAMESPEED_DROPDOWNBUTTON");

			startBriefingVideoButton = widget.Get<ButtonWidget>("START_BRIEFING_VIDEO_BUTTON");
			stopBriefingVideoButton = widget.Get<ButtonWidget>("STOP_BRIEFING_VIDEO_BUTTON");
			stopBriefingVideoButton.IsVisible = () => playingVideo == PlayingVideo.Briefing;
			stopBriefingVideoButton.OnClick = () => StopVideo(videoPlayer);

			startInfoVideoButton = widget.Get<ButtonWidget>("START_INFO_VIDEO_BUTTON");
			stopInfoVideoButton = widget.Get<ButtonWidget>("STOP_INFO_VIDEO_BUTTON");
			stopInfoVideoButton.IsVisible = () => playingVideo == PlayingVideo.Info;
			stopInfoVideoButton.OnClick = () => StopVideo(videoPlayer);

			var allMaps = new List<Map>();
			missionList.RemoveChildren();

			// Add a group for each campaign
			if (Game.ModData.Manifest.Missions.Any())
			{
				var yaml = Game.ModData.Manifest.Missions.Select(MiniYaml.FromFile).Aggregate(MiniYaml.MergeLiberal);

				foreach (var kv in yaml)
				{
					var missionMapPaths = kv.Value.Nodes.Select(n => Path.GetFullPath(n.Key));

					var maps = Game.ModData.MapCache
						.Where(p => p.Status == MapStatus.Available && missionMapPaths.Contains(Path.GetFullPath(p.Map.Path)))
						.Select(p => p.Map);

					CreateMissionGroup(kv.Key, maps);
					allMaps.AddRange(maps);
				}
			}

			// Add an additional group for loose missions
			var looseMissions = Game.ModData.MapCache
				.Where(p => p.Status == MapStatus.Available && p.Map.Visibility.HasFlag(MapVisibility.MissionSelector) && !allMaps.Contains(p.Map))
				.Select(p => p.Map);

			if (looseMissions.Any())
			{
				CreateMissionGroup("Missions", looseMissions);
				allMaps.AddRange(looseMissions);
			}

			if (allMaps.Any())
				SelectMap(allMaps.First());

			var startButton = widget.Get<ButtonWidget>("STARTGAME_BUTTON");
			startButton.OnClick = StartMissionClicked;
			startButton.IsDisabled = () => selectedMapPreview == null || selectedMapPreview.RuleStatus != MapRuleStatus.Cached;

			widget.Get<ButtonWidget>("BACK_BUTTON").OnClick = () =>
			{
				StopVideo(videoPlayer);
				Game.Disconnect();
				Ui.CloseWindow();
				onExit();
			};
		}