-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
93 lines (77 loc) · 1.87 KB
/
game.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var Move = {
UP: 0,
RIGHT: 1,
DOWN: 2,
LEFT: 3
}
var MoveToKeyCode = {
0: 38, // Up
1: 39, // Right
2: 40, // Down
3: 37, // Left
}
/**
* Execute a move repeatly.
* The interval is set in GameConfig.
*/
function startGame() {
setTimeout(function () {
var grid = getGrid(document);
getBestMove(grid, function(move){
moveTo(move);
startGame();
});
}, GameConfig.interval);
}
startGame();
/**
* Ask to the REST API at http://localhost:3000/next-move
* which is the best next move and return it
*/
function getBestMove(grid, cb) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/next-move", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
cb(xhr.responseText);
}
}
xhr.send(JSON.stringify(grid));
}
/**
* Execute the next move in the grid.
*/
function moveTo(move) {
evt = new KeyboardEvent('keydown', {
bubbles: true
})
// Chromium Hack
Object.defineProperty(evt, 'which', {
get: function () {
return MoveToKeyCode[move];
}
});
document.body.dispatchEvent(evt);
}
/**
* Return the grid status as a matrix of integer.
*/
function getGrid(dom) {
var grid = [];
for (var r = 1; r < 5; r++) {
var row = [];
for (var c = 1; c < 5; c++) {
var cell = 0;
try {
var potentialCells = dom.getElementsByClassName('tile-position-' + c + '-' + r);
cell = potentialCells[potentialCells.length-1]
.getElementsByClassName('tile-inner')[0].innerHTML;
} catch (e) {
}
row.push(parseInt(cell));
}
grid.push(row);
}
return grid;
}