Skip to content

Instantly share code, notes, and snippets.

@OrKoN
Last active July 24, 2019 08:20
Show Gist options
  • Save OrKoN/b3391c6ff9c2132e5054e95657528644 to your computer and use it in GitHub Desktop.
Save OrKoN/b3391c6ff9c2132e5054e95657528644 to your computer and use it in GitHub Desktop.
Autonomous LumberJack
var c = document.getElementById('canvas_wrap').children[0];
var gl = c.getContext('webgl', { preserveDrawingBuffer: true });
function getColor(pixels, y) {
var color =
decimalToHex(pixels[y * 4], 2) +
decimalToHex(pixels[y * 4 + 1], 2) +
decimalToHex(pixels[y * 4 + 2], 2);
return color;
}
const treeColors = ['886332', '986d35', 'a17438', '7ead4f', '99cc66', 'afdd7f'];
function decimalToHex(d, padding) {
var hex = Number(d).toString(16);
padding =
typeof padding === 'undefined' || padding === null
? (padding = 2)
: padding;
while (hex.length < padding) {
hex = '0' + hex;
}
return hex;
}
function testTree(pixels, i = 0) {
// console.log(
// '%c #' + getColor(pixels, 211 + i * 50),
// `background: ${'#' + getColor(pixels, 211 + i * 50)};`,
// );
return treeColors.indexOf(getColor(pixels, 211 + i * 50)) !== -1;
}
function readPixels() {
const height = 600;
var left = new Uint8Array(height * 4);
gl.readPixels(216, 1, 1, height, gl.RGBA, gl.UNSIGNED_BYTE, left);
var right = new Uint8Array(height * 4);
gl.readPixels(386, 1, 1, height, gl.RGBA, gl.UNSIGNED_BYTE, right);
return { left, right };
}
async function sleep(ms) {
await new Promise((resolve, reject) => {
setTimeout(resolve, ms);
});
if (
getComputedStyle(document.getElementById('button_left').children[1])
.display == 'block'
) {
throw new Error('ddd');
}
}
function clickLeft() {
document.getElementById('button_left').click();
}
function clickRight() {
document.getElementById('button_right').click();
}
function notD(d) {
return d === 'left' ? 'right' : 'left';
}
async function start(position) {
const clicks = {
left: clickLeft,
right: clickRight,
};
const directions = ['left', 'right'];
const lookahead = 8;
while (true) {
await sleep(165);
const data = readPixels();
const tests = {
left: [],
right: [],
};
for (var k = 0; k <= lookahead; k++) {
for (var d of directions) {
tests[d].push(testTree(data[d], k));
}
}
for (var t of tests[position]) {
if (!t) {
clicks[position]();
await sleep(35);
} else {
clicks[notD(position)]();
position = notD(position);
await sleep(35);
break;
}
}
}
return position;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment