Skip to content

Instantly share code, notes, and snippets.

@joydeep-b
Created June 26, 2019 00:53
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 joydeep-b/ec953a58c84cf2b7d47495e659e8e814 to your computer and use it in GitHub Desktop.
Save joydeep-b/ec953a58c84cf2b7d47495e659e8e814 to your computer and use it in GitHub Desktop.
const r = require('robotLibrary');
const id = 0;
r.setId(id);
const gridCellSize = 300;
function getX() {
return Math.floor(r.queryWorld().ourBots[id].pX / gridCellSize + 0.5);
}
function getY() {
return Math.floor(r.queryWorld().ourBots[id].pY / gridCellSize + 0.5);
}
function moveX(x) {
console.log(`moveX(${x})`);
r.moveX((getX() + x) * gridCellSize);
}
function moveY(y) {
console.log(`moveY(${y})`);
r.moveY((getY() + y) * gridCellSize);
}
// Returns true iff the line joining (x1,y1) and (x2,y2) collides with the obstacle.
// NOTE: Assumes all numbers are integers, and the line is either vertical or horizontal.
function collides(obstX, obstY, x1, y1, x2, y2) {
if (x1 === x2) {
// Vertical move.
return (y1 - obstY) * (y2 - obstY) <= 0 && x1 === obstX;
} else if (y1 === y2) {
// Horizontal move.
return (x1 - obstX) * (x2 - obstX) <= 0 && y1 === obstY;
} else {
// Can't handle this: it's a diagonal move.
assert(false);
}
// WTF: how did we get here?
assert(false);
}
function goTo(x1, y1, x2, y2) {
const obstX = 0;
const obstY = 0;
// See if you can move horizontally, then vertically.
if (!collides(obstX, obstY, x1, y1, x2, y1) &&
!collides(obstX, obstY, x2, y1, x2, y2)) {
console.log(`horizonal, then vertical`);
moveX(x2 - x1);
moveY(y2 - y1);
return;
}
// See if you can move vertically, then horizontally.
if (!collides(obstX, obstY, x1, y1, x1, y2) &&
!collides(obstX, obstY, x1, y2, x2, y2)) {
console.log(`vertical, then horizontal`);
moveY(y2 - y1);
moveX(x2 - x1);
return;
}
// Does the vertical collide?
if (collides(obstX, obstY, x1, y1, x1, y2)) {
// Go right one, then do vertical and then horizontal.
console.log(`right, vertical, then left`);
moveX(1);
moveY(y2 - y1);
moveX(-1);
return;
}
// Does the horizontal collide?
if (collides(obstX, obstY, x1, y1, x2, y1)) {
// Go right one, then do vertical and then horizontal.
console.log(`right, vertical, then left`);
moveY(1);
moveX(x2 - x1);
moveY(-1);
return;
}
// Should not happen!
assert(false);
}
let x0 = -2;
let y0 = 0;
let x1 = 2;
let y1 = 0;
r.move(x0 * gridCellSize, y0 * gridCellSize, 0);
goTo(x0, y0, x1, y1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment