# Changing game controls using .txt file

I'm using XNA to create a simple block breaker game. At the moment I have controls set in the standard way:

if (keystate.IsKeyDown(Keys.s))


I've figured out the file handling problems involved and have taken in a string from a text box, for examples sake I'll have that string as "NumPad2". Now I need the game to take that string and somehow use "NumPad2" as the new control, instead of "s".

Just use Enum.Parse, something like this:

var key = (Keys) Enum.Parse(typeof(Keys), keyString);


where keyString = "NumPad2", as you declared previously

• Brilliant. This is exactly what I was looking for. – Matthew Morgan Mar 27 '13 at 10:48
• @MatthewMorgan Ah, okay, I guess the wording of the question confused me. As a long-term solution, you should still consider using some kind of built-in serialization to store your settings. – Marton Mar 27 '13 at 10:59
• It might be better to use Enum.TryParse in the event that you want to do error handling without handling the exceptiont hat enum.parse would throw in the event of an invalid string value. – Tetrad Mar 27 '13 at 22:09

Create an IXmlSerializable class that handles saving / loading of the key settings. For example:

public class ControlSettings : IXmlSerializable
{
public Keys MoveUp;
public Keys MoveDown;
public Keys Shoot;

public ControlSettings() {}
//...
}


When you start the game, create a new instance of ControlSettings by deserializing an XML that defines the assigned keyboard controls (let's call this instance myControlSettings). Then in your game code:

if (keystate.IsKeyDown(myControlSettings.MoveUp))
{
//...
}

• I think the real important take away here, even though its kind of confusing since Keys is already used in XNA, is you should really map your inputs to actions (Shoot is the real hint at this) and have a class that performs the conversion between Inputs and Actions. This class could be created using the technique described in the other answer. – SpartanDonut Mar 27 '13 at 17:04
• @ToddersLegrande Yes, you're right, I'll edit the names of the Up and Down variables. – Marton Mar 27 '13 at 22:00