Skip to content

Instantly share code, notes, and snippets.

@Jjagg

Jjagg/Input.cs Secret

Last active June 22, 2017 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jjagg/2a30c9214d38bcc5ec79665ff762df6b to your computer and use it in GitHub Desktop.
Save Jjagg/2a30c9214d38bcc5ec79665ff762df6b to your computer and use it in GitHub Desktop.
Game implementation for testing https://github.com/MonoGame/MonoGame/pull/5585
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
namespace WindowResize
{
/// <summary>
/// A simple input handler. Add this as a component to your game to let it automatically update.
/// </summary>
public class Input : GameComponent
{
#region Action Map
/// <summary>
/// A list of gamepad buttons and keyboard keys.
/// </summary>
public class List
{
/// <summary>
/// Add the given button to the input list.
/// </summary>
public void Add(Buttons button)
{
GamePadButtons.Add(button);
}
/// <summary>
/// Add the given key to the input list.
/// </summary>
public void Add(Keys key)
{
KeyboardKeys.Add(key);
}
/// <summary>
/// List of GamePad buttons.
/// </summary>
internal readonly List<Buttons> GamePadButtons = new List<Buttons>();
/// <summary>
/// List of Keyboard keys.
/// </summary>
internal readonly List<Keys> KeyboardKeys = new List<Keys>();
}
/// <summary>
/// Check if any of the inputs registered for the given action is pressed.
/// </summary>
public static bool IsPressed(object action)
{
return IsActionPressed(ActionMaps[action]);
}
/// <summary>
/// Check if any of the inputs registered for the given action is down.
/// </summary>
public static bool IsDown(object action)
{
return IsActionDown(ActionMaps[action]);
}
/// <summary>
/// Check if any of the inputs registered for the given action is released.
/// </summary>
public static bool IsReleased(object action)
{
return IsActionReleased(ActionMaps[action]);
}
private static bool IsActionPressed(List map)
{
return map.KeyboardKeys.Any(IsPressed) ||
map.GamePadButtons.Any(IsPressed);
}
private static bool IsActionDown(List map)
{
return map.KeyboardKeys.Any(IsDown) ||
map.GamePadButtons.Any(IsDown);
}
private static bool IsActionReleased(List map)
{
return map.KeyboardKeys.Any(IsReleased) ||
map.GamePadButtons.Any(IsReleased);
}
private static Dictionary<object, List> ActionMaps { get; set; }
/// <summary>
/// Add or update the inputlist of the given action.
/// </summary>
/// <param name="action"></param>
/// <param name="list"></param>
public static void SetAction(object action, List list)
{
ActionMaps[action] = list;
}
/// <summary>
/// Remove the given action.
/// </summary>
/// <param name="action"></param>
public static void RemoveAction(object action)
{
ActionMaps.Remove(action);
}
/// <summary>
/// Clear all actions.
/// </summary>
public static void ClearActions()
{
ActionMaps.Clear();
}
#endregion
#region Constructor
/// <summary>Create a new Input object. Should be done only once in a game.</summary>
/// <remarks>
/// Recommended use in main Game class: <c>Components.Add(new Input(this));</c>
/// Alternatively keep a reference to this instance and update it manually every frame.
/// </remarks>
public Input(Game game) : base(game)
{
_keyboardState = Keyboard.GetState();
ActionMaps = new Dictionary<object, List>();
}
#endregion
#region Update
/// <summary>
/// Updates keyboard and gamepad states.
/// </summary>
/// <param name="gameTime"></param>
public override void Update(GameTime gameTime)
{
_lastKeyboardState = _keyboardState;
_keyboardState = Keyboard.GetState();
_lastGamePadState = _gamePadState;
_gamePadState = GamePad.GetState(PlayerIndex.One);
base.Update(gameTime);
}
#endregion
#region Keyboard
private static KeyboardState _keyboardState;
private static KeyboardState _lastKeyboardState;
/// <summary>
/// Check if the given key is released this frame.
/// </summary>
public static bool IsReleased(Keys key)
{
return _keyboardState.IsKeyUp(key) && _lastKeyboardState.IsKeyDown(key);
}
/// <summary>
/// Check if the given key is pressed this frame.
/// </summary>
public static bool IsPressed(Keys key)
{
return _keyboardState.IsKeyDown(key) && _lastKeyboardState.IsKeyUp(key);
}
/// <summary>
/// Check if the given key is down.
/// </summary>
public static bool IsDown(Keys key)
{
return _keyboardState.IsKeyDown(key);
}
#endregion
#region GamePad
private static GamePadState _gamePadState;
private static GamePadState _lastGamePadState;
/// <summary>
/// Check if the given button is released this frame.
/// </summary>
public static bool IsReleased(Buttons button)
{
return _gamePadState.IsButtonUp(button) && _lastGamePadState.IsButtonDown(button);
}
/// <summary>
/// Check if the given button is pressed this frame.
/// </summary>
public static bool IsPressed(Buttons button)
{
return _gamePadState.IsButtonDown(button) && _lastGamePadState.IsButtonUp(button);
}
/// <summary>
/// Check if the given button is down.
/// </summary>
public static bool IsDown(Buttons button)
{
return _gamePadState.IsButtonDown(button);
}
/// <summary>
/// Get the position of the left thumbstick.
/// </summary>
public static Vector2 LeftThumbStick()
{
return _gamePadState.ThumbSticks.Left;
}
/// <summary>
/// Get the position of the Right thumbstick.
/// </summary>
public static Vector2 RightThumbStick()
{
return _gamePadState.ThumbSticks.Right;
}
#endregion
}
}
using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace WindowResize
{
public class Game1 : Game
{
[STAThread]
private static void Main()
{
using (var game = new Game1())
game.Run();
}
readonly GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private SpriteFont _font;
private Texture2D _blank;
private Texture2D _gradient;
private double _totalSeconds;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//_graphics.PreferredBackBufferWidth = 1500;
//graphics.PreferredBackBufferHeight = scrDimensions.Y;
//Window.Position = Point.Zero;
//graphics.IsFullScreen = true;
//_graphics.HardwareModeSwitch = false;
Window.AllowUserResizing = true;
Window.ClientSizeChanged += PrintCSC;
foreach (var adapter in GraphicsAdapter.Adapters)
{
Console.WriteLine("=====================");
Console.WriteLine();
//Console.WriteLine(adapter.DeviceName);
Console.WriteLine();
Console.WriteLine(adapter.Description);
Console.WriteLine(adapter.SupportedDisplayModes.Count());
Console.WriteLine(adapter.CurrentDisplayMode.Width);
Console.WriteLine(adapter.CurrentDisplayMode.Height);
Console.WriteLine();
Console.WriteLine("DisplayModes:");
foreach (var dm in adapter.SupportedDisplayModes)
{
Console.WriteLine("-\t" + dm.Width);
Console.WriteLine(" \t" + dm.Height);
Console.WriteLine(" \t" + dm.Format);
}
}
}
private void PrintReset(object sender, EventArgs e)
{
Console.WriteLine("Device Reset");
}
private void PrintCSC(object sender, EventArgs e)
{
Console.WriteLine($"Client Size Changed! VP={GraphicsDevice.Viewport}s W={Window.ClientBounds.Width}; H={Window.ClientBounds.Height}");
}
private void PrintPDS(object sender, EventArgs e)
{
Console.WriteLine("Preparing Device Settings!");
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
Components.Add(new Input(this));
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
_spriteBatch = new SpriteBatch(GraphicsDevice);
_font = Content.Load<SpriteFont>("font");
_blank = new Texture2D(GraphicsDevice, 1, 1);
_blank.SetData(new[] {Color.White});
const int size = 2500;
_gradient = new Texture2D(GraphicsDevice, size, size);
var data = new Color[size * size];
for (var y = 0; y < size; y++)
for (var x = 0; x < size; x++)
data[size * y + x] = new Color((float) x / size, (float) y / size, 0.5f);
_gradient.SetData(data);
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
if (Input.IsPressed(Keys.H))
{
_graphics.HardwareModeSwitch = !_graphics.HardwareModeSwitch;
_graphics.ApplyChanges();
}
if (Input.IsPressed(Keys.F))
{
_graphics.ToggleFullScreen();
}
if (Input.IsPressed(Keys.S))
{
ChangeBackBuffer();
_graphics.ApplyChanges();
}
if (Input.IsPressed(Keys.B))
{
ChangeBackBuffer();
_graphics.HardwareModeSwitch = !_graphics.HardwareModeSwitch;
_graphics.ApplyChanges();
}
if (Input.IsPressed(Keys.M))
{
_graphics.PreferMultiSampling = !_graphics.PreferMultiSampling;
_graphics.ApplyChanges();
}
if (Input.IsPressed(Keys.P))
Console.WriteLine("Display mode is " + '\n' + GraphicsDevice.Adapter.CurrentDisplayMode + '\n');
_totalSeconds = gameTime.TotalGameTime.TotalSeconds;
_totalSeconds = gameTime.TotalGameTime.TotalSeconds;
base.Update(gameTime);
}
private void ChangeBackBuffer()
{
if (_graphics.PreferredBackBufferWidth == 840)
{
_graphics.PreferredBackBufferWidth = 400;
_graphics.PreferredBackBufferHeight = 340;
}
else
{
_graphics.PreferredBackBufferWidth = 840;
_graphics.PreferredBackBufferHeight = 600;
}
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_spriteBatch.Begin();
var w = GraphicsDevice.PresentationParameters.BackBufferWidth;
var h = GraphicsDevice.PresentationParameters.BackBufferHeight;
_spriteBatch.Draw(_gradient, new Vector2(w / 2f, h / 2f), null, Color.White, (float) gameTime.TotalGameTime.TotalSeconds,
new Vector2(_gradient.Width / 2f, _gradient.Height / 2f), new Vector2(1, 1), SpriteEffects.None, 0);
_spriteBatch.DrawString(_font, $"Width: {w}", new Vector2(100f, 100f), Color.Black);
_spriteBatch.DrawString(_font, $"Height: {h}", new Vector2(100f, 130f), Color.Black);
_spriteBatch.DrawString(_font, $"Window width: {Window.ClientBounds.Width}", new Vector2(100f, 160f), Color.Black);
_spriteBatch.DrawString(_font, $"Window height: {Window.ClientBounds.Height}", new Vector2(100f, 190f), Color.Black);
_spriteBatch.DrawString(_font, $"Hardware mode switch: {GraphicsDevice.PresentationParameters.HardwareModeSwitch}", new Vector2(100f, 220f), Color.Black);
_spriteBatch.Draw(_blank, new Rectangle(300, 300, 100, 100), null, Color.White, 0.05f, Vector2.Zero, SpriteEffects.None, 0);
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment