xxxxxxxxxx
246
class CommandList {
constructor() {
this.list = [];
}
push(n) {
if (n === undefined) return;
switch (n) {
case 0:
this.list.push({
id: 0,
command: "emergency",
args: []
});
break;
case 1:
this.list.push({
id: 1,
command: "takeoff",
args: []
});
break;
case 2:
this.list.push({
id: 2,
command: "land",
args: []
});
break;
case 3:
this.list.push({
id: 3,
command: "up",
args: []
});
break;
case 4:
this.list.push({
id: 4,
command: "down",
args: []
});
break;
case 5:
this.list.push({
id: 5,
command: "left",
args: []
});
break;
case 6:
this.list.push({
id: 6,
command: "right",
args: []
});
break;
case 7:
this.list.push({
id: 7,
command: "forward",
args: []
});
break;
case 8:
this.list.push({
id: 8,
command: "back",
args: []
});
break;
case 9:
this.list.push({
id: 9,
command: "cw",
args: []
});
break;
case 10:
this.list.push({
id: 10,
command: "ccw",
args: []
});
break;
case 10:
this.list.push({
id: 10,
command: "flip",
args: []
});
break;
default:
break;
}
}
// adds argument to current command
add(n) {
if (n === undefined) return;
let cmd = this.list[this.list.length - 1];
console.log(n);
cmd.args.push(n);
}
send() {
for (let c of this.list) {
let text = "";
text += c.command;
for (let a of c.args) {
text += " " + a.toString();
}
console.log(c)
console.log(text)
droneCmd(text, true);
}
}
}
class BfStringIterator {
constructor(str) {
this.str = str;
this.index = 0;
}
next() {
return this.str[this.index++];
}
set( index ) {
this.index = index + 1;
}
}
/* [ { begin: number, end: number }... ] */
function DoesSubroutineExists(subroutine_list, {begin, end}, use_end = undefined) {
let test = use_end === undefined ? begin : end;
for (let sr of subroutine_list) {
if (use_end === undefined) {
if (sr.begin == begin) return true;
}
else if (sr.end == end) return true;
}
return false;
}
class BrainFuck {
constructor(str) {
this.str = str;
this.cmds = new CommandList();
}
interp() {
let index = 0;
let tape = [0, 0, 0, 0, 0, 0]
let subroutines = [];
let str_index = 0;
let string = new BfStringIterator(this.str);
let c = string.next();
while (c) {
switch (c) {
case '>':
index++;
break;
case '<':
index--;
break;
case '+':
tape[index] = tape[index] === undefined ? 1 : tape[index] + 1;
break;
case '-':
tape[index] = tape[index] === undefined ? -1 : tape[index] - 1;
break;
case '.':
this.cmds.push(tape[index]);
break;
case ',':
this.cmds.add(tape[index]);
break;
case '[':
if (!DoesSubroutineExists(subroutines, str_index)) {
let str = this.str.substr(str_index, string.length);
let nxt = 0;
while (str[nxt++] != ']') {
if (nxt >= str.length) break
}
subroutines.push({
begin: str_index,
end: str_index + nxt
});
}
if (tape[index] == 0) {
str_index = subroutines[subroutines.length - 1].end + 1;
string.set(str_index);
}
break;
case ']': {
console.log(tape[index]);
if (tape[index] == 0) {
subroutines.pop();
} else {
string.set(subroutines[subroutines.length - 1].begin);
}
}
}
str_index++;
c = string.next();
}
}
run() {
this.interp();
this.cmds.send();
}
}