Skip to content

Instantly share code, notes, and snippets.

@chaitan94
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaitan94/9571044 to your computer and use it in GitHub Desktop.
Save chaitan94/9571044 to your computer and use it in GitHub Desktop.
2048 Autopilot

This is a autopilot for the game 2048 by gabrielecirulli.

How to use:

  1. Open the game
  2. If you're using Chrome, open console from Dev tools (F12>Console)
  3. Paste the autopilot.js javascript
  4. Profit.

You can also type ap_stop() to stop the autopilot and ap_start() to start it again.

var ap_Tile = function(val,pos){
this.val = val;
this.pos = pos;
}
var ap_tiles = [];
ap_Tile.get = function(x,y){
for (var i = 0; i < ap_tiles.length; i++) {
if (ap_tiles[i].pos.x == x && ap_tiles[i].pos.y == y){
return ap_tiles[i];
}
};
return false;
}
var ap_vectors = [
{x: 0, y:-1},
{x: 1, y:0},
{x: 0, y:1},
{x: -1, y:0},
];
var ap_refresh_tiles = function(){
ap_tiles = [];
var ap_t = document.querySelectorAll(".tile");
for (var i = 0; i < ap_t.length; i++) {
var ap_c = ap_t[i].classList;
var ap_v = parseInt(ap_c[1].substr(5));
var ap_p = {
x: parseInt(ap_c[2][14]),
y: parseInt(ap_c[2][16])
};
var ap_f = true;
for (var j = 0; j < ap_tiles.length; j++) {
if (ap_tiles[j].pos.x == ap_p.x && ap_tiles[j].pos.y == ap_p.y){
ap_f = false;
if(ap_tiles[j].val < ap_v){
ap_tiles[j].val = ap_v;
break;
}
}
};
if(ap_f){
ap_tiles.push(new ap_Tile(ap_v,ap_p));
}
};
}
var ap_think = function(){
ap_refresh_tiles();
for (var i = 0; i < ap_tiles.length; i++) {
tile = ap_tiles[i];
for (var th = 0; th < ap_vectors.length; th++) {
for (var ra = 1; ra < 4; ra++) {
var vec = ap_vectors[th];
var cell = ap_Tile.get(tile.pos.x + ra*vec.x, tile.pos.y + ra*vec.y);
if (cell){
if(cell.val === tile.val) return th;
else break;
}
}
}
}
return -1;
}
var ap_move = function(n){
var key;
switch(n){
case 0: key = 38; break;//up
case 1: key = 39; break;//right
case 2: key = 40; break;//down
case 3: key = 37; break;//left
}
if(key){
var eventObj = document.createEventObject ?
document.createEventObject() : document.createEvent("Events");
if(eventObj.initEvent)
eventObj.initEvent("keydown", true, true);
eventObj.key = key;
eventObj.which = key;
document.dispatchEvent ? document.dispatchEvent(eventObj) : document.fireEvent("onkeydown", eventObj);
}
};
var game;
var ap_nextMove = function(){
var a = ap_think();
ap_move(a);
};
var ap_play = function(){game = setInterval(ap_nextMove,200); }
var ap_stop = function(){clearInterval(game); }
ap_play();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment