haixunMaster/lib/konami-code.ts

42 lines
902 B
TypeScript

/** 上上下下左右左右 B A B A */
export const KONAMI_SEQUENCE = [
"ArrowUp",
"ArrowUp",
"ArrowDown",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowLeft",
"ArrowRight",
"b",
"a",
"b",
"a",
] as const;
function normalizeKey(key: string): string {
return key.length === 1 ? key.toLowerCase() : key;
}
export function subscribeKonamiCode(onMatch: () => void): () => void {
let position = 0;
const onKeyDown = (event: KeyboardEvent) => {
const key = normalizeKey(event.key);
const expected = KONAMI_SEQUENCE[position];
if (key === expected) {
position += 1;
if (position >= KONAMI_SEQUENCE.length) {
position = 0;
onMatch();
}
return;
}
position = key === KONAMI_SEQUENCE[0] ? 1 : 0;
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}