Esempio n. 1
0
 // Use this for initialization
 void Start()
 {
     _data_manager = GameObject.Find("DataManager").GetComponent<Datamanager>();
     _input_manager = GameObject.Find("InputManager").GetComponent<Inputmanager>();
     _input_manager.OnDoubleClickEvent += OnDoubleClick;
     _ui = GameObject.Find("UIManager").GetComponent<Ui>();
     _starblock = GetComponent<Starblock>();
 }
Esempio n. 2
0
    // Use this for initialization
    void Start()
    {
        Basics.assert(!instance);
        instance = this;

        debug = "_";
        dragSpeedCoefficient = 1f;
        keyboardScrollSpeed = 1000f;
    }
Esempio n. 3
0
        public void StartenKommandZeigtDieBefragenSeite()
        {
            dynamic expandoObject = new ExpandoObject();
            expandoObject.cmd = "Starten";

            // Json functionality available after NuGet installation and deinstallation of Microsoft.AspNet.Web.Helpers.Mvc 2.0.20710
            // System.Web.helpers v1.0.20105.407 is now available in lib-dir - but also not needed as reference.
            var json = JsonExtensions.ToJson(expandoObject);
            Console.WriteLine(json);
            //jsonObject.ToJson();

            var ui = new Ui();
            ui.Process(json);
        }
Esempio n. 4
0
        public ReplayBrowserLogic(Widget widget, ModData modData, Action onExit, Action onStart)
        {
            map   = MapCache.UnknownMap;
            panel = widget;

            services              = modData.Manifest.Get <WebServices>();
            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 || map.Status != MapStatus.Available;
            watch.OnClick    = () => { WatchReplay(); };

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

            Ui.LoadWidget("MAP_PREVIEW", panel.Get("MAP_PREVIEW_ROOT"), new WidgetArgs
            {
                { "orderManager", null },
                { "getMap", (Func <MapPreview>)(() => map) },
                { "onMouseDown", (Action <MapPreviewWidget, MapPreview, MouseInput>)((preview, mapPreview, mi) => { }) },
                { "getSpawnOccupants", (Func <MapPreview, Dictionary <CPos, SpawnOccupant> >)(mapPreview =>
                                                                                              LobbyUtils.GetSpawnOccupants(selectedReplay.GameInfo.Players, mapPreview)) },
                { "showUnoccupiedSpawnpoints", false },
            });

            var replayDuration = new CachedTransform <ReplayMetadata, string>(r =>
                                                                              "Duration: {0}".F(WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds)));

            panel.Get <LabelWidget>("DURATION").GetText = () => replayDuration.Update(selectedReplay);

            SetupFilters();
            SetupManagement();
        }
Esempio n. 5
0
 public void OnClick_Play()
 {
     Ui.Show <UiInGame>();
 }
    internal void ShowRtmpUi()
    {
        DrawTitle("REAL-TIME MULTIPLAYER");
        DrawStatus();

        if (GUI.Button(CalcGrid(0, 1), "Quick Game 2p"))
        {
            DoQuickGame(2);
        }
        else if (GUI.Button(CalcGrid(0, 2), "Create Game"))
        {
            DoCreateGame();
        }
        else if (GUI.Button(CalcGrid(0, 3), "From Inbox"))
        {
            DoAcceptFromInbox();
        }
        else if (GUI.Button(CalcGrid(1, 1), "Broadcast msg"))
        {
            DoBroadcastMessage();
        }
        else if (GUI.Button(CalcGrid(0, 4), "Send msg"))
        {
            DoSendMessage();
        }
        else if (GUI.Button(CalcGrid(1, 2), "Who Is Here"))
        {
            DoListParticipants();
        }
        else if (GUI.Button(CalcGrid(1, 3), "Accept incoming"))
        {
            DoAcceptIncoming();
        }
        else if (GUI.Button(CalcGrid(1, 4), "Decline incoming"))
        {
            DoDeclineIncoming();
        }
        else if (GUI.Button(CalcGrid(0, 5), "Leave Room"))
        {
            DoLeaveRoom();
        }
        else if (GUI.Button(CalcGrid(1, 5), "Back"))
        {
            mUi = Ui.Multiplayer;
        }
    }
    internal void ShowNotAuthUi()
    {
        this.DrawTitle(null);
        this.DrawStatus();
        if (GUI.Button(this.CalcGrid(0, 1), "Authenticate"))
        {
            this.DoAuthenticate();
        }

        if (GUI.Button(this.CalcGrid(1, 1), "Nearby Connections"))
        {
            this.mUi = Ui.NearbyConnections;
        }
    }
 public void SetUI(Ui page)
 {
     this.mUi = page;
 }
 private void DoTbmpQuickGame()
 {
     SetStandBy("Creating TBMP quick match...");
     PlayGamesPlatform.Instance.TurnBased.CreateQuickMatch(
         1,
         1,
         0,
         (bool success, TurnBasedMatch match) =>
         {
             ShowEffect(success);
             EndStandBy();
             mMatch = match;
             mStatus = success ? "Match created" : "Match creation failed";
             if (success)
             {
                 mUi = Ui.TbmpMatch;
             }
         });
 }
    private void DoTbmpAckFinish()
    {
        if (mMatch == null)
        {
            mStatus = "No match is active.";
            return;
        }

        if (mMatch.Status != TurnBasedMatch.MatchStatus.Complete)
        {
            mStatus = "Match is not complete";
            return;
        }

        SetStandBy("Ack'ing finished match");
        PlayGamesPlatform.Instance.TurnBased.AcknowledgeFinished(
            mMatch,
            (bool success) =>
            {
                EndStandBy();
                ShowEffect(success);
                mStatus = success ? "Successfully ack'ed finish." : "Failed to ack finish.";
                if (success)
                {
                    mMatch = null;
                    mUi = Ui.Tbmp;
                }
            });
    }
Esempio n. 11
0
        public static void InitializeMod(string mod, Arguments args)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => { };
            ConnectionStateChanged = om => { };
            BeforeGameStart        = () => { };
            Ui.ResetAll();

            worldRenderer = null;
            if (server != null)
            {
                server.Shutdown();
            }
            if (orderManager != null)
            {
                orderManager.Dispose();
            }

            // Fall back to default if the mod doesn't exist
            if (!ModMetadata.AllMods.ContainsKey(mod))
            {
                mod = new GameSettings().Mod;
            }

            Console.WriteLine("Loading mod: {0}", mod);
            Settings.Game.Mod = mod;

            Sound.StopMusic();
            Sound.StopVideo();
            Sound.Initialize();

            modData = new ModData(mod);
            Renderer.InitializeFonts(modData.Manifest);
            modData.InitializeLoaders();
            using (new PerfTimer("LoadMaps"))
                modData.MapCache.LoadMaps();

            PerfHistory.items["render"].hasNormalTick         = false;
            PerfHistory.items["batches"].hasNormalTick        = false;
            PerfHistory.items["render_widgets"].hasNormalTick = false;
            PerfHistory.items["render_flip"].hasNormalTick    = false;

            JoinLocal();

            if (Settings.Server.Dedicated)
            {
                while (true)
                {
                    Settings.Server.Map = WidgetUtils.ChooseInitialMap(Settings.Server.Map);
                    Settings.Save();
                    CreateServer(new ServerSettings(Settings.Server));
                    while (true)
                    {
                        Thread.Sleep(100);

                        if (server.State == Server.ServerState.GameStarted && server.Conns.Count < 1)
                        {
                            Console.WriteLine("No one is playing, shutting down...");
                            server.Shutdown();
                            break;
                        }
                    }

                    if (Settings.Server.DedicatedLoop)
                    {
                        Console.WriteLine("Starting a new server instance...");
                        modData.MapCache.LoadMaps();
                        continue;
                    }

                    break;
                }

                Environment.Exit(0);
            }
            else
            {
                var window = args != null?args.GetValue("Launch.Window", null) : null;

                if (!string.IsNullOrEmpty(window))
                {
                    var installData = modData.Manifest.ContentInstaller;
                    if (installData.InstallerBackgroundWidget != null)
                    {
                        Ui.LoadWidget(installData.InstallerBackgroundWidget, Ui.Root, new WidgetArgs());
                    }

                    Widgets.Ui.OpenWindow(window, new WidgetArgs());
                }
                else
                {
                    modData.LoadScreen.StartGame();
                    Settings.Save();
                    var replay = args != null?args.GetValue("Launch.Replay", null) : null;

                    if (!string.IsNullOrEmpty(replay))
                    {
                        Game.JoinReplay(replay);
                    }
                }
            }
        }
Esempio n. 12
0
 public override void Content(Ui ui, List <IdentityApplication> model)
 {
 }
Esempio n. 13
0
 private void Begin()
 {
     Sequence.Begin(0, this);
     Ui.Begin();
 }
Esempio n. 14
0
 public void Dispose()
 {
     Ui?.Dispose();
 }
Esempio n. 15
0
 public VirtualResolver(IServiceProvider inner, Ui ui)
 {
     _inner = inner;
     _ui    = ui;
 }
Esempio n. 16
0
        public MusicPlayerLogic(Widget widget, ModData modData, World world, Action onExit)
        {
            var panel = widget;

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

            BuildMusicTable();

            Func <bool> noMusic = () => !musicPlaylist.IsMusicAvailable || musicPlaylist.CurrentSongIsBackground || currentSong == null;

            panel.Get("NO_MUSIC_LABEL").IsVisible = () => !musicPlaylist.IsMusicAvailable;

            if (musicPlaylist.IsMusicAvailable)
            {
                panel.Get <LabelWidget>("MUTE_LABEL").GetText = () =>
                {
                    if (Game.Settings.Sound.Mute)
                    {
                        return("Audio has been muted in settings.");
                    }

                    return("");
                };
            }

            var playButton = panel.Get <ButtonWidget>("BUTTON_PLAY");

            playButton.OnClick    = Play;
            playButton.IsDisabled = noMusic;
            playButton.IsVisible  = () => !Game.Sound.MusicPlaying;

            var pauseButton = panel.Get <ButtonWidget>("BUTTON_PAUSE");

            pauseButton.OnClick    = Game.Sound.PauseMusic;
            pauseButton.IsDisabled = noMusic;
            pauseButton.IsVisible  = () => Game.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;
            shuffleCheckbox.IsDisabled = () => musicPlaylist.CurrentSongIsBackground;

            var repeatCheckbox = panel.Get <CheckboxWidget>("REPEAT");

            repeatCheckbox.IsChecked  = () => Game.Settings.Sound.Repeat;
            repeatCheckbox.OnClick    = () => Game.Settings.Sound.Repeat ^= true;
            repeatCheckbox.IsDisabled = () => musicPlaylist.CurrentSongIsBackground;

            panel.Get <LabelWidget>("TIME_LABEL").GetText = () =>
            {
                if (currentSong == null || musicPlaylist.CurrentSongIsBackground)
                {
                    return("");
                }

                var seek         = Game.Sound.MusicSeekPosition;
                var minutes      = (int)seek / 60;
                var seconds      = (int)seek % 60;
                var totalMinutes = currentSong.Length / 60;
                var totalSeconds = currentSong.Length % 60;

                return("{0:D2}:{1:D2} / {2:D2}:{3:D2}".F(minutes, seconds, totalMinutes, totalSeconds));
            };

            var musicTitle = panel.GetOrNull <LabelWidget>("TITLE_LABEL");

            if (musicTitle != null)
            {
                musicTitle.GetText = () => currentSong != null ? currentSong.Title : "No song playing";
            }

            var musicSlider = panel.Get <SliderWidget>("MUSIC_SLIDER");

            musicSlider.OnChange += x => Game.Sound.MusicVolume = x;
            musicSlider.Value     = Game.Sound.MusicVolume;

            var songWatcher = widget.GetOrNull <LogicTickerWidget>("SONG_WATCHER");

            if (songWatcher != null)
            {
                songWatcher.OnTick = () =>
                {
                    if (musicPlaylist.CurrentSongIsBackground && currentSong != null)
                    {
                        currentSong = null;
                    }

                    if (Game.Sound.CurrentMusic == null || currentSong == Game.Sound.CurrentMusic || musicPlaylist.CurrentSongIsBackground)
                    {
                        return;
                    }

                    currentSong = Game.Sound.CurrentMusic;
                };
            }

            var backButton = panel.GetOrNull <ButtonWidget>("BACK_BUTTON");

            if (backButton != null)
            {
                backButton.OnClick = () => { Game.Settings.Save(); Ui.CloseWindow(); onExit(); }
            }
            ;
        }
Esempio n. 17
0
 void OnGameStart()
 {
     Ui.CloseWindow();
     onStart();
 }
    internal void ShowTbmpUi()
    {
        DrawTitle("TURN-BASED MULTIPLAYER");
        DrawStatus();

        if (GUI.Button(CalcGrid(0, 1), "Quick Game 2p"))
        {
            DoTbmpQuickGame();
        }
        else if (GUI.Button(CalcGrid(0, 2), "Create Game"))
        {
            DoTbmpCreateGame();
        }
        else if (GUI.Button(CalcGrid(0, 3), "View all Matches"))
        {
            DoTbmpAcceptFromInbox();
        }
        else if (GUI.Button(CalcGrid(1, 1), "Accept incoming"))
        {
            DoTbmpAcceptIncoming();
        }
        else if (GUI.Button(CalcGrid(1, 2), "Decline incoming"))
        {
            DoTbmpDeclineIncoming();
        }
        else if (GUI.Button(CalcGrid(1, 3), "Match..."))
        {
            if (mMatch == null)
            {
                mStatus = "No match active.";
            }
            else
            {
                mUi = Ui.TbmpMatch;
            }
        }
        else if (GUI.Button(CalcGrid(1, 5), "Back"))
        {
            mUi = Ui.Multiplayer;
        }
    }
 private void DoTbmpAcceptFromInbox()
 {
     SetStandBy("Accepting TBMP from inbox...");
     PlayGamesPlatform.Instance.TurnBased.AcceptFromInbox((bool success, TurnBasedMatch match) =>
         {
             ShowEffect(success);
             EndStandBy();
             mMatch = match;
             mStatus = success ? "Successfully accepted from inbox!" : "Failed to accept from inbox";
             if (success)
             {
                 mUi = Ui.TbmpMatch;
             }
         });
 }
Esempio n. 20
0
        public MissionBrowserLogic(Widget widget, ModData modData, World world, Action onStart, Action onExit)
        {
            this.modData          = modData;
            this.onStart          = onStart;
            Game.BeforeGameStart += OnGameStart;

            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 ? selectedMap.Title : title.Text;
            }

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

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

            previewWidget.Preview   = () => selectedMap;
            previewWidget.IsVisible = () => playingVideo == PlayingVideo.None;

            videoPlayer = widget.Get <VideoPlayerWidget>("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 allPreviews = new List <MapPreview>();

            missionList.RemoveChildren();

            // Add a group for each campaign
            if (modData.Manifest.Missions.Any())
            {
                var yaml = MiniYaml.Merge(modData.Manifest.Missions.Select(
                                              m => MiniYaml.FromStream(modData.DefaultFileSystem.Open(m), m)));

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

                    var previews = modData.MapCache
                                   .Where(p => p.Class == MapClassification.System && p.Status == MapStatus.Available)
                                   .Select(p => new
                    {
                        Preview = p,
                        Index   = missionMapPaths.IndexOf(Path.GetFileName(p.Package.Name))
                    })
                                   .Where(x => x.Index != -1)
                                   .OrderBy(x => x.Index)
                                   .Select(x => x.Preview);

                    if (previews.Any())
                    {
                        CreateMissionGroup(kv.Key, previews);
                        allPreviews.AddRange(previews);
                    }
                }
            }

            // Add an additional group for loose missions
            var loosePreviews = modData.MapCache
                                .Where(p => p.Status == MapStatus.Available && p.Visibility.HasFlag(MapVisibility.MissionSelector) && !allPreviews.Any(a => a.Uid == p.Uid));

            if (loosePreviews.Any())
            {
                CreateMissionGroup("Missions", loosePreviews);
                allPreviews.AddRange(loosePreviews);
            }

            if (allPreviews.Any())
            {
                SelectMap(allPreviews.First());
            }

            // Preload map preview to reduce jank
            new Thread(() =>
            {
                foreach (var p in allPreviews)
                {
                    p.GetMinimap();
                }
            }).Start();

            var startButton = widget.Get <ButtonWidget>("STARTGAME_BUTTON");

            startButton.OnClick    = StartMissionClicked;
            startButton.IsDisabled = () => selectedMap == null;

            widget.Get <ButtonWidget>("BACK_BUTTON").OnClick = () =>
            {
                StopVideo(videoPlayer);
                Game.Disconnect();
                Ui.CloseWindow();
                onExit();
            };
        }
    private void DoTbmpFinish()
    {
        if (mMatch == null)
        {
            mStatus = "No match is active.";
            return;
        }

        if (mMatch.TurnStatus != TurnBasedMatch.MatchTurnStatus.MyTurn)
        {
            mStatus = "Not my turn.";
            return;
        }

        // I win; every one else loses
        MatchOutcome outcome = new MatchOutcome();
        foreach (Participant p in mMatch.Participants)
        {
            if (p.ParticipantId.Equals(mMatch.SelfParticipantId))
            {
                outcome.SetParticipantResult(p.ParticipantId, MatchOutcome.ParticipantResult.Win, 1);
            }
            else
            {
                outcome.SetParticipantResult(p.ParticipantId, MatchOutcome.ParticipantResult.Loss, 2);
            }
        }

        SetStandBy("Finishing match...");
        PlayGamesPlatform.Instance.TurnBased.Finish(
            mMatch,
            System.Text.ASCIIEncoding.Default.GetBytes("the end!"),
            outcome,
            (bool success) =>
            {
                EndStandBy();
                ShowEffect(success);
                mStatus = success ? "Successfully finished match." : "Failed to finish match.";
                if (success)
                {
                    mMatch = null;
                    mUi = Ui.Tbmp;
                }
            });
    }
Esempio n. 22
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;

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

            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;

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

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

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

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

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

            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 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 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 classNames = new Dictionary <string, string>()
                {
                    { "none", "MCV Only" },
                    { "light", "Light Support" },
                    { "heavy", "Heavy Support" },
                };

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

                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>().ToArray();
                techLevel.IsVisible = () => techTraits.Length > 0;
                optionsBin.GetOrNull <LabelWidget>("TECHLEVEL_DESC").IsVisible = () => techTraits.Length > 0;
                techLevel.IsDisabled  = () => Map.Status != MapStatus.Available || Map.Map.Options.TechLevel != null || configurationDisabled() || techTraits.Length <= 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 = "Cancel";
            }

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

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

                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", DoNothing }
                });
            }

            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)));
                    }
                });
            }
        }
    private void DoTbmpTakeTurn()
    {
        if (mMatch == null)
        {
            mStatus = "No match is active.";
            return;
        }

        if (mMatch.TurnStatus != TurnBasedMatch.MatchTurnStatus.MyTurn)
        {
            mStatus = "Not my turn.";
            return;
        }

        SetStandBy("Taking turn...");
        PlayGamesPlatform.Instance.TurnBased.TakeTurn(
            mMatch,
            System.Text.ASCIIEncoding.Default.GetBytes(GenString()),
            GetNextToPlay(mMatch),
            (bool success) =>
            {
                EndStandBy();
                ShowEffect(success);
                mStatus = success ? "Successfully took turn." : "Failed to take turn.";
                if (success)
                {
                    mMatch = null;
                    mUi = Ui.Tbmp;
                }
            });
    }
Esempio n. 24
0
        public NewMapLogic(Action onExit, Action <string> onSelect, Ruleset modRules, Widget widget, World world)
        {
            panel = widget;

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

            var tilesetDropDown = panel.Get <DropDownButtonWidget>("TILESET");
            var tilesets        = modRules.TileSets.Select(t => t.Key).ToList();
            Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (option, template) =>
            {
                var item = ScrollItemWidget.Setup(template,
                                                  () => tilesetDropDown.Text == option,
                                                  () => { tilesetDropDown.Text = option; });
                item.Get <LabelWidget>("LABEL").GetText = () => option;
                return(item);
            };

            tilesetDropDown.Text    = tilesets.First();
            tilesetDropDown.OnClick = () =>
                                      tilesetDropDown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, tilesets, setupItem);

            var widthTextField  = panel.Get <TextFieldWidget>("WIDTH");
            var heightTextField = panel.Get <TextFieldWidget>("HEIGHT");

            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = () =>
            {
                var tileset = modRules.TileSets[tilesetDropDown.Text];
                var map     = Map.FromTileset(tileset);

                int width, height;
                int.TryParse(widthTextField.Text, out width);
                int.TryParse(heightTextField.Text, out height);

                // Require at least a 2x2 playable area so that the
                // ground is visible through the edge shroud
                width  = Math.Max(2, width);
                height = Math.Max(2, height);

                map.Resize(width + 2, height + tileset.MaxGroundHeight + 2);
                map.ResizeCordon(1, 1, width + 1, height + tileset.MaxGroundHeight + 1);
                map.PlayerDefinitions = new MapPlayers(map.Rules, map.SpawnPoints.Value.Length).ToMiniYaml();
                map.FixOpenAreas(modRules);

                var userMapFolder = Game.ModData.Manifest.MapFolders.First(f => f.Value == "User").Key;

                // Ignore optional flag
                if (userMapFolder.StartsWith("~"))
                {
                    userMapFolder = userMapFolder.Substring(1);
                }

                var mapDir = Platform.ResolvePath(userMapFolder);
                Directory.CreateDirectory(mapDir);
                var tempLocation = Path.Combine(mapDir, "temp") + ".oramap";
                map.Save(tempLocation);                 // TODO: load it right away and save later properly

                var newMap = new Map(tempLocation);
                Game.ModData.MapCache[newMap.Uid].UpdateFromMap(newMap, MapClassification.User);

                ConnectionLogic.Connect(System.Net.IPAddress.Loopback.ToString(),
                                        Game.CreateLocalServer(newMap.Uid),
                                        "",
                                        () => { Game.LoadEditor(newMap.Uid); },
                                        () => { Game.CloseServer(); onExit(); });
                onSelect(newMap.Uid);
            };
        }
    internal void ShowEditSavedGameName()
    {
        this.DrawTitle("EDIT SAVED GAME FILENAME");
        this.DrawStatus();

        this.mSavedGameFilename = GUI.TextArea(this.CalcGrid(0, 1), this.mSavedGameFilename);

        if (GUI.Button(this.CalcGrid(1, 7), "Back"))
        {
            this.mUi = Ui.SavedGame;
        }
    }
Esempio n. 26
0
 public UICirclePicture()
 {
     BackColor = Ui.GetApplicationBackgroundColor();
     SizeMode  = PictureBoxSizeMode.StretchImage;
 }
    internal void ShowRegularUi()
    {
        this.DrawTitle(null);
        this.DrawStatus();

        if (GUI.Button(this.CalcGrid(0, 1), "Ach Reveal"))
        {
            this.DoAchievementReveal();
        }
        else if (GUI.Button(this.CalcGrid(0, 2), "Ach Unlock"))
        {
            this.DoAchievementUnlock();
        }
        else if (GUI.Button(this.CalcGrid(0, 3), "Ach Increment"))
        {
            this.DoAchievementIncrement();
        }
        else if (GUI.Button(this.CalcGrid(0, 4), "Ach Show UI"))
        {
            this.DoAchievementUI();
        }

        if (GUI.Button(this.CalcGrid(1, 1), "Post Score"))
        {
            this.DoPostScore();
        }
        else if (GUI.Button(this.CalcGrid(1, 2), "LB Show UI"))
        {
            this.DoLeaderboardUI();
        }
        else if (GUI.Button(this.CalcGrid(1, 3), "Cloud Save"))
        {
            this.DoCloudSave();
        }
        else if (GUI.Button(this.CalcGrid(1, 4), "Cloud Load"))
        {
            this.DoCloudLoad();
        }

        if (GUI.Button(this.CalcGrid(0, 5), "Multiplayer"))
        {
            this.mUi = Ui.Multiplayer;
        }

        if (GUI.Button(this.CalcGrid(1, 5), "Quests / Events"))
        {
            this.mUi = Ui.QuestsAndEvents;
        }

        if (GUI.Button(this.CalcGrid(0, 6), "Saved Game"))
        {
            this.mUi = Ui.SavedGame;
        }

        if (GUI.Button(this.CalcGrid(1, 6), "Nearby Connections"))
        {
            this.mUi = Ui.NearbyConnections;
        }

        if (GUI.Button(this.CalcGrid(0, 7), "Sign Out"))
        {
            this.DoSignOut();
        }
    }
Esempio n. 28
0
        public void Command_AdminVehicle(Client player, string args = "")
        {
            Character charData = Account.GetPlayerData(player);

            if (charData == null)
            {
                return;
            }
            if (charData.AdminLevel == 0)
            {
                return;
            }
            const string legend =
                "/av [uid, stworz, edytuj, usun, tm, to, spawn, napraw, kolor1, kolor2, pj, przypisz, przeszukaj, " +
                "respawn, parkuj, mods, info, paliwo]";

            string[] arguments = Command.GetCommandArguments(args);
            if (arguments.Length < 1)
            {
                Ui.ShowUsage(player, legend);
                return;
            }

            string option = arguments[0].ToLower();

            if (option == "uid")
            {
                Vehicle vehicleFound = Library.GetNearestVehicle(player.Position, player.Dimension);
                if (vehicleFound == null)
                {
                    Ui.ShowError(player, "Nie znaleziono żadnego pojazdu obok Ciebie.");
                    return;
                }

                Player.SendFormattedChatMessage(player,
                                                $"Znaleziony pojazd: (UID: {vehicleFound.Id}) {vehicleFound.Name}", Constants.ColorDelRio);
            }
            else if (option == "info")
            {
                if (player.IsInVehicle)
                {
                    Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                    if (vehData == null)
                    {
                        Ui.ShowError(player, "Nie znaleziono takiego pojazdu.");
                        return;
                    }

                    Library.ShowUi(charData, UiType.VehicleInfo, vehData.Id);
                }
                else
                {
                    if (arguments.Length - 1 < 1)
                    {
                        Ui.ShowUsage(player, "/av info [ID pojazdu]");
                        return;
                    }

                    int vehId = Command.GetNumberFromString(arguments[1]);
                    if (vehId == Command.InvalidNumber)
                    {
                        Ui.ShowError(player, "Podano błędne dane.");
                        return;
                    }

                    Vehicle vehData = Library.GetVehicleData(vehId);
                    if (vehData == null)
                    {
                        Ui.ShowError(player, "Nie znaleziono takiego pojazdu.");
                        return;
                    }

                    Library.ShowUi(charData, UiType.VehicleInfo, vehData.Id);
                }
            }
            else if (option == "paliwo")
            {
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                vehData.Fuel = vehData.MaxFuel;
                vehData.Save();

                Ui.ShowInfo(player, "Pojazd został napełniony.");
            }
            else if (option == "handling")
            {
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                if (arguments.Length - 1 < 2)
                {
                    Ui.ShowUsage(player, "/av handling [typ] [wartość]");
                }

                string type  = arguments[1].ToUpper();
                double value = Command.GetDoubleFromString(arguments[2]);

                if (vehData.TestHandling.ContainsKey(type))
                {
                    vehData.TestHandling.Remove(type);
                }

                vehData.TestHandling.Add(type, value);
                Library.SyncVehicleForPlayer(null, vehData.VehicleHandle.Value);
                Ui.ShowInfo(player, $"Zmieniono wartość \"{type}\" na \"{value}\".");
            }
            else if (option == "mods")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesColor, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                using (Database.Database db = new Database.Database())
                {
                    List <VehicleMod> mods = db.VehicleMods.Where(t => t.VehicleId == vehData.Id).ToList();
                    if (mods.Count == 0)
                    {
                        Ui.ShowInfo(player, "Pojazd nie posiada żadnych modyfikacji.");
                        return;
                    }

                    List <DialogColumn> dialogColumns = new List <DialogColumn>
                    {
                        new DialogColumn("ID Modyfikacji", 40),
                        new DialogColumn("Wartość modyfikacji", 40)
                    };

                    List <DialogRow> dialogRows = new List <DialogRow>();
                    foreach (VehicleMod entry in mods)
                    {
                        dialogRows.Add(new DialogRow(null, new[] { entry.ModId.ToString(), entry.ModVal.ToString() }));
                    }

                    string[] dialogButtons = { "Wybierz", "Zamknij" };

                    Dialogs.Library.CreateDialog(player, DialogId.None, "Zainstalowane modyfikacje", dialogColumns,
                                                 dialogRows, dialogButtons);
                }
            }
            else if (option == "rmods")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesColor, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                for (int i = 0; i < 76; i++)
                {
                    NAPI.Vehicle.SetVehicleMod(vehData.VehicleHandle, i, -1);
                }

                using (Database.Database db = new Database.Database())
                {
                    List <VehicleMod> vehMods = db.VehicleMods.Where(t => t.VehicleId == vehData.Id).ToList();
                    foreach (VehicleMod entry in vehMods)
                    {
                        NAPI.Vehicle.SetVehicleMod(vehData.VehicleHandle, (int)entry.ModId, entry.ModVal);
                    }
                }
            }
            else if (option == "stworz")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehicleCreate, true))
                {
                    return;
                }
                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av stworz [nazwa pojazdu]");
                    return;
                }

                uint?vehicleHash = Library.GetVehicleHashByName(arguments[1].ToLower());
                if (vehicleHash == null)
                {
                    Ui.ShowError(player, "Nie znaleziono takiego pojazdu.");
                    return;
                }

                Vector3 posInFrontOf = Global.GetPositionInFrontOf(player.Position, player.Heading, 5.0f);
                Vehicle vehicle      = Library.CreateVehicle((long)vehicleHash, posInFrontOf,
                                                             new Vector3(0, 0, player.Heading + 90), 0, 0, OwnerType.Player, (int)player.Dimension, charData.Id,
                                                             Command.UpperFirst(arguments[1], false), Player.GetPlayerDebugName(charData));

                Player.SendFormattedChatMessage(player, $"Utworzono pojazd \"{vehicle.Name}\" (UID: {vehicle.Id})",
                                                Constants.ColorDarkRed);
            }
            else if (option == "edytuj")
            {
                Vehicle vehData;
                if (player.IsInVehicle)
                {
                    vehData = Library.GetVehicleData(player.Vehicle);
                    if (vehData == null)
                    {
                        Ui.ShowError(player, "Nie znaleziono pojazdu o podanym ID.");
                        return;
                    }

                    Library.ShowUi(charData, UiType.VehicleEditAdmin, vehData.Id);
                    return;
                }

                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehicleCreate, true))
                {
                    return;
                }
                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av edytuj [id pojazdu]");
                    return;
                }

                int vehId = Command.GetNumberFromString(arguments[1]);
                if (vehId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano niepoprawne UID pojazdu.");
                    return;
                }

                vehData = Library.GetVehicleData(vehId);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Nie znaleziono pojazdu o podanym ID.");
                    return;
                }

                Library.ShowUi(charData, UiType.VehicleEditAdmin, vehData.Id);
            }
            else if (option == "usun")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehicleDelete, true))
                {
                    return;
                }
                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av usun [id pojazdu]");
                    return;
                }

                int vehId = Command.GetNumberFromString(arguments[1]);
                if (vehId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano niepoprawne UID pojazdu");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(vehId);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd o takim UID nie istnieje.");
                    return;
                }

                Player.SendFormattedChatMessage(player,
                                                $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został usunięty.", Constants.ColorDarkRed);
                Library.DestroyVehicle(vehData.Id);
            }
            else if (option == "to")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesTeleport, true))
                {
                    return;
                }
                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av to [id pojazdu]");
                    return;
                }

                int vehId = Command.GetNumberFromString(arguments[1]);
                if (vehId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano niepoprawne UID pojazdu.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(vehId);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Nie znaleziono pojazdu o podanym ID.");
                    return;
                }

                if (!vehData.Spawned || vehData.VehicleHandle == null ||
                    !NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                {
                    Ui.ShowError(player, "Pojazd nie jest zespawnowany.");
                    return;
                }

                player.Position = new Vector3(vehData.VehicleHandle.Position.X - 2.5,
                                              vehData.VehicleHandle.Position.Y - 2.5, vehData.VehicleHandle.Position.Z);
                player.Dimension = vehData.VehicleHandle.Dimension;

                Player.SendFormattedChatMessage(player,
                                                $"Teleportowałeś się do pojazdu \"{vehData.Name}\" (UID: {vehData.Id}).", Constants.ColorDelRio);
            }
            else if (option == "tm")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesTeleport, true))
                {
                    return;
                }
                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av tm [id pojazdu]");
                    return;
                }

                int vehId = Command.GetNumberFromString(arguments[1]);
                if (vehId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano niepoprawne UID pojazdu.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(vehId);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Nie znaleziono pojazdu o podanym ID.");
                    return;
                }

                if (!vehData.Spawned || vehData.VehicleHandle == null ||
                    !NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                {
                    Ui.ShowError(player, "Pojazd nie jest zespawnowany.");
                    return;
                }

                Vector3 newPosition = Global.GetPositionInFrontOf(player.Position, player.Heading, 5.0f);
                vehData.VehicleHandle.Position  = newPosition;
                vehData.VehicleHandle.Rotation  = new Vector3(0, 0, player.Heading + 90.0f);
                vehData.VehicleHandle.Dimension = player.Dimension;

                Player.SendFormattedChatMessage(player,
                                                $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został przeteleportowany do Ciebie.",
                                                Constants.ColorDelRio);
            }
            else if (option == "spawn")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesSpawn, true))
                {
                    return;
                }
                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av spawn [id pojazdu]");
                    return;
                }

                int vehId = Command.GetNumberFromString(arguments[1]);
                if (vehId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano niepoprawne UID pojazdu.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(vehId);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Nie znaleziono pojazdu o podanym ID.");
                    return;
                }

                if (!vehData.Spawned || vehData.VehicleHandle == null ||
                    !NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                {
                    Library.SpawnVehicle(vehData.Id);
                    Player.SendFormattedChatMessage(player,
                                                    $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został zespawnowany.", Constants.ColorDelRio);
                }
                else
                {
                    Library.UnspawnVehicle(vehData.Id);
                    Player.SendFormattedChatMessage(player,
                                                    $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został odspawnowany.", Constants.ColorDelRio);
                }
            }
            else if (option == "parkuj")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesPark, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                Library.ParkVehicle(charData.PlayerHandle, vehData, player.Vehicle.Position, player.Vehicle.Rotation,
                                    (int)player.Dimension);
            }
            else if (option == "napraw")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesFix, true))
                {
                    return;
                }
                if (player.IsInVehicle)
                {
                    Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                    if (vehData == null)
                    {
                        Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                        return;
                    }

                    vehData.Health = 1000.0f;
                    vehData.Save();

                    if (vehData.Spawned && vehData.VehicleHandle != null &&
                        NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                    {
                        vehData.VehicleHandle.Repair();
                    }

                    Player.SendFormattedChatMessage(player,
                                                    $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został naprawiony.", Constants.ColorDelRio);
                }
                else
                {
                    if (arguments.Length - 1 < 1)
                    {
                        Ui.ShowUsage(player, "/av napraw [id pojazdu]");
                        return;
                    }

                    int vehId = Command.GetNumberFromString(arguments[1]);
                    if (vehId == Command.InvalidNumber)
                    {
                        Ui.ShowError(player, "Podano niepoprawne UID pojazdu.");
                        return;
                    }

                    Vehicle vehData = Library.GetVehicleData(vehId);
                    if (vehData == null)
                    {
                        Ui.ShowError(player, "Nie znaleziono pojazdu o podanym ID.");
                        return;
                    }

                    vehData.Health = 1000.0f;
                    vehData.Save();

                    if (vehData.Spawned && vehData.VehicleHandle != null &&
                        NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                    {
                        vehData.VehicleHandle.Repair();
                    }

                    Player.SendFormattedChatMessage(player,
                                                    $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został naprawiony.", Constants.ColorDelRio);
                }
            }
            else if (option == "kolor1")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesColor, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av kolor1 [id koloru]");
                    return;
                }

                int colorId = Command.GetNumberFromString(arguments[1]);
                if (colorId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano nieprawidłowy kolor pojazdu.");
                    return;
                }

                vehData.FirstColor = colorId;

                if (vehData.Spawned && vehData.VehicleHandle != null &&
                    NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                {
                    vehData.VehicleHandle.PrimaryColor = vehData.FirstColor;
                }

                Player.SendFormattedChatMessage(player,
                                                $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został przemalowany.", Constants.ColorDelRio);
            }
            else if (option == "kolor2")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesColor, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av kolor2 [id koloru]");
                    return;
                }

                int colorId = Command.GetNumberFromString(arguments[1]);
                if (colorId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano nieprawidłowy kolor pojazdu.");
                    return;
                }

                vehData.SecondColor = colorId;

                if (vehData.Spawned && vehData.VehicleHandle != null &&
                    NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                {
                    vehData.VehicleHandle.SecondaryColor = vehData.SecondColor;
                }

                Player.SendFormattedChatMessage(player,
                                                $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został przemalowany.", Constants.ColorDelRio);
            }
            else if (option == "pj")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesPj, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av pj [id paintjobu]");
                    return;
                }

                int liveryId = Command.GetNumberFromString(arguments[1]);
                if (liveryId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano nieprawidłowe id paintjobu.");
                    return;
                }

                vehData.Livery = liveryId;
                vehData.Save();

                if (vehData.Spawned && vehData.VehicleHandle != null &&
                    NAPI.Entity.DoesEntityExist(vehData.VehicleHandle))
                {
                    vehData.VehicleHandle.Livery = vehData.Livery;
                    Library.SyncVehicleForPlayer(null, vehData.VehicleHandle.Value, "livery", vehData.Livery);
                }

                Player.SendFormattedChatMessage(player,
                                                $"Pojazd \"{vehData.Name}\" (UID: {vehData.Id}) został przemalowany.", Constants.ColorDelRio);
            }
            else if (option == "przypisz")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesAssign, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                if (arguments.Length - 1 < 2)
                {
                    Ui.ShowUsage(player, "/av przypisz [gracz, grupa] [Id właściciela]");
                    return;
                }

                int ownerId = Command.GetNumberFromString(arguments[2]);
                if (ownerId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano niepoprawne Id właściciela");
                    return;
                }

                string subOption = arguments[1].ToLower();
                if (subOption == "gracz")
                {
                    Character targetData = Account.GetPlayerDataByServerId(ownerId);
                    if (targetData == null)
                    {
                        Ui.ShowError(player, "Nie znaleziono gracza o podanym Id.");
                        return;
                    }

                    vehData.OwnerType = OwnerType.Player;
                    vehData.Owner     = targetData.Id;
                    vehData.Save();

                    Player.SendFormattedChatMessage(targetData.PlayerHandle,
                                                    $"Administrator przypisał Ci pojazd {Library.GetVehicleFormattedName(vehData)}.",
                                                    Constants.ColorPictonBlue);
                    Player.SendFormattedChatMessage(player,
                                                    $"Pojazd {Library.GetVehicleFormattedName(vehData)} został przypisany graczowi " +
                                                    $"{Player.GetPlayerIcName(targetData, true)}.", Constants.ColorDarkRed);
                }
                else if (subOption == "grupa")
                {
                    Group groupData = Groups.Library.GetGroupData(ownerId);
                    if (groupData == null)
                    {
                        Ui.ShowError(player, "Nie znaleziono grupy o podanym Id.");
                        return;
                    }

                    vehData.OwnerType = OwnerType.Group;
                    vehData.Owner     = groupData.Id;
                    vehData.Save();

                    Player.SendFormattedChatMessage(player,
                                                    $"Pojazd {Library.GetVehicleFormattedName(vehData)} został przypisany grupie " +
                                                    $"{groupData.Name} (UID: {groupData.Id})", Constants.ColorDarkRed);
                }
                else
                {
                    Ui.ShowUsage(player, "/av przypisz [gracz, grupa] [Id właściciela]");
                }
            }
            else if (option == "extra")
            {
                if (!Admin.Library.DoesPlayerHasAdminPerm(charData, Permissions.VehiclesPj, true))
                {
                    return;
                }
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Pojazd w którym siedzisz jest nieprawidłowym pojazdem.");
                    return;
                }

                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/av extra [id extrasu]");
                    return;
                }

                int extrasId = Command.GetNumberFromString(arguments[1]);
                if (extrasId == Command.InvalidNumber)
                {
                    Ui.ShowError(player, "Podano nieprawidłowe id extrasu.");
                    return;
                }

                if (vehData.MappedExtras == null)
                {
                    vehData.MappedExtras = new Dictionary <int, bool>();
                }

                if (vehData.MappedExtras.ContainsKey(extrasId))
                {
                    vehData.MappedExtras[extrasId] = !vehData.MappedExtras[extrasId];
                    Ui.ShowInfo(player, $"Zmieniono stan extrasu na {vehData.MappedExtras[extrasId].ToString()}.");
                }
                else
                {
                    vehData.MappedExtras.Add(extrasId, !vehData.VehicleHandle.GetExtra(extrasId));
                    Ui.ShowInfo(player, $"Zmieniono stan extrasu na {vehData.MappedExtras[extrasId].ToString()}.");
                }

                vehData.Save();
                vehData.RebuildExtras();
            }
        }
Esempio n. 29
0
        public void Update(Control control, Camera camera, Player player, NpcPackage npcs, Ui.FloatingTextCollection floatingText, ref Map map)
        {
            #region Initialize Weapons

            if (player.Inventory.Quickbar.UsingItem.Type == "useweapon")
            {
                ItemUse use = player.Inventory.Quickbar.UsingItem;
                Weapon weapon = GetWeaponById(int.Parse(use.Value));

                if (weapon.Type.Name == "Sword" && !player.Inventory.Quickbar.IsUsingItem)
                {
                    LiveWeapons.Add(new LiveSword(GetWeaponById(player.Inventory.Quickbar.UsingItem.IntValue),new Vector2(player.Movement.Area.Center.X, player.Movement.Area.Center.Y - 5), player.Movement.Direction));
                    player.Inventory.Quickbar.IsUsingItem = true;
                }

                if (weapon.Type.Name == "Arrow")
                {
                    if(control.currentMouse.LeftButton == ButtonState.Pressed){
                        if(!player.Inventory.Quickbar.IsUsingItem) {
                            player.Inventory.Quickbar.IsUsingItem = true;
                            use.Charge = 10f;
                        } else {
                            use.Charge += 0.1f;
                        }
                    } else {
                        LiveProjectile liveWeapon = new LiveProjectile(Weapons[2], new Vector2(player.Movement.Area.Center.X, player.Movement.Area.Center.Y), (float)use.Charge, control, camera);
                        use.Charge = 0;
                        LiveWeapons.Add(liveWeapon);
                        player.Inventory.Quickbar.IsUsingItem = false;
                        Player = player;
                    }
                }
            }

            #endregion

            #region Update weapons

            for ( int i = 0; i < LiveWeapons.Count; i++)
            {
                if (LiveWeapons[i].Weapon.Type.Name == "Sword")
                {
                    LiveSword weapon = LiveWeapons[i];
                    weapon.Rotation += LiveWeapons[i].Speed;
                    LiveWeapons[i].Location += player.Movement.Moved;
                    if ((LiveWeapons[i].SwingEnd > 0 && LiveWeapons[i].Rotation > LiveWeapons[i].SwingEnd) || (LiveWeapons[i].SwingEnd < 0 && LiveWeapons[i].Rotation < LiveWeapons[i].SwingEnd))
                    {
                        LiveWeapons.RemoveAt(i);
                        player.Inventory.Quickbar.IsUsingItem = false;
                    }
                } else if(LiveWeapons[i].Weapon.Type.Name == "Arrow")
                {
                    LiveProjectile weapon = LiveWeapons[i];
                    if (weapon.Movement.Velocity != Vector2.Zero)
                    {
                        weapon.Movement.Update(map);
                    }
                    else
                    {
                        weapon.TimeToLive -= 1;
                        if (weapon.TimeToLive <= 0) { LiveWeapons.RemoveAt(i); }
                    }
                }
            }

            #endregion

            #region Check for weapon collisions

            // Npc Collisions
            for (int w = 0; w < LiveWeapons.Count; w++)
            {

                var weapon = LiveWeapons[w];
                for (int i = 0; i < npcs.ActiveNpcs.Count; i++)
                {

                    if (weapon.Weapon.Type.Name == "Sword")
                    {
                        LiveSword sword = weapon;
                        if (weapon.currentLocation.Intersects(npcs.ActiveNpcs[i].Movement.Area))
                        {
                            if (npcs.Damage(npcs.ActiveNpcs[i], 10, weapon.Location))
                            {
                                floatingText.Add("10", weapon.Location);
                            }
                        }
                    }
                    else if(weapon.Weapon.Type.Name == "Arrow" && weapon.Movement.Velocity != Vector2.Zero)
                    {
                        LiveProjectile projectile = weapon;
                        if (projectile.Movement.Area.Intersects(npcs.ActiveNpcs[i].Movement.Area))
                        {
                            if (npcs.Damage(npcs.ActiveNpcs[i], 10, weapon.Location))
                            {
                                floatingText.Add("10", new Vector2(projectile.Movement.Area.Center.X, projectile.Movement.Area.Center.Y));
                                LiveWeapons.RemoveAt(w);
                            }
                        }
                    }
                }

                // X/Y Collisions
                int startx = (int)MathHelper.Clamp(camera.X * -1 / 24f, 0, map.SizeX);
                int endx = startx + camera.Width / 24;
                int starty = (int)MathHelper.Clamp(camera.Y * -1 / 24f, 0, map.SizeY);
                int endy = starty + camera.Height / 24;

                for (int x = startx; x < endx; x++)
                {
                    for (int y = starty; y < endy; y++)
                    {

                        Rectangle area = new Rectangle(x * 24, y * 24, 24,24);

                        if (map.Flora.Flora[x, y] != null)
                        {
                            if (weapon.Weapon.Type.Name == "Sword")
                            {
                                if (weapon.currentLocation.Intersects(area)) { map.Flora.Flora[x, y] = null; }
                            }
                            else if (weapon.Weapon.Type.Name == "Arrow")
                            {
                                if (weapon.Movement.Area.Intersects(area)) { map.Flora.Flora[x, y] = null; }
                            }
                        }

                    }
                }

            }

            #endregion
        }
    void ShowRegularUi()
    {
        DrawTitle(null);
        DrawStatus();

        if (GUI.Button(CalcGrid(0,1), "Ach Reveal")) {
            DoAchievementReveal();
        } else if (GUI.Button(CalcGrid(0,2), "Ach Unlock")) {
            DoAchievementUnlock();
        } else if (GUI.Button(CalcGrid(0,3), "Ach Increment")) {
            DoAchievementIncrement();
        } else if (GUI.Button(CalcGrid(0,4), "Ach Show UI")) {
            DoAchievementUI();
        }

        if (GUI.Button(CalcGrid(1,1), "Post Score")) {
            DoPostScore();
        } else if (GUI.Button(CalcGrid(1,2), "LB Show UI")) {
            DoLeaderboardUI();
        } else if (GUI.Button(CalcGrid(1,3), "Cloud Save")) {
            DoCloudSave();
        } else if (GUI.Button(CalcGrid(1,4), "Cloud Load")) {
            DoCloudLoad();
        }

        if (GUI.Button(CalcGrid(0,5), "Multiplayer")) {
            mUi = Ui.Multiplayer;
        }

        if (GUI.Button(CalcGrid(1,5), "Sign Out")) {
            DoSignOut();
        }
    }
Esempio n. 31
0
        public void Command_Vehicle(Client player, string args = "")
        {
            Character charData = Account.GetPlayerData(player);

            if (charData == null)
            {
                return;
            }
            const string legend = "/v [l(ista), z(amknij), (za)parkuj, maska, bagaznik]";

            string[] arguments = Command.GetCommandArguments(args);
            if (arguments.Length < 1)
            {
                Ui.ShowUsage(player, legend);
                return;
            }

            string option = arguments[0].ToLower();

            if (option == "lista" || option == "l")
            {
                Library.ShowUi(charData, UiType.VehiclesList, 0);
            }
            else if (option == "zamknij" || option == "z")
            {
                Vehicle vehData = Library.GetNearestVehicle(player.Position, player.Dimension);
                if (vehData == null)
                {
                    Ui.ShowWarning(player, "Nie znaleziono żadnego pojazdu obok Ciebie.");
                    return;
                }

                if (!Library.DoesPlayerHasVehiclePerm(charData, vehData.Id))
                {
                    Ui.ShowError(player, "Nie posiadasz kluczy do tego pojazdu.");
                    return;
                }

                if (vehData.Closed)
                {
                    vehData.Closed = false;
                    vehData.VehicleHandle.Locked = false;
                    Chat.Library.SendPlayerMeMessage(charData, $"otwiera drzwi pojazdu \"{vehData.Name}\".", true);
                }
                else
                {
                    vehData.Closed = true;
                    vehData.VehicleHandle.Locked = true;
                    Chat.Library.SendPlayerMeMessage(charData, $"zamyka drzwi pojazdu \"{vehData.Name}\".", true);
                }
            }
            else if (option == "zaparkuj" || option == "parkuj")
            {
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz być w pojeździe.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Nie znaleziono tego pojazdu.");
                    return;
                }

                if (!Library.DoesPlayerHasVehicleOwner(charData, vehData.Id))
                {
                    Ui.ShowError(player, "Nie posiadasz odpowiednich uprawnień.");
                    return;
                }

                vehData.X = vehData.VehicleHandle.Position.X;
                vehData.Y = vehData.VehicleHandle.Position.Y;
                vehData.Z = vehData.VehicleHandle.Position.Z;

                vehData.Rx = vehData.VehicleHandle.Rotation.X;
                vehData.Ry = vehData.VehicleHandle.Rotation.Y;
                vehData.Rz = vehData.VehicleHandle.Rotation.Z;

                vehData.Dimension = (int)vehData.VehicleHandle.Dimension;

                vehData.Save();

                Ui.ShowInfo(player, "Pojazd został zaparkowany pomyślnie.");
            }
            else if (option == "maska")
            {
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                if (player.VehicleSeat != -1)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe jako kierowca.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Niewłaściwy pojazd.");
                    return;
                }

                vehData.Hood = !vehData.Hood;
                foreach (KeyValuePair <int, Character> entry in Account.GetAllPlayers())
                {
                    NAPI.ClientEvent.TriggerClientEvent(entry.Value.PlayerHandle, "client.vehicle.sync.hood",
                                                        vehData.VehicleHandle.Value, vehData.Hood);
                }
            }
            else if (option == "bagaznik")
            {
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                if (player.VehicleSeat != -1)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe jako kierowca.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Niewłaściwy pojazd.");
                    return;
                }

                vehData.Trunk = !vehData.Trunk;
                foreach (KeyValuePair <int, Character> entry in Account.GetAllPlayers())
                {
                    NAPI.ClientEvent.TriggerClientEvent(entry.Value.PlayerHandle, "client.vehicle.sync.trunk",
                                                        vehData.VehicleHandle.Value, vehData.Trunk);
                }
            }
            else if (option == "opis")
            {
                if (!player.IsInVehicle)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe.");
                    return;
                }

                if (player.VehicleSeat != -1)
                {
                    Ui.ShowError(player, "Musisz siedzieć w pojeździe jako kierowca.");
                    return;
                }

                Vehicle vehData = Library.GetVehicleData(player.Vehicle);
                if (vehData == null)
                {
                    Ui.ShowError(player, "Niewłaściwy pojazd.");
                    return;
                }

                if (arguments.Length - 1 < 1)
                {
                    Ui.ShowUsage(player, "/v opis [tresc opisu] | Aby usunac opis wpisz /v opis usun");
                    return;
                }

                if (arguments[1].ToLower() == "usun")
                {
                    Library.SyncVehicleForPlayer(null, player.Vehicle.Value, "descdel", 0);
                    Ui.ShowInfo(player, "Opis pojazdu usunięty.");
                    vehData.VehicleDescription = null;
                    return;
                }

                vehData.VehicleDescription = Command.GetConcatString(arguments, 1);
                Library.SyncVehicleForPlayer(null, player.Vehicle.Value, "desc", vehData.VehicleDescription);
                Ui.ShowInfo(player, "Opis pojazdu został ustawiony.");
            }
        }
Esempio n. 32
0
        public virtual void StartGame(Arguments args)
        {
            Launch = new LaunchArguments(args);
            Ui.ResetAll();
            Game.Settings.Save();

            if (!string.IsNullOrEmpty(Launch.Benchmark))
            {
                Console.WriteLine("Saving benchmark data into {0}".F(Path.Combine(Platform.SupportDir, "Logs")));

                Game.BenchmarkMode(Launch.Benchmark);
            }

            // Join a server directly
            var connect = Launch.GetConnectAddress();

            if (!string.IsNullOrEmpty(connect))
            {
                var parts = connect.Split(':');

                if (parts.Length == 2)
                {
                    var host = parts[0];
                    var port = Exts.ParseIntegerInvariant(parts[1]);
                    Game.LoadShellMap();
                    Game.RemoteDirectConnect(host, port);
                    return;
                }
            }

            // Start a map directly
            if (!string.IsNullOrEmpty(Launch.Map))
            {
                Game.LoadMap(Launch.Map);
                return;
            }

            // Load a replay directly
            if (!string.IsNullOrEmpty(Launch.Replay))
            {
                ReplayMetadata replayMeta = null;
                try
                {
                    replayMeta = ReplayMetadata.Read(Launch.Replay);
                }
                catch { }

                if (ReplayUtils.PromptConfirmReplayCompatibility(replayMeta, Game.LoadShellMap))
                {
                    Game.JoinReplay(Launch.Replay);
                }

                if (replayMeta != null)
                {
                    var mod = replayMeta.GameInfo.Mod;
                    if (mod != null && mod != Game.ModData.Manifest.Id && Game.Mods.ContainsKey(mod))
                    {
                        Game.InitializeMod(mod, args);
                    }
                }

                return;
            }

            Game.LoadShellMap();
            Game.Settings.Save();
        }
    void DoTbmpLeave()
    {
        if (mMatch == null) {
            mStatus = "No match is active.";
            return;
        }
        if (mMatch.TurnStatus == TurnBasedMatch.MatchTurnStatus.MyTurn) {
            mStatus = "It's my turn; use 'Leave During Turn'.";
            return;
        }

        SetStandBy("Leaving match...");
        PlayGamesPlatform.Instance.TurnBased.Leave(mMatch.MatchId, (bool success) => {
            EndStandBy();
            ShowEffect(success);
            mStatus = success ? "Successfully left match." : "Failed to leave match.";
            if (success) {
                mMatch = null;
                mUi = Ui.Tbmp;
            }
        });
    }
Esempio n. 34
0
        public ConnectionSwitchModLogic(Widget widget, OrderManager orderManager, NetworkConnection connection, Action onAbort, Action <string> onRetry)
        {
            var panel        = widget;
            var abortButton  = panel.Get <ButtonWidget>("ABORT_BUTTON");
            var switchButton = panel.Get <ButtonWidget>("SWITCH_BUTTON");

            var mod        = CurrentServerSettings.ServerExternalMod;
            var modTitle   = mod.Title;
            var modVersion = mod.Version;

            switchButton.OnClick = () =>
            {
                var launchCommand = $"Launch.URI={new UriBuilder("tcp", connection.EndPoint.Address.ToString(), connection.EndPoint.Port)}";
                Game.SwitchToExternalMod(CurrentServerSettings.ServerExternalMod, new[] { launchCommand }, () =>
                {
                    orderManager.ServerError = "Failed to switch mod.";
                    Ui.CloseWindow();
                    Ui.OpenWindow("CONNECTIONFAILED_PANEL", new WidgetArgs()
                    {
                        { "orderManager", orderManager },
                        { "onAbort", onAbort },
                        { "onRetry", onRetry }
                    });
                });
            };

            abortButton.Visible = onAbort != null;
            abortButton.OnClick = () => { Ui.CloseWindow(); onAbort(); };

            var width = 0;
            var title = panel.GetOrNull <LabelWidget>("MOD_TITLE");

            if (title != null)
            {
                var font       = Game.Renderer.Fonts[title.Font];
                var label      = WidgetUtils.TruncateText(modTitle, title.Bounds.Width, font);
                var labelWidth = font.Measure(label).X;
                width = Math.Max(width, title.Bounds.X + labelWidth);
                title.Bounds.Width = labelWidth;
                title.GetText      = () => label;
            }

            var version = panel.GetOrNull <LabelWidget>("MOD_VERSION");

            if (version != null)
            {
                var font       = Game.Renderer.Fonts[version.Font];
                var label      = WidgetUtils.TruncateText(modVersion, version.Bounds.Width, font);
                var labelWidth = font.Measure(label).X;
                width = Math.Max(width, version.Bounds.X + labelWidth);
                version.Bounds.Width = labelWidth;
                version.GetText      = () => label;
            }

            var logo = panel.GetOrNull <RGBASpriteWidget>("MOD_ICON");

            if (logo != null)
            {
                logo.GetSprite = () =>
                {
                    var ws = Game.Renderer.WindowScale;
                    if (ws > 2 && mod.Icon3x != null)
                    {
                        return(mod.Icon3x);
                    }

                    if (ws > 1 && mod.Icon2x != null)
                    {
                        return(mod.Icon2x);
                    }

                    return(mod.Icon);
                };

                if (mod.Icon == null)
                {
                    // Hide the logo and center just the text
                    if (title != null)
                    {
                        title.Bounds.X = logo.Bounds.X;
                    }

                    if (version != null)
                    {
                        version.Bounds.X = logo.Bounds.X;
                    }

                    width -= logo.Bounds.Width;
                }
                else
                {
                    // Add an equal logo margin on the right of the text
                    width += logo.Bounds.Width;
                }
            }

            var container = panel.GetOrNull("MOD_CONTAINER");

            if (container != null)
            {
                container.Bounds.X    += (container.Bounds.Width - width) / 2;
                container.Bounds.Width = width;
            }
        }
    internal void ShowTbmpMatchUi()
    {
        DrawTitle("TURN-BASED MULTIPLAYER MATCH\n" + GetMatchSummary());
        DrawStatus();

        if (GUI.Button(CalcGrid(0, 1), "Match Data"))
        {
            DoTbmpShowMatchData();
        }
        else if (GUI.Button(CalcGrid(0, 2), "Take Turn"))
        {
            DoTbmpTakeTurn();
        }
        else if (GUI.Button(CalcGrid(0, 3), "Finish"))
        {
            DoTbmpFinish();
        }
        else if (GUI.Button(CalcGrid(0, 4), "Ack Finish"))
        {
            DoTbmpAckFinish();
        }
        else if (GUI.Button(CalcGrid(0, 5), "Max Data Size"))
        {
            mStatus = PlayGamesPlatform.Instance.TurnBased.GetMaxMatchDataSize() + " bytes";
        }
        else if (GUI.Button(CalcGrid(1, 1), "Leave"))
        {
            DoTbmpLeave();
        }
        else if (GUI.Button(CalcGrid(1, 2), "Leave During Turn"))
        {
            DoTbmpLeaveDuringTurn();
        }
        else if (GUI.Button(CalcGrid(1, 3), "Cancel"))
        {
            DoTbmpCancel();
        }
        else if (GUI.Button(CalcGrid(1, 4), "Rematch"))
        {
            DoTbmpRematch();
        }
        else if (GUI.Button(CalcGrid(1, 5), "Back"))
        {
            mUi = Ui.Tbmp;
        }
    }
Esempio n. 36
0
 void CloseWindow()
 {
     Game.ConnectionStateChanged -= ConnectionStateChanged;
     Ui.CloseWindow();
 }
    internal void ShowWriteSavedGame()
    {
        DrawTitle("WRITE SAVED GAME");
        DrawStatus();

        mSavedGameFileContent = GUI.TextArea(CalcGrid(0, 1), mSavedGameFileContent);

        if (mCurrentSavedGame == null || !mCurrentSavedGame.IsOpen)
        {
            mStatus = "No opened saved game selected.";
            mUi = Ui.SavedGame;
            return;
        }

        var update = new SavedGameMetadataUpdate.Builder()
            .WithUpdatedDescription("Saved at " + DateTime.Now.ToString())
            .WithUpdatedPlayedTime(mCurrentSavedGame.TotalTimePlayed.Add(TimeSpan.FromHours(1)))
            .Build();

        if (GUI.Button(CalcGrid(0, 7), "Write"))
        {
            SetStandBy("Writing update");
            PlayGamesPlatform.Instance.SavedGame.CommitUpdate(
                mCurrentSavedGame,
                update,
                System.Text.ASCIIEncoding.Default.GetBytes(mSavedGameFileContent),
                (status, updated) =>
                {
                    mStatus = "Write status was: " + status;
                    mUi = Ui.SavedGame;
                    EndStandBy();
                });
            mCurrentSavedGame = null;
        }
        else if (GUI.Button(CalcGrid(1, 7), "Cancel"))
        {
            mUi = Ui.SavedGame;
        }
    }
Esempio n. 38
0
        public ConnectionFailedLogic(Widget widget, OrderManager orderManager, NetworkConnection connection, string password, Action onAbort, Action <string> onRetry)
        {
            var panel       = widget;
            var abortButton = panel.Get <ButtonWidget>("ABORT_BUTTON");
            var retryButton = panel.Get <ButtonWidget>("RETRY_BUTTON");

            abortButton.Visible = onAbort != null;
            abortButton.OnClick = () => { Ui.CloseWindow(); onAbort(); };

            retryButton.Visible = onRetry != null;
            retryButton.OnClick = () =>
            {
                var pass = passwordField != null && passwordField.IsVisible() ? passwordField.Text : password;

                Ui.CloseWindow();
                onRetry(pass);
            };

            widget.Get <LabelWidget>("CONNECTING_DESC").GetText = () => $"Could not connect to {connection.Target}";

            var connectionError = widget.Get <LabelWidget>("CONNECTION_ERROR");

            connectionError.GetText = () => orderManager.ServerError ?? connection.ErrorMessage ?? "Unknown error";

            var panelTitle = widget.Get <LabelWidget>("TITLE");

            panelTitle.GetText = () => orderManager.AuthenticationFailed ? "Password Required" : "Connection Failed";

            passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");
            if (passwordField != null)
            {
                passwordField.TakeKeyboardFocus();
                passwordField.IsVisible = () => orderManager.AuthenticationFailed;
                var passwordLabel = widget.Get <LabelWidget>("PASSWORD_LABEL");
                passwordLabel.IsVisible  = passwordField.IsVisible;
                passwordField.OnEnterKey = _ => { retryButton.OnClick(); return(true); };
                passwordField.OnEscKey   = _ => { abortButton.OnClick(); return(true); };
            }

            passwordOffsetAdjusted = false;
            var connectionFailedTicker = panel.GetOrNull <LogicTickerWidget>("CONNECTION_FAILED_TICKER");

            if (connectionFailedTicker != null)
            {
                connectionFailedTicker.OnTick = () =>
                {
                    // Adjust the dialog once the AuthenticationError is parsed.
                    if (passwordField.IsVisible() && !passwordOffsetAdjusted)
                    {
                        var offset = passwordField.Bounds.Y - connectionError.Bounds.Y;
                        abortButton.Bounds.Y += offset;
                        retryButton.Bounds.Y += offset;
                        panel.Bounds.Height  += offset;
                        panel.Bounds.Y       -= offset / 2;

                        var background = panel.GetOrNull("CONNECTION_BACKGROUND");
                        if (background != null)
                        {
                            background.Bounds.Height += offset;
                        }

                        passwordOffsetAdjusted = true;
                    }
                };
            }
        }
    private void DoTbmpAcceptIncoming()
    {
        if (mLastInvitationId == null)
        {
            mStatus = "No incoming invitation received from listener.";
            return;
        }

        SetStandBy("Accepting TBMP invitation...");
        PlayGamesPlatform.Instance.TurnBased.AcceptInvitation(
            mLastInvitationId,
            (bool success, TurnBasedMatch match) =>
            {
                ShowEffect(success);
                EndStandBy();
                mMatch = match;
                mStatus = success ? "Successfully accepted invitation!" :
                "Failed to accept invitation";
                if (success)
                {
                    mUi = Ui.TbmpMatch;
                }
            });
    }
Esempio n. 40
0
        public LeaveMapLogic(Widget widget, World world, OrderManager orderManager)
        {
            this.orderManager = orderManager;

            var mpe = world.WorldActor.TraitOrDefault <MenuPaletteEffect>();

            if (mpe != null)
            {
                mpe.Fade(mpe.Info.MenuEffect);
            }

            widget.Get <LabelWidget>("VERSION_LABEL").Text = Game.ModData.Manifest.Mod.Version;

            var showStats = false;

            var scriptContext = world.WorldActor.TraitOrDefault <LuaScript>();
            var iop           = world.WorldActor.TraitsImplementing <IObjectivesPanel>().FirstOrDefault();
            var isMultiplayer = !world.LobbyInfo.IsSinglePlayer && !world.IsReplay;
            var hasError      = scriptContext != null && scriptContext.FatalErrorOccurred;
            var hasObjectives = hasError || (iop != null && iop.PanelName != null && world.LocalPlayer != null);
            var showTabs      = hasObjectives && isMultiplayer;

            currentTab = hasObjectives ? Tab.Objectives : Tab.Chat;

            var panelName = hasObjectives || isMultiplayer ? "LEAVE_MAP_FULL" : "LEAVE_MAP_SIMPLE";
            var dialog    = widget.Get <ContainerWidget>(panelName);

            dialog.IsVisible = () => !showStats;
            widget.IsVisible = () => Ui.CurrentWindow() == null;

            if (hasObjectives || isMultiplayer)
            {
                var titleText       = dialog.Get <LabelWidget>("GAME_ENDED_LABEL");
                var titleTextNoTabs = dialog.GetOrNull <LabelWidget>("GAME_ENDED_LABEL_NO_TABS");
                titleText.IsVisible = () => showTabs || (!showTabs && titleTextNoTabs == null);
                if (titleTextNoTabs != null)
                {
                    titleTextNoTabs.IsVisible = () => !showTabs;
                }

                var bg       = dialog.Get <BackgroundWidget>("LEAVE_MAP_BG");
                var bgNoTabs = dialog.GetOrNull <BackgroundWidget>("LEAVE_MAP_BG_NO_TABS");
                bg.IsVisible = () => showTabs || (!showTabs && bgNoTabs == null);
                if (bgNoTabs != null)
                {
                    bgNoTabs.IsVisible = () => !showTabs;
                }

                var objButton = dialog.Get <ButtonWidget>("OBJECTIVES_BUTTON");
                objButton.IsVisible     = () => showTabs;
                objButton.OnClick       = () => currentTab = Tab.Objectives;
                objButton.IsHighlighted = () => currentTab == Tab.Objectives;

                var chatButton = dialog.Get <ButtonWidget>("CHAT_BUTTON");
                chatButton.IsVisible = () => showTabs;
                chatButton.OnClick   = () =>
                {
                    currentTab     = Tab.Chat;
                    newChatMessage = false;
                };
                chatButton.IsHighlighted = () => currentTab == Tab.Chat || (newChatMessage && Game.LocalTick % 50 < 25);

                Game.BeforeGameStart     += UnregisterChatNotification;
                orderManager.AddChatLine += NotifyNewChatMessage;
            }

            var statsButton = dialog.Get <ButtonWidget>("STATS_BUTTON");

            statsButton.IsVisible = () => !world.Map.Visibility.HasFlag(MapVisibility.MissionSelector) || world.IsReplay;
            statsButton.OnClick   = () =>
            {
                showStats = true;
                Game.LoadWidget(world, "INGAME_OBSERVERSTATS_BG", Ui.Root, new WidgetArgs()
                {
                    { "onExit", () => showStats = false }
                });
            };

            var leaveButton = dialog.Get <ButtonWidget>("LEAVE_BUTTON");

            leaveButton.OnClick = () =>
            {
                leaveButton.Disabled = true;

                Sound.PlayNotification(world.Map.Rules, null, "Speech", "Leave",
                                       world.LocalPlayer == null ? null : world.LocalPlayer.Country.Race);

                var exitDelay = 1200;
                if (mpe != null)
                {
                    Game.RunAfterDelay(exitDelay, () => mpe.Fade(MenuPaletteEffect.EffectType.Black));
                    exitDelay += 40 * mpe.Info.FadeLength;
                }

                Game.RunAfterDelay(exitDelay, () =>
                {
                    Game.Disconnect();
                    Ui.ResetAll();
                    Game.LoadShellMap();
                });
            };

            if (hasObjectives)
            {
                var panel = hasError ? "SCRIPT_ERROR_PANEL" : iop.PanelName;
                var objectivesContainer = dialog.Get <ContainerWidget>("OBJECTIVES_PANEL");
                Game.LoadWidget(world, panel, objectivesContainer, new WidgetArgs());
                objectivesContainer.IsVisible = () => currentTab == Tab.Objectives;

                string video = null;
                if (world.LocalPlayer.WinState != WinState.Undefined)
                {
                    video = world.LocalPlayer.WinState == WinState.Won ? world.Map.Videos.GameWon : world.Map.Videos.GameLost;
                }

                if (!string.IsNullOrEmpty(video))
                {
                    Media.PlayFMVFullscreen(world, video, () => { });
                }
            }

            if (isMultiplayer)
            {
                var chatContainer = dialog.Get <ContainerWidget>("DIALOG_CHAT_PANEL");
                chatContainer.IsVisible = () => currentTab == Tab.Chat;
            }
        }
    private void DoTbmpCancel()
    {
        if (mMatch == null)
        {
            mStatus = "No match is active.";
            return;
        }

        if (mMatch.Status != TurnBasedMatch.MatchStatus.Active)
        {
            mStatus = "Match is not active.";
            return;
        }

        SetStandBy("Cancelling match...");
        PlayGamesPlatform.Instance.TurnBased.Cancel(
            mMatch,
            (bool success) =>
            {
                EndStandBy();
                ShowEffect(success);
                mStatus = success ? "Successfully cancelled match." : "Failed to cancel match.";
                if (success)
                {
                    mMatch = null;
                    mUi = Ui.Tbmp;
                }
            });
    }
Esempio n. 42
0
        /// <summary>
        /// Pokazuje wybrany interfejs graczowi.
        /// </summary>
        /// <param name="charData"></param>
        /// <param name="uiType"></param>
        /// <param name="id"></param>
        public static void ShowUi(Character charData, UiType uiType, int id)
        {
            if (charData == null)
            {
                return;
            }

            if (uiType == UiType.InteriorInfo)
            {
                Interior interiorData = GetInteriorData(id);
                if (interiorData == null)
                {
                    return;
                }

                List <DialogColumn> dialogColumns = new List <DialogColumn>
                {
                    new DialogColumn("", 45),
                    new DialogColumn("", 45)
                };

                List <DialogRow> dialogRows = new List <DialogRow>
                {
                    new DialogRow(null, new [] { "ID", interiorData.Id.ToString() }),
                    new DialogRow("name", new [] { "Nazwa", interiorData.Name }),
                    new DialogRow("ownertype", new [] { "Typ właściciela", ((int)interiorData.OwnerType).ToString() }),
                    new DialogRow("owner", new [] { "Właściciel", Global.GetOwnerName((int)interiorData.OwnerType, interiorData.Owner) }),
                    new DialogRow(null, new [] { "Virtual World", interiorData.Dimension.ToString() }),
                    new DialogRow(null, new [] { "", "" }),
                    new DialogRow("doors", new [] { "Lista drzwi", "" })
                };
                string[] dialogButtons = { "Edytuj", "Zamknij" };

                Managers.Account.SetServerData(charData, Account.ServerData.TempDialogData, interiorData.Id);
                Dialogs.Library.CreateDialog(charData.PlayerHandle, DialogId.InteriorInfo, "Edycja interioru", dialogColumns, dialogRows, dialogButtons);
            }
            else if (uiType == UiType.InteriorDoorsList)
            {
                Interior interiorData = GetInteriorData(id);
                if (interiorData == null)
                {
                    return;
                }

                IEnumerable <InteriorDoor> interiorDoors = GetInteriorDoors(interiorData);
                if (interiorDoors == null)
                {
                    Ui.ShowWarning(charData.PlayerHandle, "Interior nie ma żadnych drzwi.");
                    return;
                }

                List <DialogColumn> dialogColumns = new List <DialogColumn>
                {
                    new DialogColumn("", 90)
                };

                List <DialogRow> dialogRows    = interiorDoors.Select(entry => new DialogRow(null, new[] { $"{entry.Name} (ID: {entry.Id})" })).ToList();
                string[]         dialogButtons = { "Zamknij" };

                Dialogs.Library.CreateDialog(charData.PlayerHandle, DialogId.None, $"{interiorData.Name} - drzwi", dialogColumns, dialogRows, dialogButtons);
            }
        }
    private void DoTbmpLeaveDuringTurn()
    {
        if (mMatch == null)
        {
            mStatus = "No match is active.";
            return;
        }

        if (mMatch.TurnStatus != TurnBasedMatch.MatchTurnStatus.MyTurn)
        {
            mStatus = "It's not my turn.";
            return;
        }

        SetStandBy("Leaving match during turn...");
        PlayGamesPlatform.Instance.TurnBased.LeaveDuringTurn(
            mMatch,
            GetNextToPlay(mMatch),
            (bool success) =>
            {
                EndStandBy();
                ShowEffect(success);
                mStatus = success ? "Successfully left match during turn." :
                "Failed to leave match during turn.";
                if (success)
                {
                    mMatch = null;
                    mUi = Ui.Tbmp;
                }
            });
    }
Esempio n. 44
0
 public Control(Game game, Ui ui)
 {
     this.Game = game;
     this.Ui   = ui;
 }
    private void DoTbmpRematch()
    {
        if (mMatch == null)
        {
            mStatus = "No match is active.";
            return;
        }

        if (!mMatch.CanRematch)
        {
            mStatus = "Match can't be rematched.";
            return;
        }

        SetStandBy("Rematching match...");
        PlayGamesPlatform.Instance.TurnBased.Rematch(
            mMatch,
            (bool success, TurnBasedMatch match) =>
            {
                EndStandBy();
                ShowEffect(success);
                mMatch = match;
                mStatus = success ? "Successfully rematched." : "Failed to rematch.";
                if (success)
                {
                    // if we succeed, it will be our turn, so go to the appropriate UI
                    mUi = Ui.TbmpMatch;
                }
            });
    }
Esempio n. 46
0
        public IngameMenuLogic(Widget widget, World world, Action onExit, WorldRenderer worldRenderer, IngameInfoPanel activePanel)
        {
            var leaving = false;

            menu = widget.Get("INGAME_MENU");
            var mpe = world.WorldActor.TraitOrDefault <MenuPaletteEffect>();

            if (mpe != null)
            {
                mpe.Fade(mpe.Info.MenuEffect);
            }

            menu.Get <LabelWidget>("VERSION_LABEL").Text = Game.ModData.Manifest.Mod.Version;

            var hideMenu = false;

            menu.Get("MENU_BUTTONS").IsVisible = () => !hideMenu;

            var scriptContext = world.WorldActor.TraitOrDefault <LuaScript>();
            var hasError      = scriptContext != null && scriptContext.FatalErrorOccurred;

            // TODO: Create a mechanism to do things like this cleaner. Also needed for scripted missions
            Action onQuit = () =>
            {
                if (world.Type == WorldType.Regular)
                {
                    Sound.PlayNotification(world.Map.Rules, null, "Speech", "Leave", world.LocalPlayer == null ? null : world.LocalPlayer.Faction.InternalName);
                }

                leaving = true;

                var iop       = world.WorldActor.TraitsImplementing <IObjectivesPanel>().FirstOrDefault();
                var exitDelay = iop != null ? iop.ExitDelay : 0;
                if (mpe != null)
                {
                    Game.RunAfterDelay(exitDelay, () => mpe.Fade(MenuPaletteEffect.EffectType.Black));
                    exitDelay += 40 * mpe.Info.FadeLength;
                }

                Game.RunAfterDelay(exitDelay, () =>
                {
                    Game.Disconnect();
                    Ui.ResetAll();
                    Game.LoadShellMap();
                });
            };

            Action closeMenu = () =>
            {
                Ui.CloseWindow();
                if (mpe != null)
                {
                    mpe.Fade(MenuPaletteEffect.EffectType.None);
                }
                onExit();
            };

            Action showMenu = () => hideMenu = false;

            var abortMissionButton = menu.Get <ButtonWidget>("ABORT_MISSION");

            abortMissionButton.IsVisible  = () => world.Type == WorldType.Regular;
            abortMissionButton.IsDisabled = () => leaving;
            if (world.IsGameOver)
            {
                abortMissionButton.GetText = () => "Leave";
            }

            abortMissionButton.OnClick = () =>
            {
                if (world.IsGameOver)
                {
                    onQuit();
                    return;
                }

                hideMenu = true;
                ConfirmationDialogs.PromptConfirmAction("Abort Mission", "Leave this game and return to the menu?", onQuit, showMenu);
            };

            var exitEditorButton = menu.Get <ButtonWidget>("EXIT_EDITOR");

            exitEditorButton.IsVisible = () => world.Type == WorldType.Editor;
            exitEditorButton.OnClick   = () =>
            {
                hideMenu = true;
                ConfirmationDialogs.PromptConfirmAction("Exit Map Editor", "Exit and lose all unsaved changes?", onQuit, showMenu);
            };

            Action onSurrender = () =>
            {
                world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));
                closeMenu();
            };
            var surrenderButton = menu.Get <ButtonWidget>("SURRENDER");

            surrenderButton.IsVisible  = () => world.Type == WorldType.Regular;
            surrenderButton.IsDisabled = () => (world.LocalPlayer == null || world.LocalPlayer.WinState != WinState.Undefined) || hasError;
            surrenderButton.OnClick    = () =>
            {
                hideMenu = true;
                ConfirmationDialogs.PromptConfirmAction("Surrender", "Are you sure you want to surrender?", onSurrender, showMenu);
            };

            var saveMapButton = menu.Get <ButtonWidget>("SAVE_MAP");

            saveMapButton.IsVisible = () => world.Type == WorldType.Editor;
            saveMapButton.OnClick   = () =>
            {
                hideMenu = true;
                var editorActorLayer = world.WorldActor.Trait <EditorActorLayer>();
                Ui.OpenWindow("SAVE_MAP_PANEL", new WidgetArgs()
                {
                    { "onSave", (Action <string>)(_ => hideMenu = false) },
                    { "onExit", () => hideMenu = false },
                    { "map", world.Map },
                    { "playerDefinitions", editorActorLayer.Players.ToMiniYaml() },
                    { "actorDefinitions", editorActorLayer.Save() }
                });
            };

            var musicButton = menu.Get <ButtonWidget>("MUSIC");

            musicButton.IsDisabled = () => leaving;
            musicButton.OnClick    = () =>
            {
                hideMenu = true;
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs()
                {
                    { "onExit", () => hideMenu = false },
                    { "world", world }
                });
            };

            var settingsButton = widget.Get <ButtonWidget>("SETTINGS");

            settingsButton.IsDisabled = () => leaving;
            settingsButton.OnClick    = () =>
            {
                hideMenu = true;
                Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs()
                {
                    { "world", world },
                    { "worldRenderer", worldRenderer },
                    { "onExit", () => hideMenu = false },
                });
            };

            var resumeButton = menu.Get <ButtonWidget>("RESUME");

            resumeButton.IsDisabled = () => leaving;
            if (world.IsGameOver)
            {
                resumeButton.GetText = () => "Return to map";
            }

            resumeButton.OnClick = closeMenu;

            var panelRoot = widget.GetOrNull("PANEL_ROOT");

            if (panelRoot != null && world.Type != WorldType.Editor)
            {
                var gameInfoPanel = Game.LoadWidget(world, "GAME_INFO_PANEL", panelRoot, new WidgetArgs()
                {
                    { "activePanel", activePanel }
                });

                gameInfoPanel.IsVisible = () => !hideMenu;
            }
        }
 private void OnMatchFromNotification(TurnBasedMatch match, bool fromNotification)
 {
     if (fromNotification)
     {
         mUi = Ui.TbmpMatch;
         mMatch = match;
         mStatus = "Got match from notification! " + match;
     }
     else
     {
         mStatus = "Got match a update not from notification.";
     }
 }
Esempio n. 48
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 = OpenMultiplayerPanel;

            mainMenu.Get <ButtonWidget>("CONTENT_BUTTON").OnClick = () =>
            {
                // Switching mods changes the world state (by disposing it),
                // so we can't do this inside the input handler.
                Game.RunAfterTick(() =>
                {
                    var content = modData.Manifest.Get <ModContent>();
                    Game.InitializeMod(content.ContentInstallerMod, new Arguments(new[] { "Content.Mod=" + modData.Manifest.Id }));
                });
            };

            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 = OpenMissionBrowserPanel;

            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;

            var hasMaps        = modData.MapCache.Any(p => p.Visibility.HasFlag(MapVisibility.Lobby));
            var skirmishButton = singleplayerMenu.Get <ButtonWidget>("SKIRMISH_BUTTON");

            skirmishButton.OnClick  = StartSkirmishGame;
            skirmishButton.Disabled = !hasMaps;

            var loadButton = singleplayerMenu.Get <ButtonWidget>("LOAD_BUTTON");

            loadButton.IsDisabled = () => !GameSaveBrowserLogic.IsLoadPanelEnabled(modData.Manifest);
            loadButton.OnClick    = OpenGameSaveBrowserPanel;

            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 = OpenReplayBrowserPanel;

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

            loadMapButton.Disabled = !hasMaps;

            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.StartupPrompts;

                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;

            // Check for updates in the background
            var webServices = modData.Manifest.Get <WebServices>();

            if (Game.Settings.Debug.CheckVersion)
            {
                webServices.CheckModVersion();
            }

            var updateLabel = rootMenu.GetOrNull("UPDATE_NOTICE");

            if (updateLabel != null)
            {
                updateLabel.IsVisible = () => !newsOpen && menuType != MenuType.None &&
                                        menuType != MenuType.StartupPrompts &&
                                        webServices.ModVersionStatus == ModVersionStatus.Outdated;
            }

            var playerProfile = widget.GetOrNull("PLAYER_PROFILE_CONTAINER");

            if (playerProfile != null)
            {
                Func <bool> minimalProfile = () => Ui.CurrentWindow() != null;
                Game.LoadWidget(world, "LOCAL_PROFILE_PANEL", playerProfile, new WidgetArgs()
                {
                    { "minimalProfile", minimalProfile }
                });
            }

            menuType = MenuType.StartupPrompts;

            Action onIntroductionComplete = () =>
            {
                Action onSysInfoComplete = () =>
                {
                    LoadAndDisplayNews(webServices, newsBG);
                    SwitchMenu(MenuType.Main);
                };

                if (SystemInfoPromptLogic.ShouldShowPrompt())
                {
                    Ui.OpenWindow("MAINMENU_SYSTEM_INFO_PROMPT", new WidgetArgs
                    {
                        { "onComplete", onSysInfoComplete }
                    });
                }
                else
                {
                    onSysInfoComplete();
                }
            };

            if (IntroductionPromptLogic.ShouldShowPrompt())
            {
                Game.OpenWindow("MAINMENU_INTRODUCTION_PROMPT", new WidgetArgs
                {
                    { "onComplete", onIntroductionComplete }
                });
            }
            else
            {
                onIntroductionComplete();
            }

            Game.OnShellmapLoaded += OpenMenuBasedOnLastGame;

            DiscordService.UpdateStatus(DiscordState.InMenu);
        }

        void LoadAndDisplayNews(WebServices webServices, Widget newsBG)
        {
            if (newsBG != null && Game.Settings.Game.FetchNews)
            {
                var cacheFile   = Path.Combine(Platform.SupportDir, webServices.GameNewsFileName);
                var currentNews = ParseNews(cacheFile);
                if (currentNews != null)
                {
                    DisplayNews(currentNews);
                }

                var newsButton = newsBG.GetOrNull <DropDownButtonWidget>("NEWS_BUTTON");
                if (newsButton != null)
                {
                    if (!fetchedNews)
                    {
                        Task.Run(async() =>
                        {
                            try
                            {
                                var client = HttpClientFactory.Create();

                                // Send the mod and engine version to support version-filtered news (update prompts)
                                var url = new HttpQueryBuilder(webServices.GameNews)
                                {
                                    { "version", Game.EngineVersion },
                                    { "mod", Game.ModData.Manifest.Id },
                                    { "modversion", Game.ModData.Manifest.Metadata.Version }
                                }.ToString();

                                // Parameter string is blank if the player has opted out
                                url += SystemInfoPromptLogic.CreateParameterString();

                                var response = await client.GetStringAsync(url);
                                await File.WriteAllTextAsync(cacheFile, response);

                                Game.RunAfterTick(() =>                                 // run on the main thread
                                {
                                    fetchedNews = true;
                                    var newNews = ParseNews(cacheFile);
                                    if (newNews == null)
                                    {
                                        return;
                                    }

                                    DisplayNews(newNews);

                                    if (currentNews == null || newNews.Any(n => !currentNews.Select(c => c.DateTime).Contains(n.DateTime)))
                                    {
                                        OpenNewsPanel(newsButton);
                                    }
                                });
                            }
                            catch (Exception e)
                            {
                                Game.RunAfterTick(() =>                                 // run on the main thread
                                {
                                    SetNewsStatus($"Failed to retrieve news: {e}");
                                });
                            }
                        });
                    }

                    newsButton.OnClick = () => OpenNewsPanel(newsButton);
                }
            }
        }

        void OpenNewsPanel(DropDownButtonWidget button)
        {
            newsOpen = true;
            button.AttachPanel(newsPanel, () => newsOpen = false);
        }

        void OnRemoteDirectConnect(ConnectionTarget endpoint)
        {
            SwitchMenu(MenuType.None);
            Ui.OpenWindow("MULTIPLAYER_PANEL", new WidgetArgs
            {
                { "onStart", RemoveShellmapUI },
                { "onExit", () => SwitchMenu(MenuType.Main) },
                { "directConnectEndPoint", endpoint },
            });
        }

        void LoadMapIntoEditor(string uid)
        {
            ConnectionLogic.Connect(Game.CreateLocalServer(uid),
                                    "",
                                    () => { Game.LoadEditor(uid); },
                                    () => { Game.CloseServer(); SwitchMenu(MenuType.MapEditor); });

            DiscordService.UpdateStatus(DiscordState.InMapEditor);

            lastGameState = MenuPanel.MapEditor;
        }

        void SetNewsStatus(string message)
        {
            message            = WidgetUtils.WrapText(message, newsStatus.Bounds.Width, Game.Renderer.Fonts[newsStatus.Font]);
            newsStatus.GetText = () => message;
        }
    internal void DoOpenManual()
    {
        SetStandBy("Manual opening file: " + mSavedGameFilename);
        PlayGamesPlatform.Instance.SavedGame.OpenWithManualConflictResolution(
            mSavedGameFilename,
            DataSource.ReadNetworkOnly,
            true,
            (resolver, original, originalData, unmerged, unmergedData) =>
            {
                Logger.d("Entering conflict callback");
                mConflictResolver = resolver;
                mConflictOriginal = original;
                mConflictOriginalData = System.Text.ASCIIEncoding.Default.GetString(originalData);
                mConflictUnmerged = unmerged;
                mConflictUnmergedData = System.Text.ASCIIEncoding.Default.GetString(unmergedData);
                mUi = Ui.ResolveSaveConflict;
                EndStandBy();
                Logger.d("Encountered manual open conflict.");
            },
            (status, openedFile) =>
            {
                mStatus = "Open status for file " + mSavedGameFilename + ": " + status + "\n";
                if (openedFile != null)
                {
                    mStatus += "Successfully opened file: " + openedFile.ToString();
                    Logger.d("Opened file: " + openedFile.ToString());
                    mCurrentSavedGame = openedFile;
                }

                EndStandBy();
            });
    }
Esempio n. 50
0
        public CncIngameMenuLogic(Widget widget, World world, Action onExit, WorldRenderer worldRenderer)
        {
            var resumeDisabled = false;

            menu = widget.Get("INGAME_MENU");
            var mpe = world.WorldActor.Trait <CncMenuPaletteEffect>();

            mpe.Fade(CncMenuPaletteEffect.EffectType.Desaturated);

            menu.Get <LabelWidget>("VERSION_LABEL").GetText = WidgetUtils.ActiveModVersion;

            bool hideButtons = false;

            menu.Get("MENU_BUTTONS").IsVisible = () => !hideButtons;

            // TODO: Create a mechanism to do things like this cleaner. Also needed for scripted missions
            Action onQuit = () =>
            {
                Sound.PlayNotification(null, "Speech", "Leave", null);
                resumeDisabled = true;
                Game.RunAfterDelay(1200, () => mpe.Fade(CncMenuPaletteEffect.EffectType.Black));
                Game.RunAfterDelay(1200 + 40 * mpe.Info.FadeLength, () =>
                {
                    Game.Disconnect();
                    Ui.ResetAll();
                    Game.LoadShellMap();
                });
            };

            Action doNothing = () => { };

            menu.Get <ButtonWidget>("QUIT_BUTTON").OnClick = () =>
                                                             CncWidgetUtils.PromptConfirmAction("Abort Mission", "Leave this game and return to the menu?", onQuit, doNothing);

            Action onSurrender     = () => world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));
            var    surrenderButton = menu.Get <ButtonWidget>("SURRENDER_BUTTON");

            surrenderButton.IsDisabled = () => (world.LocalPlayer == null || world.LocalPlayer.WinState != WinState.Undefined);
            surrenderButton.OnClick    = () =>
                                         CncWidgetUtils.PromptConfirmAction("Surrender", "Are you sure you want to surrender?", onSurrender, doNothing);

            menu.Get <ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                hideButtons = true;
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs()
                {
                    { "onExit", () => hideButtons = false },
                });
            };

            menu.Get <ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                hideButtons = true;
                Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs()
                {
                    { "world", world },
                    { "worldRenderer", worldRenderer },
                    { "onExit", () => hideButtons = false },
                });
            };

            var resumeButton = menu.Get <ButtonWidget>("RESUME_BUTTON");

            resumeButton.IsDisabled = () => resumeDisabled;
            resumeButton.OnClick    = () =>
            {
                Ui.CloseWindow();
                Ui.Root.RemoveChild(menu);
                world.WorldActor.Trait <CncMenuPaletteEffect>().Fade(CncMenuPaletteEffect.EffectType.None);
                onExit();
            };

            // Menu panels - ordered from lowest to highest priority
            var       panelParent    = Game.OpenWindow(world, "INGAME_MENU_PANEL");
            PanelType panelType      = PanelType.Objectives;
            var       visibleButtons = 0;

            // Debug / Cheats panel
            var debugButton = panelParent.Get <ButtonWidget>("DEBUG_BUTTON");

            debugButton.OnClick       = () => panelType = PanelType.Debug;
            debugButton.IsHighlighted = () => panelType == PanelType.Debug;

            if (world.LocalPlayer != null && world.LobbyInfo.GlobalSettings.AllowCheats)
            {
                panelType = PanelType.Debug;
                visibleButtons++;
                var debugPanel = Game.LoadWidget(world, "CHEATS_PANEL", panelParent, new WidgetArgs()
                {
                    { "onExit", doNothing }
                });
                debugPanel.IsVisible  = () => panelType == PanelType.Debug;
                debugButton.IsVisible = () => visibleButtons > 1;
            }

            // Mission objectives
            var iop = world.WorldActor.TraitsImplementing <IObjectivesPanel>().FirstOrDefault();
            var objectivesButton = panelParent.Get <ButtonWidget>("OBJECTIVES_BUTTON");

            objectivesButton.OnClick       = () => panelType = PanelType.Objectives;
            objectivesButton.IsHighlighted = () => panelType == PanelType.Objectives;

            if (iop != null && iop.ObjectivesPanel != null)
            {
                panelType = PanelType.Objectives;
                visibleButtons++;
                var objectivesPanel = Game.LoadWidget(world, iop.ObjectivesPanel, panelParent, new WidgetArgs());
                objectivesPanel.IsVisible  = () => panelType == PanelType.Objectives;
                objectivesButton.IsVisible = () => visibleButtons > 1;
            }
        }
    internal void ShowMultiplayerUi()
    {
        this.DrawTitle("MULTIPLAYER");
        this.DrawStatus();

        if (GUI.Button(this.CalcGrid(0, 1), "RTMP"))
        {
            this.mUi = Ui.Rtmp;
        }
        else if (GUI.Button(this.CalcGrid(1, 1), "TBMP"))
        {
            this.mUi = Ui.Tbmp;
        }
        else if (GUI.Button(this.CalcGrid(1, 5), "Back"))
        {
            this.mUi = Ui.Main;
        }
    }
Esempio n. 52
0
        public IngameMenuLogic(Widget widget, World world, Action onExit, WorldRenderer worldRenderer)
        {
            var resumeDisabled = false;
            var mpe            = world.WorldActor.TraitOrDefault <MenuPaletteEffect>();

            Action onQuit = () =>
            {
                Sound.PlayNotification(world.Map.Rules, null, "Speech", "Leave", world.LocalPlayer == null ? null : world.LocalPlayer.Country.Race);
                resumeDisabled = true;

                var exitDelay = 1200;
                if (mpe != null)
                {
                    Game.RunAfterDelay(exitDelay, () => mpe.Fade(MenuPaletteEffect.EffectType.Black));
                    exitDelay += 40 * mpe.Info.FadeLength;
                }

                Game.RunAfterDelay(exitDelay, () =>
                {
                    Game.Disconnect();
                    Ui.ResetAll();
                    Game.LoadShellMap();
                });
            };

            Action onSurrender = () =>
            {
                world.IssueOrder(new Order("Surrender", world.LocalPlayer.PlayerActor, false));
                onExit();
            };

            widget.Get <ButtonWidget>("DISCONNECT").OnClick = () =>
            {
                widget.Visible = false;
                ConfirmationDialogs.PromptConfirmAction("Abort Mission", "Leave this game and return to the menu?", onQuit, () => widget.Visible = true);
            };

            widget.Get <ButtonWidget>("SETTINGS").OnClick = () =>
            {
                widget.Visible = false;
                Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs()
                {
                    { "onExit", () => widget.Visible = true },
                    { "worldRenderer", worldRenderer },
                });
            };

            widget.Get <ButtonWidget>("MUSIC").OnClick = () =>
            {
                widget.Visible = false;
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs {
                    { "onExit", () => { widget.Visible = true; } }
                });
            };

            var resumeButton = widget.Get <ButtonWidget>("RESUME");

            resumeButton.OnClick    = () => onExit();
            resumeButton.IsDisabled = () => resumeDisabled;

            widget.Get <ButtonWidget>("SURRENDER").OnClick = () =>
            {
                widget.Visible = false;
                ConfirmationDialogs.PromptConfirmAction(
                    "Surrender",
                    "Are you sure you want to surrender?",
                    onSurrender,
                    () => widget.Visible = true,
                    "Surrender");
            };
            widget.Get("SURRENDER").IsVisible = () => world.LocalPlayer != null && world.LocalPlayer.WinState == WinState.Undefined;
        }
    internal void ShowQuestsAndEventsUi()
    {
        if (mQuest != null)
        {
            mStatus = "Selected Quest: " + mQuest.Id + "\n";
        }

        if (mQuestMilestone != null)
        {
            mStatus += "Selected Milestone: " + mQuestMilestone.Id;
        }

        DrawStatus();
        DrawTitle("Quests and Events");

        if (GUI.Button(CalcGrid(0, 1), "Fetch All Events"))
        {
            SetStandBy("Fetching All Events");
            PlayGamesPlatform.Instance.Events.FetchAllEvents(
                DataSource.ReadNetworkOnly,
                (status, events) =>
                {
                    mStatus = "Fetch All Status: " + status + "\n";
                    mStatus += "Events: [" +
                    string.Join(",", events.Select(g => g.Id).ToArray()) + "]";
                    events.ForEach(e => Logger.d("Retrieved event: " + e.ToString()));
                    EndStandBy();
                });
        }
        else if (GUI.Button(CalcGrid(1, 1), "Fetch Event"))
        {
            SetStandBy("Fetching Event");
            PlayGamesPlatform.Instance.Events.FetchEvent(
                DataSource.ReadNetworkOnly,
                Settings.Event,
                (status, fetchedEvent) =>
                {
                    mStatus = "Fetch Status: " + status + "\n";
                    if (fetchedEvent != null)
                    {
                        mStatus += "Event: [" + fetchedEvent.Id + ", " + fetchedEvent.Description + "]";
                        Logger.d("Fetched event: " + fetchedEvent.ToString());
                    }

                    EndStandBy();
                });
        }
        else if (GUI.Button(CalcGrid(0, 2), "Increment Event"))
        {
            PlayGamesPlatform.Instance.Events.IncrementEvent(Settings.Event, 10);
        }

        if (GUI.Button(CalcGrid(1, 2), "Fetch Open Quests"))
        {
            FetchQuestList(QuestFetchFlags.Open);
        }
        else if (GUI.Button(CalcGrid(0, 3), "Fetch Upcoming Quests"))
        {
            FetchQuestList(QuestFetchFlags.Upcoming);
        }
        else if (GUI.Button(CalcGrid(1, 3), "Fetch Accepted Quests"))
        {
            FetchQuestList(QuestFetchFlags.Accepted);
        }
        else if (GUI.Button(CalcGrid(0, 4), "Show All Quests UI"))
        {
            SetStandBy("Showing all Quest UI");
            mQuest = null;
            mQuestMilestone = null;
            PlayGamesPlatform.Instance.Quests.ShowAllQuestsUI(HandleQuestUI);
        }
        else if (GUI.Button(CalcGrid(1, 4), "Show Quest UI"))
        {
            if (mQuest == null)
            {
                mStatus = "Could not show Quest UI - no quest selected";
            }
            else
            {
                PlayGamesPlatform.Instance.Quests.ShowSpecificQuestUI(mQuest, HandleQuestUI);
            }
        }
        else if (GUI.Button(CalcGrid(0, 5), "Fetch Quest"))
        {
            if (mQuest == null)
            {
                mStatus = "Could not fetch Quest - no quest selected";
            }
            else
            {
                SetStandBy("Fetching Quest");
                PlayGamesPlatform.Instance.Quests.Fetch(
                    DataSource.ReadNetworkOnly,
                    mQuest.Id,
                    (status, quest) =>
                    {
                        mStatus = "Fetch Quest Status: " + status + "\n";
                        mQuest = quest;
                        Logger.d("Fetched quest " + quest);
                        EndStandBy();
                    });
            }
        }
        else if (GUI.Button(CalcGrid(1, 5), "Accept Quest"))
        {
            if (mQuest == null)
            {
                mStatus = "Could not accept Quest - no quest selected";
            }
            else
            {
                SetStandBy("Accepting quest");
                PlayGamesPlatform.Instance.Quests.Accept(
                    mQuest,
                    (status, quest) =>
                    {
                        mStatus = "Accept Quest Status: " + status + "\n";
                        mQuest = quest;
                        Logger.d("Accepted quest " + quest);
                        EndStandBy();
                    });
            }
        }
        else if (GUI.Button(CalcGrid(0, 6), "Claim Milestone"))
        {
            if (mQuestMilestone == null)
            {
                mStatus = "Could not claim milestone - no milestone selected";
            }
            else
            {
                SetStandBy("Claiming milestone");
                PlayGamesPlatform.Instance.Quests.ClaimMilestone(
                    mQuestMilestone,
                    (status, quest, milestone) =>
                    {
                        mStatus = "Claim milestone Status: " + status + "\n";
                        mQuest = quest;
                        mQuestMilestone = milestone;
                        Logger.d("Claim quest: " + quest);
                        Logger.d("Claim milestone: " + milestone);
                        EndStandBy();
                    });
            }
        }

        if (GUI.Button(CalcGrid(1, 6), "Back"))
        {
            mUi = Ui.Main;
        }
    }
Esempio n. 54
0
        public ServerCreationLogic(Widget widget, ModData modData, Action onExit, Action openLobby)
        {
            panel       = widget;
            onCreate    = openLobby;
            this.onExit = onExit;

            var settings = Game.Settings;

            preview = modData.MapCache[modData.MapCache.ChooseInitialMap(Game.Settings.Server.Map, Game.CosmeticRandom)];

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick   = () => { Ui.CloseWindow(); onExit(); };
            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = CreateAndJoin;

            var mapButton = panel.GetOrNull <ButtonWidget>("MAP_BUTTON");

            if (mapButton != null)
            {
                panel.Get <ButtonWidget>("MAP_BUTTON").OnClick = () =>
                {
                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", preview.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", () => { } },
                        { "onSelect", (Action <string>)(uid => preview = modData.MapCache[uid]) },
                        { "filter", MapVisibility.Lobby },
                        { "onStart", () => { } }
                    });
                };

                panel.Get <MapPreviewWidget>("MAP_PREVIEW").Preview = () => preview;

                var titleLabel = panel.GetOrNull <LabelWithTooltipWidget>("MAP_TITLE");
                if (titleLabel != 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(preview);
                    titleLabel.GetTooltipText = () => preview.Title;
                }

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

                var authorLabel = panel.GetOrNull <LabelWidget>("MAP_AUTHOR");
                if (authorLabel != null)
                {
                    var font   = Game.Renderer.Fonts[authorLabel.Font];
                    var author = new CachedTransform <MapPreview, string>(
                        m => WidgetUtils.TruncateText("Created by {0}".F(m.Author), authorLabel.Bounds.Width, font));
                    authorLabel.GetText = () => author.Update(preview);
                }
            }

            var serverName = panel.Get <TextFieldWidget>("SERVER_NAME");

            serverName.Text        = Settings.SanitizedServerName(settings.Server.Name);
            serverName.OnEnterKey  = () => { serverName.YieldKeyboardFocus(); return(true); };
            serverName.OnLoseFocus = () =>
            {
                serverName.Text      = Settings.SanitizedServerName(serverName.Text);
                settings.Server.Name = serverName.Text;
            };

            panel.Get <TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();

            advertiseOnline = Game.Settings.Server.AdvertiseOnline;

            var advertiseCheckbox = panel.Get <CheckboxWidget>("ADVERTISE_CHECKBOX");

            advertiseCheckbox.IsChecked = () => advertiseOnline;
            advertiseCheckbox.OnClick   = () =>
            {
                advertiseOnline ^= true;
                BuildNotices();
            };

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");

            if (passwordField != null)
            {
                passwordField.Text = Game.Settings.Server.Password;
            }

            noticesLabelA = panel.GetOrNull <LabelWidget>("NOTICES_HEADER_A");
            noticesLabelB = panel.GetOrNull <LabelWidget>("NOTICES_HEADER_B");
            noticesLabelC = panel.GetOrNull <LabelWidget>("NOTICES_HEADER_C");

            var noticesNoUPnP = panel.GetOrNull("NOTICES_NO_UPNP");

            if (noticesNoUPnP != null)
            {
                noticesNoUPnP.IsVisible = () => advertiseOnline &&
                                          (UPnP.Status == UPnPStatus.NotSupported || UPnP.Status == UPnPStatus.Disabled);

                var settingsA = noticesNoUPnP.GetOrNull("SETTINGS_A");
                if (settingsA != null)
                {
                    settingsA.IsVisible = () => UPnP.Status == UPnPStatus.Disabled;
                }

                var settingsB = noticesNoUPnP.GetOrNull("SETTINGS_B");
                if (settingsB != null)
                {
                    settingsB.IsVisible = () => UPnP.Status == UPnPStatus.Disabled;
                }
            }

            var noticesUPnP = panel.GetOrNull("NOTICES_UPNP");

            if (noticesUPnP != null)
            {
                noticesUPnP.IsVisible = () => advertiseOnline && UPnP.Status == UPnPStatus.Enabled;
            }

            var noticesLAN = panel.GetOrNull("NOTICES_LAN");

            if (noticesLAN != null)
            {
                noticesLAN.IsVisible = () => !advertiseOnline;
            }

            BuildNotices();
        }
    internal void ShowResolveConflict()
    {
        this.DrawTitle("RESOLVE SAVE GAME CONFLICT");
        this.DrawStatus();

        if (this.mConflictResolver == null)
        {
            mStatus = "No pending conflict";
            mUi = Ui.SavedGame;
            return;
        }

        string msg = "Original: " + mConflictOriginal.Filename + ":" + mConflictOriginal.Description + "\n" +
                     "Data: " + mConflictOriginalData;
        GUI.Label(CalcGrid(0, 1, 2, 2), msg);

        msg = "Unmerged: " + mConflictUnmerged.Filename + ":" + mConflictUnmerged.Description + "\n" +
        "Data: " + mConflictUnmergedData;
        GUI.Label(CalcGrid(0, 2, 2, 2), msg);

        if (GUI.Button(CalcGrid(0, 3), "Use Original"))
        {
            mConflictResolver.ChooseMetadata(mConflictOriginal);
            SetStandBy("Choosing original, retrying open");
            mUi = Ui.SavedGame;
        }
        else if (GUI.Button(CalcGrid(1, 3), "Use Unmerged"))
        {
            mConflictResolver.ChooseMetadata(mConflictUnmerged);
            SetStandBy("Choosing unmerged, retrying open");
            mUi = Ui.SavedGame;
        }

        if (GUI.Button(CalcGrid(1, 7), "Back"))
        {
            mUi = Ui.SavedGame;
        }
    }
Esempio n. 56
0
        public ServerCreationLogic(Widget widget, Action onExit, Action openLobby)
        {
            panel       = widget;
            onCreate    = openLobby;
            this.onExit = onExit;

            var settings = Game.Settings;

            preview = Game.ModData.MapCache[WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map)];

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick   = () => { Ui.CloseWindow(); onExit(); };
            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = CreateAndJoin;

            var mapButton = panel.GetOrNull <ButtonWidget>("MAP_BUTTON");

            if (mapButton != null)
            {
                panel.Get <ButtonWidget>("MAP_BUTTON").OnClick = () =>
                {
                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", preview.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", () => { } },
                        { "onSelect", (Action <string>)(uid => preview = Game.ModData.MapCache[uid]) },
                        { "filter", MapVisibility.Lobby },
                        { "onStart", () => { } }
                    });
                };

                panel.Get <MapPreviewWidget>("MAP_PREVIEW").Preview = () => preview;
                panel.Get <LabelWidget>("MAP_NAME").GetText         = () => preview.Title;
            }

            panel.Get <TextFieldWidget>("SERVER_NAME").Text = settings.Server.Name ?? "";
            panel.Get <TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();
            advertiseOnline = Game.Settings.Server.AdvertiseOnline;

            var externalPort = panel.Get <TextFieldWidget>("EXTERNAL_PORT");

            externalPort.Text       = settings.Server.ExternalPort.ToString();
            externalPort.IsDisabled = () => !advertiseOnline;

            var advertiseCheckbox = panel.Get <CheckboxWidget>("ADVERTISE_CHECKBOX");

            advertiseCheckbox.IsChecked = () => advertiseOnline;
            advertiseCheckbox.OnClick   = () => advertiseOnline ^= true;

            allowPortForward = Game.Settings.Server.AllowPortForward;
            var checkboxUPnP = panel.Get <CheckboxWidget>("UPNP_CHECKBOX");

            checkboxUPnP.IsChecked  = () => allowPortForward;
            checkboxUPnP.OnClick    = () => allowPortForward ^= true;
            checkboxUPnP.IsDisabled = () => !Game.Settings.Server.NatDeviceAvailable;

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");

            if (passwordField != null)
            {
                passwordField.Text = Game.Settings.Server.Password;
            }
        }
    internal void ShowSavedGameUi()
    {
        DrawTitle("SAVED GAME - Using file: " + mSavedGameFilename);
        DrawStatus();

        if (GUI.Button(CalcGrid(0, 1), "Show UI"))
        {
            DoShowSavedGameUI();
        }
        else if (GUI.Button(CalcGrid(1, 1), "Open Manual"))
        {
            DoOpenManual();
        }
        else if (GUI.Button(CalcGrid(0, 2), "Open Keep Original"))
        {
            OpenSavedGame(ConflictResolutionStrategy.UseOriginal);
        }
        else if (GUI.Button(CalcGrid(1, 2), "Open Keep Unmerged"))
        {
            OpenSavedGame(ConflictResolutionStrategy.UseUnmerged);
        }
        else if (GUI.Button(CalcGrid(0, 3), "Read"))
        {
            DoReadSavedGame();
        }
        else if (GUI.Button(CalcGrid(1, 3), "Write"))
        {
            mUi = Ui.WriteSavedGame;
        }
        else if (GUI.Button(CalcGrid(0, 4), "Fetch All"))
        {
            DoFetchAll();
        }
        else if (GUI.Button(CalcGrid(1, 4), "Edit Filename"))
        {
            mUi = Ui.EditSavedGameName;
        }
        else if (GUI.Button(CalcGrid(1, 6), "Back"))
        {
            mUi = Ui.Main;
        }
    }
Esempio n. 58
0
        public CncMenuLogic(Widget widget, World world)
        {
            world.WorldActor.Trait <CncMenuPaletteEffect>()
            .Fade(CncMenuPaletteEffect.EffectType.Desaturated);

            rootMenu = widget.GetWidget("MENU_BACKGROUND");
            rootMenu.GetWidget <LabelWidget>("VERSION_LABEL").GetText = WidgetUtils.ActiveModVersion;

            // Menu buttons
            var mainMenu = widget.GetWidget("MAIN_MENU");

            mainMenu.IsVisible = () => Menu == MenuType.Main;

            mainMenu.GetWidget <ButtonWidget>("SOLO_BUTTON").OnClick        = StartSkirmishGame;
            mainMenu.GetWidget <ButtonWidget>("MULTIPLAYER_BUTTON").OnClick = () => Menu = MenuType.Multiplayer;

            mainMenu.GetWidget <ButtonWidget>("MODS_BUTTON").OnClick = () =>
            {
                Menu = MenuType.None;
                Ui.OpenWindow("MODS_PANEL", new WidgetArgs()
                {
                    { "onExit", () => Menu = MenuType.Main },
                    { "onSwitch", RemoveShellmapUI }
                });
            };

            mainMenu.GetWidget <ButtonWidget>("SETTINGS_BUTTON").OnClick = () => Menu = MenuType.Settings;
            mainMenu.GetWidget <ButtonWidget>("QUIT_BUTTON").OnClick     = Game.Exit;

            // Multiplayer menu
            var multiplayerMenu = widget.GetWidget("MULTIPLAYER_MENU");

            multiplayerMenu.IsVisible = () => Menu == MenuType.Multiplayer;

            multiplayerMenu.GetWidget <ButtonWidget>("BACK_BUTTON").OnClick          = () => Menu = MenuType.Main;
            multiplayerMenu.GetWidget <ButtonWidget>("JOIN_BUTTON").OnClick          = () => OpenGamePanel("SERVERBROWSER_PANEL");
            multiplayerMenu.GetWidget <ButtonWidget>("CREATE_BUTTON").OnClick        = () => OpenGamePanel("CREATESERVER_PANEL");
            multiplayerMenu.GetWidget <ButtonWidget>("DIRECTCONNECT_BUTTON").OnClick = () => OpenGamePanel("DIRECTCONNECT_PANEL");

            // Settings menu
            var settingsMenu = widget.GetWidget("SETTINGS_MENU");

            settingsMenu.IsVisible = () => Menu == MenuType.Settings;

            settingsMenu.GetWidget <ButtonWidget>("REPLAYS_BUTTON").OnClick = () =>
            {
                Menu = MenuType.None;
                Ui.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs()
                {
                    { "onExit", () => Menu = MenuType.Settings },
                    { "onStart", RemoveShellmapUI }
                });
            };

            settingsMenu.GetWidget <ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
            {
                Menu = MenuType.None;
                Ui.OpenWindow("MUSIC_PANEL", new WidgetArgs()
                {
                    { "onExit", () => Menu = MenuType.Settings },
                });
            };

            settingsMenu.GetWidget <ButtonWidget>("SETTINGS_BUTTON").OnClick = () =>
            {
                Menu = MenuType.None;
                Ui.OpenWindow("SETTINGS_PANEL", new WidgetArgs()
                {
                    { "world", world },
                    { "onExit", () => Menu = MenuType.Settings },
                });
            };

            settingsMenu.GetWidget <ButtonWidget>("BACK_BUTTON").OnClick = () => Menu = MenuType.Main;

            rootMenu.GetWidget <ImageWidget>("RECBLOCK").IsVisible = () => world.FrameNumber / 25 % 2 == 0;
        }
Esempio n. 59
0
 void Start()
 {
     m_PlayerColor = false;
     board = GameObject.Find ("Board").GetComponent<Board> ();
     undo = GameObject.Find("Undo").GetComponent<Undo>();
     gameInfo = GameObject.Find ("GameInfo").GetComponent<GameInfo>();
     ui = GameObject.Find ("Text").GetComponent<Ui>();
     SetTimeLimit = GameObject.Find ("TimeLimit").GetComponent<TimeLimit>();
 }
Esempio n. 60
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 = OpenMultiplayerPanel;

            mainMenu.Get <ButtonWidget>("CONTENT_BUTTON").OnClick = () =>
            {
                // Switching mods changes the world state (by disposing it),
                // so we can't do this inside the input handler.
                Game.RunAfterTick(() =>
                {
                    var content = modData.Manifest.Get <ModContent>();
                    Game.InitializeMod(content.ContentInstallerMod, new Arguments(new[] { "Content.Mod=" + modData.Manifest.Id }));
                });
            };

            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 = OpenMissionBrowserPanel;

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

            missionsButton.Disabled = !hasCampaign && !hasMissions;

            var hasMaps        = modData.MapCache.Any(p => p.Visibility.HasFlag(MapVisibility.Lobby));
            var skirmishButton = singleplayerMenu.Get <ButtonWidget>("SKIRMISH_BUTTON");

            skirmishButton.OnClick  = StartSkirmishGame;
            skirmishButton.Disabled = !hasMaps;

            var loadButton = singleplayerMenu.Get <ButtonWidget>("LOAD_BUTTON");

            loadButton.IsDisabled = () => !GameSaveBrowserLogic.IsLoadPanelEnabled(modData.Manifest);
            loadButton.OnClick    = OpenGameSaveBrowserPanel;

            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 = OpenReplayBrowserPanel;

            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 onSelectLoadToEditor = new Action <string>(uid => LoadMapIntoEditor(modData.MapCache[uid].Uid));
            var onSelect             = new Action <string>(uid => SwitchMenu(MenuType.MapEditor));

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

                Game.OpenWindow("NEW_MAP_BG", new WidgetArgs()
                {
                    { "onSelect", onSelect },
                    { "onExit", () => { } }
                });
            };

            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", onSelectLoadToEditor },
                    { "filter", MapVisibility.Lobby | MapVisibility.Shellmap | MapVisibility.MissionSelector },
                });
            };

            loadMapButton.Disabled = !hasMaps;

            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;

            // Check for updates in the background
            var webServices = modData.Manifest.Get <WebServices>();

            if (Game.Settings.Debug.CheckVersion)
            {
                webServices.CheckModVersion();
            }

            var updateLabel = rootMenu.GetOrNull("UPDATE_NOTICE");

            if (updateLabel != null)
            {
                updateLabel.IsVisible = () => !newsOpen && menuType != MenuType.None &&
                                        menuType != MenuType.SystemInfoPrompt &&
                                        webServices.ModVersionStatus == ModVersionStatus.Outdated;
            }

            var playerProfile = widget.GetOrNull("PLAYER_PROFILE_CONTAINER");

            if (playerProfile != null)
            {
                Func <bool> minimalProfile = () => Ui.CurrentWindow() != null;
                Game.LoadWidget(world, "LOCAL_PROFILE_PANEL", playerProfile, new WidgetArgs()
                {
                    { "minimalProfile", minimalProfile }
                });
            }

            // 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(webServices.GameNews, newsBG);
                };
            }
            else
            {
                //LoadAndDisplayNews(webServices.GameNews, newsBG);

                Game.OnShellmapLoaded += OpenMenuBasedOnLastGame;
            }
        }

        void LoadAndDisplayNews(string newsURL, Widget newsBG)
        {
            if (newsBG != null && Game.Settings.Game.FetchNews)
            {
                var cacheFile   = Platform.ResolvePath(Platform.SupportDirPrefix, "news.yaml");
                var currentNews = ParseNews(cacheFile);
                if (currentNews != null)
                {
                    DisplayNews(currentNews);
                }

                var newsButton = newsBG.GetOrNull <DropDownButtonWidget>("NEWS_BUTTON");
                if (newsButton != null)
                {
                    if (!fetchedNews)
                    {
                        // Send the mod and engine version to support version-filtered news (update prompts)
                        newsURL += "?version={0}&mod={1}&modversion={2}".F(
                            Uri.EscapeUriString(Game.EngineVersion),
                            Uri.EscapeUriString(Game.ModData.Manifest.Id),
                            Uri.EscapeUriString(Game.ModData.Manifest.Metadata.Version));

                        // Append system profile data if the player has opted in
                        if (Game.Settings.Debug.SendSystemInformation)
                        {
                            newsURL += "&sysinfoversion={0}&".F(SystemInformationVersion)
                                       + GetSystemInformation()
                                       .Select(kv => kv.Key + "=" + Uri.EscapeUriString(kv.Value.Second))
                                       .JoinWith("&");
                        }

                        new Download(newsURL, cacheFile, e => { },
                                     e => NewsDownloadComplete(e, cacheFile, currentNews,
                                                               () => OpenNewsPanel(newsButton)));
                    }

                    newsButton.OnClick = () => OpenNewsPanel(newsButton);
                }
            }
        }

        void OpenNewsPanel(DropDownButtonWidget button)
        {
            newsOpen = true;
            button.AttachPanel(newsPanel, () => newsOpen = false);
        }

        void OnRemoteDirectConnect(string host, int port)
        {
            SwitchMenu(MenuType.None);
            Ui.OpenWindow("MULTIPLAYER_PANEL", new WidgetArgs
            {
                { "onStart", RemoveShellmapUI },
                { "onExit", () => SwitchMenu(MenuType.Main) },
                { "directConnectHost", host },
                { "directConnectPort", port },
            });
        }

        void LoadMapIntoEditor(string uid)
        {
            ConnectionLogic.Connect(IPAddress.Loopback.ToString(),
                                    Game.CreateLocalServer(uid),
                                    "",
                                    () => { Game.LoadEditor(uid); },
                                    () => { Game.CloseServer(); SwitchMenu(MenuType.MapEditor); });

            lastGameState = MenuPanel.MapEditor;
        }

        void SetNewsStatus(string message)
        {
            message            = WidgetUtils.WrapText(message, newsStatus.Bounds.Width, Game.Renderer.Fonts[newsStatus.Font]);
            newsStatus.GetText = () => message;
        }