Created
March 19, 2014 21:51
-
-
Save zhuowei/9652193 to your computer and use it in GitHub Desktop.
2048, as I would play it (with a little help from http://maythesource.com/2012/06/26/simulating-keypresses-keystrokes-with-javascript-for-use-with-greesemonkey-etc/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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