Skip to content

Instantly share code, notes, and snippets.

@tkalve
Created December 22, 2025 14:56
Show Gist options
  • Select an option

  • Save tkalve/cb99348fcb723dc13fa9f06b4c922dcb to your computer and use it in GitHub Desktop.

Select an option

Save tkalve/cb99348fcb723dc13fa9f06b4c922dcb to your computer and use it in GitHub Desktop.
useCheatCodes react hook
/**
* @author Thomas Kalve <https://github.com/tkalve>
*/
import { useRef, useCallback, useEffect } from "react";
/**
* Listens to cheat code sequences and triggers a callback when any sequence is entered
*
* @param callback - Function to call when any cheat code is entered
*/
export function useCheatCodes(callback: (name: string) => void): void {
useCheatCode("RG9vbSBHb2QgbW9kZXxpfGR8ZHxxfGQ=", callback);
useCheatCode("U2ltIENpdHkgMjAwMCBkZWJ1ZyBjaGVhdHxwfHJ8aXxzfGN8aXxsfGx8YQ==", callback);
useCheatCode("S29uYW1pIGNvZGV8QXJyb3dVcHxBcnJvd1VwfEFycm93RG93bnxBcnJvd0Rvd258QXJyb3dMZWZ0fEFycm93UmlnaHR8QXJyb3dMZWZ0fEFycm93UmlnaHR8YnxhfEVudGVy", callback);
useCheatCode("TW9ydGFsIEtvbWJhdCBCbG9vZCBjb2RlfGF8YnxhfGN8YXxifGI=", callback);
useCheatCode("VGhlIFNpbXMgTW9uZXkgY2hlYXR8cnxvfHN8ZXxifHV8ZA==", callback);
}
/**
* Listens to a single cheat code sequence and triggers a callback when the sequence is entered
*
* @param input - Base64 encoded cheat code in format btoa("Name|k|e|y|s")
* @param callback - Function to call when the cheat code is entered
*/
function useCheatCode(input: string, callback: (name: string) => void): void {
const parts = atob(input).split("|");
const name = parts.shift() ?? "";
const sequence = parts;
const buffer = useRef<string[]>([]);
const keySequence = useCallback(
(event: KeyboardEvent) => {
if (event.defaultPrevented) return;
if (event.key === sequence[buffer.current.length]) {
buffer.current = [...buffer.current, event.key];
} else {
buffer.current = [];
}
if (buffer.current.length === sequence.length) {
const bufferString = buffer.current.toString();
const sequenceString = sequence.toString();
if (sequenceString === bufferString) {
//console.trace("Code entered: ", name);
callback(name);
}
}
},
[callback, name, sequence]
);
useEffect(() => {
document.addEventListener("keydown", keySequence);
return () => document.removeEventListener("keydown", keySequence);
}, [keySequence]);
}
@tkalve
Copy link
Author

tkalve commented Dec 22, 2025

Cheat codes before Base64 encoding:

Doom God mode|i|d|d|q|d
Sim City 2000 debug cheat|p|r|i|s|c|i|l|l|a
Konami code|ArrowUp|ArrowUp|ArrowDown|ArrowDown|ArrowLeft|ArrowRight|ArrowLeft|ArrowRight|b|a|Enter
Mortal Kombat Blood code|a|b|a|c|a|b|b
The Sims Money cheat|r|o|s|e|b|u|d

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment