Skip to content

Instantly share code, notes, and snippets.

@varenc
Last active March 21, 2024 00:38
Show Gist options
  • Save varenc/727c2122caa738a0d9441014e7c96a51 to your computer and use it in GitHub Desktop.
Save varenc/727c2122caa738a0d9441014e7c96a51 to your computer and use it in GitHub Desktop.
2048 button masher to show how artless the game is
// This script just mashes Up and Left until its stuck, and then it presses Right. Plays decently, which is the sad part.
//
// tested on https://2048game.com/
// To use this just go to that page, open dev tools, and paste this JS in the console. Refresh the page to stop it.
const simulateKeyPress = (keyCode) => {
document.dispatchEvent(new KeyboardEvent('keydown', { keyCode, which: keyCode }));
};
const upArrowKeyCode = 38, leftArrowKeyCode = 37, rightArrowKeyCode = 39;
let toggle = true, hashCheckCount = 0, lastHash = hashDOM();
// chattyg wrote this
function hashDOM() {
const str = document.documentElement.innerHTML;
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) - hash + str.charCodeAt(i) | 0;
}
return hash;
}
let looper = setInterval(() => {
// alterntaively mash between Up and Left
simulateKeyPress(toggle ? upArrowKeyCode : leftArrowKeyCode);
toggle = !toggle;
const currentHash = hashDOM();
// If the DOM hash isn't changing, then we're stuck and its time to press the Right key
if (currentHash === lastHash) {
if (++hashCheckCount === 3) {
simulateKeyPress(rightArrowKeyCode);
simulateKeyPress(leftArrowKeyCode);
hashCheckCount = 0;
}
} else {
hashCheckCount = 0;
lastHash = currentHash;
}
}, 20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment