Game-Design / Sprint3 / KeyboardController.cs
KeyboardController.cs
Raw
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Text;

namespace Sprint2_actual
{
    class KeyboardController : IController
    {
        KeyboardState oldState;

        private Dictionary<Keys, ICommand> controllerMappings;
        private ICommand idleCommand;
        public KeyboardController()
        {
            controllerMappings = new Dictionary<Keys, ICommand>();
        }
        public void RegisterCommand(Keys key, ICommand command)
        {
            controllerMappings.Add(key, command);
        }
        public void RegisterIdleCommand(ICommand command)
        {
            idleCommand = command;
        }
        public void Update()
        {
            KeyboardState keyboardState = Keyboard.GetState();
            Keys[] pressedKeys = keyboardState.GetPressedKeys();
            if (pressedKeys.Length == 0)
            {
                idleCommand.Execute();
            }
            foreach (Keys key in pressedKeys)
            {
                {
                    if(controllerMappings.ContainsKey(key) && !oldState.IsKeyDown(key))
                    { 
                        controllerMappings[key].Execute();
                    }
                }
            }

            oldState = keyboardState;
        }
    }
}