Skip to content

Instantly share code, notes, and snippets.

@ihatecsv
Created June 25, 2021 15:19
Show Gist options
  • Save ihatecsv/b1edf1e8763c6b26da6bda8b058d7fba to your computer and use it in GitHub Desktop.
Save ihatecsv/b1edf1e8763c6b26da6bda8b058d7fba to your computer and use it in GitHub Desktop.
Key combination detector (for the Konami Code and otherwise)
/**
* Reads sequences of keypresses, then activates a function when a sequential combo has been detected.
* @author Drake Luce <me@drakeluce.com>
*/
class KeyComboDetector {
/**
* Create a key combination detector.
* @param {function} functionToCall The function that is called when the combo has been detected.
* @param {boolean} [makeListener=true] Make internal listener for keypresses instead of using the detect method.
* @param {number[]} [code=[38, 38, 40, 40, 37, 39, 37, 39, 66, 65]] An array of keyCode values representing the sequence of keypresses needed to activate the combo.
*/
constructor(functionToCall, makeListener = true, code = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]){
this.functionToCall = functionToCall;
this.code = code;
this.keysSoFar = [];
const outerThis = this;
if(makeListener) window.addEventListener("keyup", function(event){
outerThis.detect(event);
});
}
/**
* Detect a keypress for combo detection.
* @param {KeyboardEvent} event The keyboard event from your listener.
*/
detect(event){
const nextKeyIndex = this.keysSoFar.length;
if (event.keyCode != this.code[nextKeyIndex]) return this.keysSoFar = [];
this.keysSoFar.push(event.keyCode);
if(this.keysSoFar.length == this.code.length){
this.keysSoFar = [];
this.functionToCall();
}
}
/**
* Change the sequence of keys needed to detect the combo. This resets the keys pressed so far.
* @param {number[]} code An array of keyCode values representing the sequence of keypresses needed to activate the combo.
*/
setCode(code){
this.code = code;
this.keysSoFar = [];
}
/**
* Change the function that is called when the combo has been detected.
* @param {function} functionToCall The functon that is called when the combo has been detected.
* @param {boolean} [resetKeysPressedSoFar=false] Whether the keys pressed so far should be reset.
*/
setFunctionToCall(functionToCall, resetKeysPressedSoFar = false){
this.functionToCall = functionToCall;
if (resetKeysPressedSoFar) this.keysSoFar = [];
}
}
// Example
const keyComboDetector = new KeyComboDetector(function(){
console.log("Cheat codes activated!");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment