Last active
November 6, 2022 18:59
-
-
Save EvilYep/7458b242d88ccfd91089591256c7ca80 to your computer and use it in GitHub Desktop.
Konami Code as a Vue3 composable
This file contains 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
<script setup> | |
import konamiCode from "../composables/konamiCode"; | |
import { onMounted } from "vue"; | |
const { startKonamiCodeListener } = konamiCode(); | |
onMounted(() => { | |
startKonamiCodeListener(() => { console.log('God Mode Activated'); }); | |
}); | |
</script> |
This file contains 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
export default function konamiCode() { | |
const KONAMI_CODE = [ | |
'ArrowUp', | |
'ArrowUp', | |
'ArrowDown', | |
'ArrowDown', | |
'ArrowLeft', | |
'ArrowRight', | |
'ArrowLeft', | |
'ArrowRight', | |
'b', | |
'a', | |
]; | |
let c = 0; | |
function startKonamiCodeListener(cb) { | |
window.addEventListener("keydown", (e) => { | |
c = (e.key === KONAMI_CODE[c] ? c + 1 : (e.key !== 'ArrowUp' ? 0 : (c ? (KONAMI_CODE[c-1] === 'ArrowUp' ? c : 0) : 0))); | |
if (c === KONAMI_CODE.length) { | |
cb() | |
} | |
}); | |
} | |
return { | |
startKonamiCodeListener | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is one of the few implementations I could find that take into account the possibility of hitting "up" 3 times at the beginning (which would be a valid input) without resetting a counter