Skip to content

Instantly share code, notes, and snippets.

@kiwiz
Created July 10, 2020 02:56
Show Gist options
  • Save kiwiz/07bd96874df378bb632fa3472a7e65bb to your computer and use it in GitHub Desktop.
Save kiwiz/07bd96874df378bb632fa3472a7e65bb to your computer and use it in GitHub Desktop.
using System;
// using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using System.Reflection;
using StardewValley.Menus;
using System.Collections.Generic;
namespace KeyboardPP
{
/// <summary>Improve keyboard support in the game.</summary>
public class ModEntry : Mod {
private FieldInfo SInputStateField;
private MethodInfo OverrideButtonMethod;
private IClickableMenu ActiveMenu;
private Dictionary<SButton, SButton> titleKeyMap = new Dictionary<SButton, SButton>{
{SButton.Left, SButton.A},
{SButton.Right, SButton.D},
{SButton.Up, SButton.W},
{SButton.Down, SButton.S},
{SButton.Space, SButton.MouseLeft},
{SButton.Enter, SButton.MouseLeft},
};
public override void Entry(IModHelper helper) {
Type type = helper.Input.GetType();
SInputStateField = type.GetField("InputState", BindingFlags.NonPublic | BindingFlags.Instance);
OverrideButtonMethod = SInputStateField.GetValue(helper.Input).GetType().GetMethod("OverrideButton");
Helper.Events.Display.MenuChanged += this.OnEnterMenu;
helper.Events.Input.ButtonPressed += this.OnButtonPressed;
}
private void TranslateEvent(SButton from, SButton to, bool down) {
object inputState = SInputStateField.GetValue(Helper.Input);
OverrideButtonMethod.Invoke(inputState, new object[] { from, false });
OverrideButtonMethod.Invoke(inputState, new object[] { to, down });
}
private void OnEnterMenu(object sender, MenuChangedEventArgs e) {
ActiveMenu = e.NewMenu;
}
private void OnButtonPressed(object sender, ButtonPressedEventArgs e) {
bool isDown = e.IsDown(e.Button);
if (!Context.IsWorldReady) {
if (!titleKeyMap.ContainsKey(e.Button)) {
return;
}
TranslateEvent(e.Button, titleKeyMap[e.Button], isDown);
}
if(ActiveMenu == null) {
return;
}
if (e.Button.IsUseToolButton() && e.Button != SButton.MouseLeft) {
TranslateEvent(e.Button, SButton.MouseLeft, isDown);
} else if (e.Button.IsActionButton() && e.Button != SButton.MouseRight) {
TranslateEvent(e.Button, SButton.MouseRight, isDown);
}
// print button presses to the console window
this.Monitor.Log($"{Game1.player.Name} pressed {e.Button}.", LogLevel.Debug);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment