Skip to content

Instantly share code, notes, and snippets.

@sunapi386
Last active August 29, 2015 13:57
Show Gist options
  • Save sunapi386/9522447 to your computer and use it in GitHub Desktop.
Save sunapi386/9522447 to your computer and use it in GitHub Desktop.
2048 bot
// Sometimes solves kortaggio's 5x5 variant of 2048: http://kortaggio.github.io/2048/
// Open the javascript console with F12 and copy past this in.
// export the game manager into the global namespace
GameManager.prototype.__original_actuate = GameManager.prototype.actuate;
GameManager.prototype.actuate = function() {
window.gm = this;
this.__original_actuate();
GameManager.prototype.actuate = GameManager.prototype.__original_actuate;
};
(function triggerFirstMove(first_move) {
event_obj = document.createEvent('Events');
event_obj.initEvent('keydown', true, true);
event_obj.keyCode = event_obj.which = first_move;
document.dispatchEvent(event_obj);
})(keycode = 37);
// instrument actuate to tell us if there was a move
GameManager.prototype.__original_actuate = GameManager.prototype.actuate;
GameManager.prototype.actuate = function() {
this.__moved = true;
this.__original_actuate();
}
GameManager.prototype.test_move = function test_move(direction) {
this.__moved = false;
this.move(direction);
return this.__moved;
};
(function auto_play() {
var UP = 0,
RIGHT = 1,
DOWN = 2,
LEFT = 3,
MOVE_TIMEOUT = 40; // ms
function preference_move(preferences) {
for(var pref_idx=0; pref_idx < preferences.length; pref_idx++) {
var move_succeeded = gm.test_move(preferences[pref_idx]);
if (move_succeeded) {
break;
}
}
}
(function auto_move() {
preferences = []
preferences.push(UP);
var lefties = 0;
var righties = 0;
for (var row=0; row<gm.grid.size; row++) {
for (var col=0; col<gm.grid.size; col++) {
var cell = { x: col,
y: row };
if (gm.grid.cellAvailable(cell)) {
if (col > (gm.grid.size / 2)) {
righties += 1;
} else {
lefties += 1;
}
}
}
}
var mixer = Math.random() - 0.5;
if (righties > lefties + mixer) {
preferences.push(RIGHT);
preferences.push(LEFT);
} else {
preferences.push(LEFT);
preferences.push(RIGHT);
}
preferences.push(DOWN)
preference_move(preferences)
setTimeout(auto_move, MOVE_TIMEOUT);
})();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment