Roses/Assets/Scripts/Domain/KeyHistory.cs
2024-04-15 00:15:39 +02:00

64 lines
No EOL
1.7 KiB
C#

using System.Collections.Generic;
using Extensions;
namespace Domain {
public class KeyHistory {
private readonly LimitedSizeList<int> _lastPresses = new(10);
private readonly int[] _customKeys = { 191, 51, 222, 186 };
private readonly bool[] _isPressed = new bool[26 + 5];
private readonly bool[] _wasPressed = new bool[26 + 5];
public void KeyPressed(int key) => _lastPresses.Add(key);
public void CheckPresses() {
const int aIndex = 0x41;
const int zIndex = 0x5A;
for (int i = aIndex, j = 0; i <= zIndex; i++, j++) {
_wasPressed[j] = _isPressed[j];
short state = Win32API.GetAsyncKeyState(i);
if (!_wasPressed[j] && state != 0) {
_isPressed[j] = true;
KeyPressed(i);
}else if (_isPressed[j] && state == 0) {
_isPressed[j] = false;
}
}
for (int i = 0; i < _customKeys.Length; i++) {
int pressIndex = 26 + i;
_wasPressed[pressIndex] = _isPressed[pressIndex];
short state = Win32API.GetAsyncKeyState(_customKeys[i]);
if (!_wasPressed[pressIndex] && state != 0) {
_isPressed[pressIndex] = true;
KeyPressed(_customKeys[i]);
}else if (_isPressed[pressIndex] && state == 0) {
_isPressed[pressIndex] = false;
}
}
}
public bool ContainsSequence(List<int> sequence) {
if (_lastPresses.List.Count < sequence.Count)
return false;
for (int i = 0; i < _lastPresses.List.Count; i++) {
if (i >= sequence.Count)
break;
int keyPressed = _lastPresses.List[_lastPresses.List.Count - 1 - i];
int sequenceKey = sequence[sequence.Count - 1 - i];
if (keyPressed != sequenceKey) {
return false;
}
}
_lastPresses.List.Clear();
return true;
}
}
}