🔄 Handy Snippets Thread

As I am now heading heavily into MonoGame development [Some of you may have seen my Instagram/Twitter feeds] I came across this handy piece of code and thought, heck why not just make this knowledge available to everyone, while adding some additional data to it… also for complete beginners I wanted to make it clear to them where this code goes too… [FTR, as of writing this post, I consider myself a MonoGame Beginner]

So I decided to start with something really useful…

Focussing on: if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) Exit(); but more specifically Exit() I also added Keyboard interaction, something useful to add to this is when the X is clicked on the window, but as that is only useful when not in full screen mode, this entry will just be on two methods… I or another user may add the interaction for when the window is force closed or the X is clicked at a later time [Or when I remember and implement that interaction myself]

Game1.cs:

/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
    // TODO: Add your update logic here

    // Let us check the gamepad input first
    // note that this works even when the gamepad is connected after the game starts.
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        {
            UnloadContent(); // A good place to call this - this is one of the other methods in Game1.cs
            Exit(); // And your window vanishes
        };

    // Now let us use the keyboard method - Hello Escape Key
    // Capture the keyboard state and then respond to input
    KeyboardState keyboardState = Keyboard.GetState();
    if (keyboardState.IsKeyDown(Keys.Escape)) // Can even be the letter X upper and lower are the same
        {
            UnloadContent(); // A good place to call this - this is one of the other methods in Game1.cs
            Exit(); // And your window vanishes
        }

    base.Update(gameTime);
}

I have a question, how do you handle more than four pads? do you drop out of XBOX pad controls? just my assumption…

Another handy piece is being able to see your mouse cursor:
Game1.cs:

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        // Look here
        IsMouseVisible = true; // This can be removed when publishing or when you add your own cursor to your game
    }

Note that all code here is here to make things work and not exactly always performance oriented, that comes later, though if performance is included, then you got lucky and should thank whoever saved your day either way.

Anyhow, I will post things which I find useful, here, it can be a sort of repository, kind of surprised this is not already a thing here really…

When I complete my web studies I will make a searchable database site and … port these over to it…

Anyway, I hope my entries become useful for others.

More to follow…

2 Likes

I forgot I had this…

I am reposting a recently posted post in my other thread, eh, at least here it will be a collection:

Just throwing this protip out there for the beginners, I have recently started coding apps again, and forgot you can hide lines of commented out code using

{ 

}

In VS…

Basically:

Method something()
    {
        {
        // some old but still useful code
        // some old but still useful code
        // some old but still useful code
        // some old but still useful code
        }
        String OtherCodeHere = "SomethingCool";
    }

And then just click the +/- sign on the top bracket to hide it all… the one immediately above the commented out code…

I had a typo that caused this to prematurely post lol, trying to indent with Tab key in a browser lol

EDIT

Adding to this, basically, you would find this useful when you need to keep some code present in a method/function but need to try out new code below it or above it but don’t want to keep scrolling or breaking out views.

You can also get get same result by using SHIFT + CTRL + / this will do a block comment:

/*
Commented code
Commented code
Commented code
*/

To uncomment the block, expand if hidden click any where inside the block and SHIFT + CTRL + / again.

1 Like

That’s really handy, but just to add to it, you need to highlight a line above and below for it to function to allow the expansion +/- on the left side, nifty, thank you!

EDIT

Hmm, does not like working on already commented out comments…
Also fails at code inside a method/function, seems to only work on full methods…

Still a lot nicer than seeing // on every line! I guess a combination of {} and this

works for:
image

not for:
image

1 Like

I thought I posted this around here somewhere but maybe not? In any case, a long time ago a friend introduced me to this handy trick and to this day most people I work with don’t seem to know about it.

Behold, the super comment!!

//*/
Console.WriteLine("The top line executes...");
/*/
Console.WriteLine("The bottom line executes...");
//*/
/*/
Console.WriteLine("The top line executes...");
/*/
Console.WriteLine("The bottom line executes...");
//*/

Just add/remove the first / character as needed to toggle the two lines. I use this a ton when debugging crap and comparing behaviour between two things. Handy that the syntax highlighter here even picks it up :slight_smile:

(Works in C/C++ as well, probably any language that supports // and /* ... */ comment styles)

2 Likes

That is pretty funky!

I will start linking things once this thread hits 50 posts, so that the top post can be used as a menu…

Keep them coming!

Gamepad Button Toggle to prevent repeated behaviours

So, Just implemented this for a Fullscreen toggle for a gamepad while testing, and figured others may find this handy for practically all usage concerning a gamepad…

Remember, I write from a complete beginner perspective.

To begin, you require:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Diagnostics;

At the top of your Game1 class.

You will require a bool for the particular button, in this case the Y button on the XBOX gamepad.

    public partial class Game1
    {
        bool IsYPressedGamePadOne = false;

Place this at the top of the Game1 class or wherever you have set your variables in your engine as indicated in the example code above.

And set it to false as the start value.

In your Update() class, poll the gamepad to see it is connected, – Gamepad 1 has the ID of (0) here, Gamepad 4 would be (3) – and then perform a check to see if it is currently connected [If Bluetooth or wirelessly connected, powered on and syncing]

// Before Update()
        protected override void Update(GameTime gameTime)
        {
// inside Update()
            // get the gamepad One state once per update call
            var gamePadOneState = GamePad.GetState(0);
// Before IsConnected
            // check if the gamepad is connected
            if (gamePadOneState.IsConnected)
            {

Next, once you have your gamepad setup and state checked, use the following code to prevent a piece of code repeating while the button is pressed:

                // This section handles toggling Fullscreen Mode with Gamepad One Y Button.
                if (gamePadOneState.Buttons.Y == ButtonState.Pressed && !IsYPressedGamePadOne)
                {
                    // Write to the debug console that the Y button is pressed.
                    Debug.WriteLine("Y is pressed");
                    // Check the Bool to see if the Y button has been pressed before
                    // if false, process some code.
                    if (IsYPressedGamePadOne == false)
                    {
                        // Set the IsYPressedGamePadOne to true so that the following code is
                        // not repeated more than once while the button is pressed.
                        IsYPressedGamePadOne = true;
                        // Toggle the Fullscreen mode.
                        _graphics.IsFullScreen = !_graphics.IsFullScreen;
                        // Apply the changes to the graphics device.
                        _graphics.ApplyChanges();
                    }
                }
                // Check if the Y button is released and set the IsYPressedGamePadOne to false.
                if (gamePadOneState.Buttons.Y == ButtonState.Released && IsYPressedGamePadOne)
                {
                    // Write to the debug console that the Y button is released.
                    Debug.WriteLine("Y is released");
                    // Set the IsYPressedGamePadOne to false so that the pressed state can run.
                    IsYPressedGamePadOne = false;
                }
            }
//after IsConnected
            base.Update(gameTime);
// End of update()

And remember to close Update()

        }
// After Update()

Where you see !_graphics.IsFullScreen as it is a bool, whatever the current value is, it will flip it and apply the opposite value, thus, a switch toggle.

I have this implemented differently to the above using method calls, but just wanted complete beginners to know where to place the code for it to be effective.

I welcome feedback for improvements or if you have the time, share another variant.

When I get to handling in-game menus, I will share my in-code implementation when i get to it.

Remember to verify the debug output

image

Y is Pressed and Y is Released should only be printed once in sequence, you can verify this by holding down the button for a while, and having other code print to the debug window, and then releasing the button, or doing as above.

In my implementation, I can have the button pressed, and the fps is not affected, I can also press another button to execute other code, in my testing I pressed the back button to close the app, and as this is in the Update() method, it did not affect the Draw() method As we are changing the bool IsYPressedGamePadOne before we execute the Fullscreen switch, on a subsequent pass of the update call, it is skipped over, thereby, not switching the Fullscreen state repeatedly.

Closing remarks

I hope this helps, and I have included a full code of the Draw() method below, click the arrow/text to open it.

Full Draw() block for reference
// Before Update()
        protected override void Update(GameTime gameTime)
        {
// inside Update()
            // get the gamepad One state once per update call
            var gamePadOneState = GamePad.GetState(0);
// Before IsConnected
            // check if the gamepad is connected
            if (gamePadOneState.IsConnected)
            {
                // This section handles toggling Fullscreen Mode with Gamepad One Y Button.
                if (gamePadOneState.Buttons.Y == ButtonState.Pressed && !IsYPressedGamePadOne)
                {
                    // Write to the debug console that the Y button is pressed.
                    Debug.WriteLine("Y is pressed");
                    // Check the Bool to see if the Y button has been pressed before
                    // if false, process some code.
                    if (IsYPressedGamePadOne == false)
                    {
                        // Set the IsYPressedGamePadOne to true so that the following code is
                        // not repeated more than once while the button is pressed.
                        IsYPressedGamePadOne = true;
                        // Toggle the Fullscreen mode.
                        _graphics.IsFullScreen = !_graphics.IsFullScreen;
                        // Apply the changes to the graphics device.
                        _graphics.ApplyChanges();
                    }
                }
                // Check if the Y button is released and set the IsYPressedGamePadOne to false.
                if (gamePadOneState.Buttons.Y == ButtonState.Released && IsYPressedGamePadOne)
                {
                    // Write to the debug console that the Y button is released.
                    Debug.WriteLine("Y is released");
                    // Set the IsYPressedGamePadOne to false so that the pressed state can run.
                    IsYPressedGamePadOne = false;
                }
            }
//after IsConnected
            base.Update(gameTime);
// End of update()
        }
// After Update()
Shh, secret message here!

I spent more than an hour writing this haha


I hope you found this helpful.

Something, Something, Best Practices: #if DEBUG

So, you want to throw things at the Output window in your code editor, but, you forget that you leave it in code upon release… a waste of compilation time and not good practice to leave it in the release builds, poor computer will feel something is wrong or something…

What do you do?

This perhaps?

First we want something useful, say, the current graphics profile…

            GraphicsProfile profile = GraphicsDevice.GraphicsProfile;
#if DEBUG
            // print the graphics profile to the debug console
            System.Diagnostics.Debug.WriteLine(profile);
#endif

This would output either Reach or HiDef to the debug console.

Notice the #if DEBUG, this tells the compiler to add this code if the compilation is a Debug run and not a Release build… so, wherever you use a call to the Debug.WriteLine, remember to surround it with this, don’t forget the #endif.

And notice how it is hugging the left side of the code block window, and likely your editor will throw it to the left side too, this helps you find these things and keeps things clear, something, something, best practices.

Happy Coding!

Something to add to this, you technically don’t need the #if preprocessor directives here. The System.Diagnostics.Debug.WriteLine method is decorated with the System.Diagnostics.ConditionalAttribute internally in dotnet

Reference Link Here

When this ConditionalAttribute is used, any calls to that method are only included in Debug build configurations. When a Release build configuration is used, any calls to that method are removed. For example, here is a simple program to illustrate that

In this image, you can see the actual code which uses the Debug.WriteLine. Next to that is the Debug build decompiled showing that the call is still there, then next to that is the Release build decompiled showing that call is completely removed.

The ConditionalAttribute can also be useful when you want to catch logic mistakes as well by building a utility class that is meant to only execute during debug to assert things. For instance, here is a snippit of one that I use in my projects called Ensure

using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;

namespace TurtleEngine;

/// <summary>
///     Defines methods to ensure the state of conditions or object during debugging.
/// </summary>
public static class Ensure
{
    /// <summary>
    ///     Ensures that a fail state occurs and signals a breakpoint to the attached debugger.
    /// </summary>
    /// <remarks>
    ///     Will only be called when DEBUG directive is defined.
    /// </remarks>
    [Conditional("DEBUG")]
    [DebuggerHidden]
    public static void Fail()
    {
        Debug.Assert(false);
        Debugger.Break();
    }

    /// <summary>
    ///     Ensures that a fail state occurs, outputs the specified message in a message box, and signals a breakpoint
    ///     to the attached debugger.
    /// </summary>
    /// <remarks>
    ///     Will only be called when DEBUG directive is defined.
    /// </remarks>
    /// <param name="message">
    ///     The message to display in the message box.
    /// </param>
    /// <param name="args">
    ///     Arguments to supply to as format items to the <paramref name="message"/>.
    /// </param>
    [Conditional("DEBUG")]
    [DebuggerHidden]
    public static void Fail(string message, params object[] args)
    {
        Debug.Assert(false, string.Format(message, args));
        Debugger.Break();
    }

    /// <summary>
    ///     <para>
    ///         Ensure that the specified <paramref name="condition"/> is <see langword="true"/>. 
    ///     </para>
    ///     <para>
    ///         When <paramref name="condition"/> is <see langword="false"/>, ensures a fail state is triggered and 
    ///         signals a breakpoint to the attached debugger.
    ///     </para>
    /// </summary>
    /// <remarks>
    ///     Will only be called when DEBUG directive is defined.
    /// </remarks>
    /// <param name="condition">
    ///     The condition to ensure is <see langword="true"/>.
    /// </param>
    [Conditional("DEBUG")]
    [DebuggerHidden]
    public static void IsTrue(bool condition)
    {
        if (!condition) Fail();
    }

   // .... other code removed for brevity but there are methods such as IsFalse, IsNull, IsNotNull, etc
}

Then in my code I can call things like

public void Foo(int value)
{
    // Let's say I know this value should never be negative, so during debug I can do this
    Ensure.IsTrue(value >= 0);

   // And that line will only ever run during a debug build, and be excluded completely from Release
   //  Builds because the [Conditional] operator that was used in the Ensure class
}

So just posting this as an alternative to #if preprocessor directives when used strictly for Debug vs Release.

1 Like

MGCB problems

One of @Aristurtle’s guides

2 Likes