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

namespace Sprint3_actual
{
    class KeyboardController : IController
    {
        KeyboardState oldState;

        private Dictionary<Keys, ICommand> controllerMappings;
        private ICommand currentCommand;
        private ICommand idleCommand;
        private List<Keys> movementList;
        private HashSet<Keys> moveKeys;
        private HashSet<Keys> actionKeys;
        private HashSet<Keys> controlKeys;

        public KeyboardController(Game1 Game1)
        {
            controllerMappings = KeysAndCommands.LoadCommands(Game1);
            idleCommand = KeysAndCommands.getIdleCommand(Game1);
            movementList = new List<Keys>();
            moveKeys = KeysAndCommands.getKeySet("Movement");
            actionKeys = KeysAndCommands.getKeySet("Action");
            controlKeys = KeysAndCommands.getKeySet("Control");
        }
        public void RegisterCommand(Keys key, ICommand command)
        {
            controllerMappings.Add(key, command);

        }
        public void RegisterIdleCommand(ICommand command)
        {
            idleCommand = command;
            currentCommand = idleCommand;
        }
        public void Update()
        {
            KeyboardState keyboardState = Keyboard.GetState();
            currentCommand = idleCommand;
            
            
            // MOVEMENT KEYS
            foreach(Keys key in moveKeys)
            {
                if (!keyboardState.IsKeyDown(key))
                {
                    movementList.Remove(key);
                }

                if (keyboardState.IsKeyDown(key) && !oldState.IsKeyDown(key))
                {
                        movementList.Insert(0, key);
                }
            }
            if(movementList.Count > 0)
            {
                currentCommand = controllerMappings[movementList[0]];
            }


            // ACTION KEYS
            foreach(Keys key in actionKeys)
            {
                if (keyboardState.IsKeyDown(key) && !oldState.IsKeyDown(key))
                {
                    if(controllerMappings.ContainsKey(key))
                    {
                        currentCommand = controllerMappings[key];
                    }
                }
            }

            // CONTROL KEYS
            foreach (Keys key in controlKeys)
            {
                if (keyboardState.IsKeyDown(key) && !oldState.IsKeyDown(key))
                {
                    if (controllerMappings.ContainsKey(key))
                    {
                        currentCommand = controllerMappings[key];
                    }
                }
            }


            currentCommand.Execute();

            oldState = keyboardState;
        }
    }
}