المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Passing a dictionary over raising multiple events in game scenerio



C# Programming
11-26-2009, 04:43 AM
My question is summarized quite well above but I feel I should provide a little more detail.
I'm writing a input system in Xna. Would it be better to raise a single event that sends a dictionary containing all the modified keys/their ids as an event argument or should I raise a seperate event for each one?

Please realized this is greatly simplified and is only intended to provide a quick visual representation as to what I am talking about.
class InputStateEventArgs
{
public Dictionary ModifiedKeys;
}

// in controller class
void update()
{
InputStateEventArgsargs = new InputStateEventArgs();
// process input

// loop through input data determining which keys change and what their states are
if (thisKeyChanged)
args.ModifiedKeys.Add(keyName, keyId);
// loop

if (args.ModifiedKeys.Count > 0)
if (InputStateChanged != null)
InputStateChanged(this, args);
}
// ...

// in game code
void InputStateChangedHandler(IController controller, InputStateEventArgs args)
{
foreach (KeyValuePairmodifiedKey in args.ModifiedKeys)
{
string keyName = modifiedKey.Key;
int keyId = modifiedKey.Value;

if (keyName == "Keys.Space")
if (controller.CurrentInputState[keyId] == InputState.Pressed)
// do something, the space key was pressed
}
}


--OR--
class InputStateEventArgs
{
public string KeyName;
public int KeyId;
}

// in controller class
void update()
{
InputStateEventArgsargs = new InputStateEventArgs();
// process input

// loop through input data determining which keys change and what their states are
if (thisKeyChanged)
{
args.KeyName = keyName;
args.KeyId = keyId;

if (InputStateChanged != null)
InputStateChanged(this, args);
}

// loop
}
// ...

// in game code
void InputStateChangedHandler(IController controller, InputStateEventArgs args)
{
if (args.KeyName == "Keys.Space")
if (controller.CurrentInputState[args.KeyId] == InputState.Pressed)
// do something, the space key was pressed
}


Remember, this is in a video game context and there will probably never be more than a few key presses per frame. Is the overhead of the dictionary too much?

The benefits I gain are that processing multi-key inputs become easier. For example, the dictionary allows me to use expressions like 'if Key.A and Key.B and Key.C then DoSomethingSpecial' whereas with the seperate input events I'd have to save the states of these keys and then act on them later in an update function.

Perhaps I can figure out how to implement both methods and have them selectable.