-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2048-solver.js
83 lines (68 loc) · 1.67 KB
/
2048-solver.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
/**
* Specifically made for the 2048 8x8 strategy
*/
// https://2048game.club/2048-8x8-board/
// https://api.razzlepuzzles.com/2048
(() => {
const CONFIG = {
/** expressed in ms (milliseconds) */
INTERVAL_TIMEOUT: 0,
DEBUG: false,
CANCEL_WITH_TIMEOUT: false,
/** expressed in ms (milliseconds) */
DEBUG_TIMEOUT_STOP: 1_250,
CANCELLED: false,
};
const logDebug = (...data) => {
if (!CONFIG.DEBUG) {
return;
}
console.log(...data);
};
const KeyboardInput = {
UP: { key: "ArrowUp", which: 38 },
RIGHT: { key: "ArrowRight", which: 39 },
DOWN: { key: "ArrowDown", which: 40 },
LEFT: { key: "ArrowLeft", which: 37 },
};
/**
* @param {KeyboardInput} key
*/
const press = (key) => {
logDebug(key);
document.dispatchEvent(new KeyboardEvent("keydown", key));
};
const actions = [
() => press(KeyboardInput.UP),
() => press(KeyboardInput.RIGHT),
() => press(KeyboardInput.DOWN),
() => press(KeyboardInput.LEFT),
];
let currentIndex = 0;
const iterate = () => {
if (CONFIG.CANCELLED) {
return;
}
const currentAction = actions[currentIndex];
currentAction();
currentIndex++;
if (currentIndex >= actions.length) {
currentIndex = 0;
}
};
let intervalId;
const resume = () => {
CONFIG.CANCELLED = false;
intervalId = setInterval(iterate, CONFIG.INTERVAL_TIMEOUT);
};
resume();
const cancel = () => {
logDebug("Stopping...");
CONFIG.CANCELLED = true;
clearInterval(intervalId);
};
if (CONFIG.DEBUG && CONFIG.CANCEL_WITH_TIMEOUT) {
setTimeout(cancel, CONFIG.DEBUG_TIMEOUT_STOP);
}
return { resume, cancel };
})();