コード例 #1
0
ファイル: Program.cs プロジェクト: yeungchenhe/SMAPI
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public static void RunGame()
        {
            Application.ThreadException += Log.Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += Log.CurrentDomain_UnhandledException;

            try
            {
                gamePtr = new SGame();
                Log.AsyncY("Patching SDV Graphics Profile...");
                Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;
                LoadMods();

                StardewForm          = Control.FromHandle(gamePtr.Window.Handle).FindForm();
                StardewForm.Closing += StardewForm_Closing;

                ready = true;

                StardewGameInfo.SetValue(StardewProgramType, gamePtr);
                gamePtr.Run();
            }
            catch (Exception ex)
            {
                Log.AsyncR("Game failed to start: " + ex);
            }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: kazuyabr/SMAPI
        static void Events_LoadContent()
        {
            LogInfo("Initializing Debug Assets...");
            DebugPixel = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1);
            DebugPixel.SetData(new Color[] { Color.White });

            LogColour(ConsoleColor.Magenta, "REGISTERING BASE CUSTOM ITEM");
            SObject so = new SObject();

            so.Name         = "Mario Block";
            so.CategoryName = "SMAPI Test Mod";
            so.Description  = "It's a block from Mario!\nLoaded in realtime by SMAPI.";
            so.Texture      = Texture2D.FromStream(Game1.graphics.GraphicsDevice, new FileStream(ModContentPath + "\\Test.png", FileMode.Open));
            so.IsPassable   = true;
            so.IsPlaceable  = true;
            LogColour(ConsoleColor.Cyan, "REGISTERED WITH ID OF: " + SGame.RegisterModItem(so));

            LogColour(ConsoleColor.Magenta, "REGISTERING SECOND CUSTOM ITEM");
            SObject so2 = new SObject();

            so2.Name         = "Mario Painting";
            so2.CategoryName = "SMAPI Test Mod";
            so2.Description  = "It's a painting of a creature from Mario!\nLoaded in realtime by SMAPI.";
            so2.Texture      = Texture2D.FromStream(Game1.graphics.GraphicsDevice, new FileStream(ModContentPath + "\\PaintingTest.png", FileMode.Open));
            so2.IsPassable   = true;
            so2.IsPlaceable  = true;
            LogColour(ConsoleColor.Cyan, "REGISTERED WITH ID OF: " + SGame.RegisterModItem(so2));
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: huangzhenwen/SMAPI
        private static void Events_LoadContent(object o, EventArgs e)
        {
            Log.AsyncY("Initializing Debug Assets...");
            DebugPixel = new Texture2D(Game1.graphics.GraphicsDevice, 1, 1);
            DebugPixel.SetData(new[] { Color.White });

#if DEBUG
            StardewModdingAPI.Log.Async("REGISTERING BASE CUSTOM ITEM");
            SObject so = new SObject();
            so.Name         = "Mario Block";
            so.CategoryName = "SMAPI Test Mod";
            so.Description  = "It's a block from Mario!\nLoaded in realtime by SMAPI.";
            so.Texture      = Texture2D.FromStream(Game1.graphics.GraphicsDevice, new FileStream(_modContentPaths[0] + "\\Test.png", FileMode.Open));
            so.IsPassable   = true;
            so.IsPlaceable  = true;
            StardewModdingAPI.Log.Async("REGISTERED WITH ID OF: " + SGame.RegisterModItem(so));

            //StardewModdingAPI.Log.Async("REGISTERING SECOND CUSTOM ITEM");
            //SObject so2 = new SObject();
            //so2.Name = "Mario Painting";
            //so2.CategoryName = "SMAPI Test Mod";
            //so2.Description = "It's a painting of a creature from Mario!\nLoaded in realtime by SMAPI.";
            //so2.Texture = Texture2D.FromStream(Game1.graphics.GraphicsDevice, new FileStream(_modContentPaths[0] + "\\PaintingTest.png", FileMode.Open));
            //so2.IsPassable = true;
            //so2.IsPlaceable = true;
            //StardewModdingAPI.Log.Async("REGISTERED WITH ID OF: " + SGame.RegisterModItem(so2));

            Command.CallCommand("load");
#endif
        }
コード例 #4
0
 private void GameEvents_UpdateTick(object sender, EventArgs e)
 {
     if (SGame.Debug)
     {
         SGame.QueueDebugMessage($"[Twister] Daily Luck: {Game1.dailyLuck} | Tomorrow's Weather: {Game1.weatherForTomorrow}");
     }
 }
コード例 #5
0
        private static void RegisterNewItem(object sender, EventArgsCommand e)
        {
#if DEBUG
            SObject s = SGame.PullModItemFromDict(0, true);
            s.Stack = 999;
            Game1.player.addItemToInventory(s);
#endif
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: huangzhenwen/SMAPI
        private static void Events_CurrentLocationChanged(GameLocation newLocation)
        {
            //SGame.CurrentLocation = null;
            //System.Threading.Thread.Sleep(10);
#if DEBUG
            Console.WriteLine(newLocation.name);
            SGame.CurrentLocation = SGame.LoadOrCreateSGameLocationFromName(newLocation.name);
#endif
            //Game1.currentLocation = SGame.CurrentLocation;
            //Log.LogComment(((SGameLocation) newLocation).name);
            //Log.LogComment("LOC CHANGED: " + SGame.currentLocation.name);
        }
コード例 #7
0
        /// <summary>
        /// Method that saves down the current game in the form of information
        /// </summary>
        /// <param name="save"></param>
        public void SaveGame(Game save)
        {
            SGame savefile = new SGame();

            savefile.GameName     = save.GamesName;
            savefile.NumOfPlayers = save.PlayerLimit;
            savefile.Players      = new List <SPlayer>();
            savefile.SavedDeck    = new SDeck();
            //Savemethods that fill the deck and list of players with adequate data
            CreatePlayerSavefiles(savefile, save);
            SpecifySaveDeck(savefile.SavedDeck, save.CurrentDeck);
            dbConnect.SaveDownToDataBase(savefile);
        }
コード例 #8
0
 /// <summary>
 /// Reads in the active players from the list of players in the active game saving the data needed to start up a new round with
 /// an old savefile later on.
 /// </summary>
 /// <param name="save"></param>
 /// <param name="gamefile"></param>
 private void CreatePlayerSavefiles(SGame save, Game gamefile)
 {
     for (int i = 0; i < save.NumOfPlayers; i++)
     {
         SPlayer add = new SPlayer();
         add.Name      = gamefile.Contest[i].Name;
         add.Draswleft = gamefile.Contest[i].DrawsLeft;
         add.Myturn    = gamefile.Contest[i].Turn;
         add.Winner    = gamefile.Contest[i].Winner;
         add.Victories = gamefile.Contest[i].Victories;
         save.Players.Add(add);
     }
 }
コード例 #9
0
 /// <summary>
 /// Method that creates a set of player files using the data found in the database
 /// </summary>
 /// <param name="pl"></param>
 /// <param name="load"></param>
 /// <param name="curr"></param>
 private void LoadPlayers(List <Player> pl, SGame load, Deck curr)
 {
     foreach (SPlayer loadpl in load.Players)
     {
         Player retrieved = new Player();
         retrieved.Name        = loadpl.Name;
         retrieved.DrawsLeft   = loadpl.Draswleft;
         retrieved.Turn        = loadpl.Myturn;
         retrieved.Winner      = loadpl.Winner;
         retrieved.Victories   = loadpl.Victories;
         retrieved.CurrentDeck = curr;
         pl.Add(retrieved);
     }
 }
コード例 #10
0
        //         [Inject]
        //         public HeartBeatBody body { set; get; }

        public override void Execute()
        {
            GuLog.Info("<><HeartBeatCommand> Execute!");
            if (mLocalChildInfoAgent.getChildSN() == null || mLocalChildInfoAgent.getChildSN() == string.Empty)
            {
                GuLog.Info("<><HeartBeatCommand> child sn null!");
                FinishAndDispatchResult(ResponseErroInfo.GetErrorInfo(100, "child sn null!"));
                return;
            }
            getHeartBeatService.serviceHeartBeatBackSignal.AddListener(HeartBeatResult);
            getHeartBeatService.serviceHeartBeatErrBackSignal.AddListener(HeartBeatResultErr);

            SChild child = SChild.getBuilder().setFriend_count(10)
                           .setX_child_sn(mLocalChildInfoAgent.getChildSN()).setLanguage(languageUtils.getLanguageToAgentKey()).build();

            CupBuild.getCupHwMac((mac) => {
                Debug.Log("HeartBeatCommand mac:" + mac);
                SCup cup = SCup.getBuilder().setCup_hw_mac(mac)
#if UNITY_EDITOR
                           .setBattery(50)
                           .setCharge(false)
                           .setCapability(0)
                           .build();
#else
                           .setBattery(BatteryUtils.getBatteryCapacity(AndroidContextHolder.GetAndroidContext()))
                           .setCharge(BatteryUtils.isCharging(AndroidContextHolder.GetAndroidContext()))
                           .setCapability(0)
                           .build();
#endif
                SGame game = SGame.getBuilder()
                             .setGame_name(AppData.GetAppName())
#if UNITY_EDITOR
                             .setGame_version("1.0.31")
#else
                             .setGame_version(CupBuild.getAppVersionName())
#endif
                             .setPet_model(mLocalPetInfoAgent.getCurrentPet()).build();

                SExtra extra = SExtra.getBuilder().setTimestamp(DateUtil.GetTimeStamp()).setTimezone(8).build();

                HeartBeatBody body = HeartBeatBody.getBuilder().setChild(child).setCup(cup).setGame(game).setExtra(extra).build();


                getHeartBeatService.HeartBeat(body);
            });
コード例 #11
0
        /// <summary>
        /// returns a previously saved game if a save with matching name can be found
        /// </summary>
        /// <param name="gameName"></param>
        /// <returns></returns>
        public Game LoadedSave(string gameName)
        {
            SGame found = dbConnect.Load(gameName);

            if (found != null)
            {
                Game loadedSave = new Game();
                loadedSave.GamesName   = found.GameName;
                loadedSave.PlayerLimit = found.NumOfPlayers;
                loadedSave.CurrentDeck = new Deck();
                RetrieveDeck(loadedSave.CurrentDeck, found.SavedDeck);
                LoadPlayers(loadedSave.Contest, found, loadedSave.CurrentDeck);

                return(loadedSave);
            }
            else
            {
                throw new ArgumentNullException("Save could not be found");
            }
        }
コード例 #12
0
ファイル: Program.cs プロジェクト: huangzhenwen/SMAPI
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        public static void RunGame()
        {
            AppDomain.CurrentDomain.UnhandledException += Log.CurrentDomain_UnhandledException;

            try
            {
                gamePtr = new SGame();
                Log.AsyncY("Patching SDV Graphics Profile...");
                Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;
                LoadMods();

                ready = true;

                StardewGameInfo.SetValue(StardewProgramType, gamePtr);
                gamePtr.Run();
            }
            catch (Exception ex)
            {
                Log.AsyncR("Game failed to start: " + ex);
            }
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: kazuyabr/SMAPI
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



        public static void RunGame()
        {
            try
            {
                gamePtr = new SGame();
                LogInfo("Patching SDV Graphics Profile...");
                Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;
                LoadMods();

                StardewForm          = Control.FromHandle(Program.gamePtr.Window.Handle).FindForm();
                StardewForm.Closing += StardewForm_Closing;
                StardewGameInfo.SetValue(StardewProgramType, gamePtr);

                ready = true;

                gamePtr.Run();
            }
            catch (Exception ex)
            {
                LogError("Game failed to start: " + ex);
            }
        }
コード例 #14
0
 public Builder setGame(SGame val)
 {
     game = val;
     return(this);
 }
コード例 #15
0
ファイル: Program.cs プロジェクト: RiasKlein/SMAPI
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public static void RunGame()
        {
            Application.ThreadException += Log.Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += Log.CurrentDomain_UnhandledException;

            try
            {
                gamePtr = new SGame();
                Log.AsyncY("Patching SDV Graphics Profile...");
                Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;
                LoadMods();

                StardewForm = Control.FromHandle(gamePtr.Window.Handle).FindForm();
                if (StardewForm != null) StardewForm.Closing += StardewForm_Closing;

                ready = true;

                StardewGameInfo.SetValue(StardewProgramType, gamePtr);
                gamePtr.Run();
            }
            catch (Exception ex)
            {
                Log.AsyncR("Game failed to start: " + ex);
            }
        }
コード例 #16
0
ファイル: RegenMod.cs プロジェクト: lyuha/SMAPI-Mods
        private void GameEvents_UpdateTick(object sender, EventArgs e)
        {
            if (TheGame == null || Player == null)
            {
                return;
            }

            if (!TheGame.IsActive || Game1.paused || Game1.activeClickableMenu != null)
            {
                return;
            }

            if (UpdateIndex <= 60)
            {
                UpdateIndex += 1;
                return;
            }

            TimeSinceLastMoved += Game1.currentGameTime.ElapsedGameTime.TotalMilliseconds;
            if (Game1.oldKBState.GetPressedKeys().Any() || Game1.oldMouseState.LeftButton == ButtonState.Pressed || Game1.oldMouseState.RightButton == ButtonState.Pressed)
            {
                TimeSinceLastMoved = 0;
            }

            #region Health Regen

            if (ModConfig.RegenHealthConstant)
            {
                HealthFloat += (ModConfig.RegenHealthConstantIsNegative ? -ModConfig.RegenHealthConstantAmountPerSecond : ModConfig.RegenHealthConstantAmountPerSecond) * ElapsedFloat;
            }

            if (ModConfig.RegenHealthStill)
            {
                if (TimeSinceLastMoved > ModConfig.RegenHealthStillTimeRequiredMS)
                {
                    HealthFloat += (ModConfig.RegenHealthStillIsNegative ? -ModConfig.RegenHealthStillAmountPerSecond : ModConfig.RegenHealthStillAmountPerSecond) * ElapsedFloat;
                }
            }

            if (Player.health + HealthFloat >= Player.maxHealth)
            {
                Player.health = Player.maxHealth;
                HealthFloat   = 0;
            }
            else if (HealthFloat >= 1)
            {
                Player.health += 1;
                HealthFloat   -= 1;
            }
            else if (HealthFloat <= -1)
            {
                Player.health -= 1;
                HealthFloat   += 1;
            }

            #endregion

            #region Stamina Regen

            if (ModConfig.RegenStaminaConstant)
            {
                StaminaFloat += (ModConfig.RegenStaminaConstantIsNegative ? -ModConfig.RegenStaminaConstantAmountPerSecond : ModConfig.RegenStaminaConstantAmountPerSecond) * ElapsedFloat;
            }

            if (ModConfig.RegenStaminaStill)
            {
                if (TimeSinceLastMoved > ModConfig.RegenStaminaStillTimeRequiredMS)
                {
                    StaminaFloat += (ModConfig.RegenStaminaStillIsNegative ? -ModConfig.RegenStaminaStillAmountPerSecond : ModConfig.RegenStaminaStillAmountPerSecond) * ElapsedFloat;
                }
            }

            if (Player.Stamina + StaminaFloat >= Player.maxStamina)
            {
                Player.Stamina = Player.maxStamina;
                StaminaFloat   = 0;
            }
            else if (StaminaFloat >= 1)
            {
                Player.Stamina += 1;
                StaminaFloat   -= 1;
            }
            else if (StaminaFloat <= -1)
            {
                Player.Stamina -= 1;
                StaminaFloat   += 1;
            }

            #endregion

            SGame.QueueDebugMessage("H: " + HealthFloat + " | S: " + StaminaFloat);
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: kazuyabr/SMAPI
        /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private static void Main(string[] args)
        {
            Console.Title = "Stardew Modding API Console";

            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            if (File.Exists(ModPath))
            {
                File.Delete(ModPath);
            }
            if (!Directory.Exists(ModPath))
            {
                Directory.CreateDirectory(ModPath);
            }
            if (!Directory.Exists(ModContentPath))
            {
                Directory.CreateDirectory(ModContentPath);
            }

            ExecutionPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            CurrentLog    = LogPath + "\\MODDED_ProgramLog_" + System.DateTime.Now.Ticks + ".txt";

            Log(ExecutionPath, false);

            LogStream = new StreamWriter(CurrentLog, false);

            LogInfo("Initializing SDV Assembly...");
            if (!File.Exists(ExecutionPath + "\\Stardew Valley.exe"))
            {
                LogError("Could not find: " + ExecutionPath + "\\Stardew Valley.exe");
                LogError("The API will now terminate.");
                Console.ReadKey();
                Environment.Exit(-4);
            }

            StardewAssembly    = Assembly.LoadFile(ExecutionPath + "\\Stardew Valley.exe");
            StardewProgramType = StardewAssembly.GetType("StardewValley.Program", true);
            StardewGameInfo    = StardewProgramType.GetField("gamePtr");



            LogInfo("Injecting New SDV Version...");
            Game1.version += "-Z_MODDED";

            gameThread = new Thread(RunGame);
            LogInfo("Starting SDV...");
            gameThread.Start();

            SGame.GetStaticFields();

            while (!ready)
            {
            }

            Log("SDV Loaded Into Memory");

            consoleInputThread = new Thread(ConsoleInputThread);
            LogInfo("Initializing Console Input Thread...");

            Command.RegisterCommand("help", "Lists all commands | 'help <cmd>' returns command description").CommandFired += help_CommandFired;

            Events.KeyPressed  += Events_KeyPressed;
            Events.LoadContent += Events_LoadContent;
            //Events.MenuChanged += Events_MenuChanged;
            Events.LocationsChanged       += Events_LocationsChanged;
            Events.CurrentLocationChanged += Events_CurrentLocationChanged;

            LogInfo("Applying Final SDV Tweaks...");
            StardewInvoke(() =>
            {
                gamePtr.IsMouseVisible = false;
                gamePtr.Window.Title   = "Stardew Valley - Version " + Game1.version;
            });

            LogInfo("Game Loaded");
            Events.InvokeGameLoaded();

            consoleInputThread.Start();
            LogColour(ConsoleColor.Cyan, "Type 'help' for help, or 'help <cmd>' for a command's usage");


            while (ready)
            {
                //Check if the game is still running 10 times a second
                Thread.Sleep(1000 / 10);
            }

            if (consoleInputThread != null && consoleInputThread.ThreadState == ThreadState.Running)
            {
                consoleInputThread.Abort();
            }

            LogInfo("Game Execution Finished");
            LogInfo("Shutting Down...");
            int time   = 0;
            int step   = 100;
            int target = 1000;

            while (true)
            {
                time += step;
                Thread.Sleep(step);

                Console.Write(".");

                if (time >= target)
                {
                    break;
                }
            }
            Environment.Exit(0);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: Shanksyue/SMAPI
        /// <summary>Hook into Stardew Valley and launch the game.</summary>
        private void StartGame()
        {
            try
            {
                this.Monitor.Log("Loading game...");

                // add error handlers
#if SMAPI_FOR_WINDOWS
                Application.ThreadException += (sender, e) => this.Monitor.Log($"Critical thread exception: {e.Exception.GetLogSummary()}", LogLevel.Error);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
#endif
                AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error);

                // override Game1 instance
                this.GameInstance          = new SGame(this.Monitor);
                this.GameInstance.Exiting += (sender, e) => this.IsGameRunning = false;
                this.GameInstance.Window.ClientSizeChanged += (sender, e) => GraphicsEvents.InvokeResize(this.Monitor, sender, e);
                this.GameInstance.Window.Title              = $"Stardew Valley {Constants.GameVersion} with SMAPI {Constants.ApiVersion}";
                StardewValley.Program.gamePtr = this.GameInstance;

                // configure
                Game1.graphics.GraphicsProfile = GraphicsProfile.HiDef;

                // load mods
                this.LoadMods();
                if (this.CancellationTokenSource.IsCancellationRequested)
                {
                    this.Monitor.Log("Shutdown requested; interrupting initialisation.", LogLevel.Error);
                    return;
                }

                // initialise console after game launches
                new Thread(() =>
                {
                    // wait for the game to load up
                    while (!this.IsGameRunning)
                    {
                        Thread.Sleep(1000);
                    }

                    // register help command
                    this.CommandManager.Add("SMAPI", "help", "Lists all commands | 'help <cmd>' returns command description", this.HandleHelpCommand);

                    // listen for command line input
                    this.Monitor.Log("Starting console...");
                    this.Monitor.Log("Type 'help' for help, or 'help <cmd>' for a command's usage", LogLevel.Info);
                    Thread consoleInputThread = new Thread(this.ConsoleInputLoop);
                    consoleInputThread.Start();
                    while (this.IsGameRunning)
                    {
                        Thread.Sleep(1000 / 10); // Check if the game is still running 10 times a second
                    }
                    // abort the console thread, we're closing
                    if (consoleInputThread.ThreadState == ThreadState.Running)
                    {
                        consoleInputThread.Abort();
                    }
                }).Start();

                // start game loop
                this.Monitor.Log("Starting game...");
                if (this.CancellationTokenSource.IsCancellationRequested)
                {
                    this.Monitor.Log("Shutdown requested; interrupting initialisation.", LogLevel.Error);
                    return;
                }
                try
                {
                    this.IsGameRunning = true;
                    this.GameInstance.Run();
                }
                finally
                {
                    this.IsGameRunning = false;
                }
            }
            catch (Exception ex)
            {
                this.Monitor.Log($"The game encountered a fatal error:\n{ex.GetLogSummary()}", LogLevel.Error);
            }
        }
コード例 #19
0
ファイル: MovementMod.cs プロジェクト: lyuha/SMAPI-Mods
        private void GameEventsOnUpdateTick(object sender, EventArgs e)
        {
            if (TheGame == null || Game1.player == null || Game1.currentLocation == null)
            {
                return;
            }

            if (!TheGame.IsActive || Game1.paused || Game1.activeClickableMenu != null)
            {
                return;
            }

            if (Game1.currentLocation.currentEvent != null)
            {
                CurrentSpeed = 0;
            }
            else
            {
                if (ModConfig.EnableHorseSpeedOverride && Player.getMount() != null)
                {
                    CurrentSpeed = ModConfig.HorseSpeed;
                }
                if (ModConfig.EnableRunningSpeedOverride && Player.running)
                {
                    CurrentSpeed = ModConfig.PlayerRunningSpeed;
                }
                else if (ModConfig.EnableWalkingSpeedOverride && !Player.running)
                {
                    CurrentSpeed = ModConfig.PlayerWalkingSpeed;
                }
                else
                {
                    CurrentSpeed = 0;
                }

                if (SprintKeyDown)
                {
                    if (ModConfig.SprintingDrainsStamina)
                    {
                        float loss = ModConfig.SprintingStaminaDrainPerSecond * TickSecondMult;
                        if (Player.position != PrevPosition && Player.stamina - loss > 0)
                        {
                            Player.stamina -= loss;
                            CurrentSpeed   *= ModConfig.PlayerSprintingSpeedMultiplier;
                        }
                    }
                    else
                    {
                        CurrentSpeed *= ModConfig.PlayerSprintingSpeedMultiplier;
                    }
                }

                Player.addedSpeed = CurrentSpeed;

                SGame.QueueDebugMessage($"CSpeed: {CurrentSpeed} - ASpeed: {Player.addedSpeed}");

                if (ModConfig.EnableDiagonalMovementSpeedFix)
                {
                    Player.movementDirections?.Clear();
                }
            }

            PrevPosition = Player.position;
        }
コード例 #20
0
 static void RegisterNewItem(Command cmd)
 {
     Game1.player.addItemToInventory(SGame.PullModItemFromDict(0, true));
 }
コード例 #21
0
        [HandleProcessCorruptedStateExceptions, SecurityCritical] // let try..catch handle corrupted state exceptions
        public void RunInteractively()
        {
            // initialise SMAPI
            try
            {
                // init logging
                this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GameVersion} on {this.GetFriendlyPlatformName()}", LogLevel.Info);
                this.Monitor.Log($"Mods go here: {Constants.ModPath}");
                this.Monitor.Log($"Log started at {DateTime.UtcNow:s} UTC", LogLevel.Trace);

                // validate paths
                this.VerifyPath(Constants.ModPath);
                this.VerifyPath(Constants.LogDir);

                // validate game version
                if (Constants.GameVersion.IsOlderThan(Constants.MinimumGameVersion))
                {
                    this.Monitor.Log($"Oops! You're running Stardew Valley {Constants.GameVersion}, but the oldest supported version is {Constants.MinimumGameVersion}. Please update your game before using SMAPI.", LogLevel.Error);
                    this.PressAnyKeyToExit();
                    return;
                }
                if (Constants.MaximumGameVersion != null && Constants.GameVersion.IsNewerThan(Constants.MaximumGameVersion))
                {
                    this.Monitor.Log($"Oops! You're running Stardew Valley {Constants.GameVersion}, but this version of SMAPI is only compatible up to Stardew Valley {Constants.MaximumGameVersion}. Please check for a newer version of SMAPI.", LogLevel.Error);
                    this.PressAnyKeyToExit();
                    return;
                }

                // add error handlers
#if SMAPI_FOR_WINDOWS
                Application.ThreadException += (sender, e) => this.Monitor.Log($"Critical thread exception: {e.Exception.GetLogSummary()}", LogLevel.Error);
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
#endif
                AppDomain.CurrentDomain.UnhandledException += (sender, e) => this.Monitor.Log($"Critical app domain exception: {e.ExceptionObject}", LogLevel.Error);

                // override game
                this.GameInstance             = new SGame(this.Monitor, this.Reflection);
                StardewValley.Program.gamePtr = this.GameInstance;

                // add exit handler
                new Thread(() =>
                {
                    this.CancellationTokenSource.Token.WaitHandle.WaitOne();
                    if (this.IsGameRunning)
                    {
                        try
                        {
                            File.WriteAllText(Constants.FatalCrashMarker, string.Empty);
                            File.Copy(this.LogFile.Path, Constants.FatalCrashLog, overwrite: true);
                        }
                        catch (Exception ex)
                        {
                            this.Monitor.Log($"SMAPI failed trying to track the crash details: {ex.GetLogSummary()}");
                        }

                        this.GameInstance.Exit();
                    }
                }).Start();

                // hook into game events
#if SMAPI_FOR_WINDOWS
                ((Form)Control.FromHandle(this.GameInstance.Window.Handle)).FormClosing += (sender, args) => this.Dispose();
#endif
                this.GameInstance.Exiting        += (sender, e) => this.Dispose();
                GameEvents.InitializeInternal    += (sender, e) => this.InitialiseAfterGameStart();
                ContentEvents.AfterLocaleChanged += (sender, e) => this.OnLocaleChanged();

                // set window titles
                this.GameInstance.Window.Title = $"Stardew Valley {Constants.GameVersion} - running SMAPI {Constants.ApiVersion}";
                Console.Title = $"SMAPI {Constants.ApiVersion} - running Stardew Valley {Constants.GameVersion}";
            }
            catch (Exception ex)
            {
                this.Monitor.Log($"SMAPI failed to initialise: {ex.GetLogSummary()}", LogLevel.Error);
                this.PressAnyKeyToExit();
                return;
            }

            // show details if game crashed during last session
            if (File.Exists(Constants.FatalCrashMarker))
            {
                this.Monitor.Log("The game crashed last time you played. That can be due to bugs in the game, but if it happens repeatedly you can ask for help here: http://community.playstarbound.com/threads/108375/.", LogLevel.Error);
                this.Monitor.Log($"If you ask for help, make sure to attach this file: {Constants.FatalCrashLog}", LogLevel.Error);
                this.Monitor.Log("Press any key to delete the crash data and continue playing.", LogLevel.Info);
                Console.ReadKey();
                File.Delete(Constants.FatalCrashLog);
                File.Delete(Constants.FatalCrashMarker);
            }

            // start game
            this.Monitor.Log("Starting game...", LogLevel.Trace);
            try
            {
                this.IsGameRunning = true;
                this.GameInstance.Run();
            }
            catch (Exception ex)
            {
                this.Monitor.Log($"The game failed unexpectedly: {ex.GetLogSummary()}", LogLevel.Error);
                this.PressAnyKeyToExit();
            }
            finally
            {
                this.Dispose();
            }
        }
コード例 #22
0
 public void setGame(SGame game)
 {
     this.game = game;
 }