Skip to content

Instantly share code, notes, and snippets.

@zhuowei
Created March 19, 2014 21:51
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 zhuowei/9652193 to your computer and use it in GitHub Desktop.
Save zhuowei/9652193 to your computer and use it in GitHub Desktop.
(function(){
var gridElem = document.getElementsByClassName("grid-cell")
function FakeInputManager(){}
function FakeScoreManager(){}
function FakeActuator(){}
FakeInputManager.prototype = {"on": function(){}};
FakeScoreManager.prototype = {"get": function(){return 0}, "set": function(){}};
FakeActuator.prototype = {"actuate": function(){}, "continue": function(){}, "clearContainer": function(){}, "addTile": function(){}, "applyClasses": function(){}};
var gm = new GameManager(4, FakeInputManager, FakeActuator, FakeScoreManager);
var moveKey = [38, 39, 40, 37];
var lastMove = 0;
function solveTick() {
var beginScore = gm.score;
var highestMove = (lastMove + 1) % 4;
var highestScore = 0;
for (var i = 0; i < 4; i++) {
updateGrid();
gm.move(i);
if (gm.score > highestScore) {
highestScore = gm.score;
highestMove = i;
}
gm.score = beginScore;
}
updateGrid();
gm.move(highestMove);
pressKeySim(moveKey[highestMove]);
lastMove = highestMove;
}
function pressKeySim(key) {
var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";
keyboardEvent[initMethod](
"keydown", // event type : keydown, keyup, keypress
true, // bubbles
true, // cancelable
window, // viewArg: should be window
false, // ctrlKeyArg
false, // altKeyArg
false, // shiftKeyArg
false, // metaKeyArg
key, // keyCodeArg : unsigned long the virtual key code, else 0
0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);
console.log(key);
}
function updateGrid() {
gm.grid.eachCell(function(x, y, val) {
theCell = document.getElementById("tile-position-" + x + "-" + y);
if (theCell == null) {
gm.grid.cells[x][y] = null;
} else {
gm.grid.cells[x][y] = new Tile({x: x, y: y}, parseInt(theCell.textContent));
}
});
}
setInterval(solveTick, 500);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment