Last active
February 23, 2025 21:41
-
-
Save MrGrigri/c3fbaab69ac97891e81f5884e3ed8f76 to your computer and use it in GitHub Desktop.
Angular Konami Service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { isPlatformBrowser } from '@angular/common'; | |
import { | |
EventEmitter, | |
inject, | |
Injectable, | |
Output, | |
PLATFORM_ID, | |
} from '@angular/core'; | |
@Injectable({ providedIn: 'root' }) | |
export class KonamiService { | |
#inputSequence: Array<string> = []; | |
#konamiCode: Array<string> = [ | |
'ArrowUp', | |
'ArrowUp', | |
'ArrowDown', | |
'ArrowDown', | |
'ArrowLeft', | |
'ArrowRight', | |
'ArrowLeft', | |
'ArrowRight', | |
'b', | |
'a', | |
]; | |
#platformId: {} = inject(PLATFORM_ID); | |
#successful: boolean = false; | |
get successful(): boolean { | |
return this.#successful; | |
} | |
@Output() konamiCodeActivated = new EventEmitter<void>(); | |
constructor() { | |
this.initialize(); | |
} | |
initialize() { | |
if (isPlatformBrowser(this.#platformId)) { | |
this.#addWindowKeydownHandler(); | |
} | |
} | |
destroy() { | |
this.#removeWindowKeydownHandler(); | |
} | |
#addWindowKeydownHandler() { | |
window.addEventListener( | |
'keydown', | |
this.#handleWindowKeydownEvent.bind(this) | |
); | |
} | |
#removeWindowKeydownHandler() { | |
window.removeEventListener( | |
'keydown', | |
this.#handleWindowKeydownEvent.bind(this) | |
); | |
} | |
#handleWindowKeydownEvent(event: KeyboardEvent) { | |
this.#inputSequence.push(event.key); | |
if (this.#inputSequence.length > this.#konamiCode.length) { | |
this.#inputSequence.shift(); | |
} | |
if (this.#inputSequence.join(',') === this.#konamiCode.join(',')) { | |
this.konamiCodeActivated.emit(); | |
this.#inputSequence = []; | |
this.#successful = true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment