-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
101 lines (88 loc) · 2.53 KB
/
index.ts
File metadata and controls
101 lines (88 loc) · 2.53 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
import fs from "fs";
import readline from "readline";
import commandParser from "commander";
import Simulator from "./simulator/simulator";
import { CompassDirection } from "./enums/movementEnums";
import ToyRobot from "./robotPlayer/robot";
import Table from "./table/tableTop";
class App {
private simulator: Simulator = new Simulator(
new ToyRobot(
new Table({
rows: 5,
columns: 5,
})
)
);
constructor() {
commandParser
.arguments("[filename]")
.description("Test robot using file data or user input.", {
filename: "File where test data is stored",
})
.action(async (filename: string) => {
if (filename) {
await this.startAutomatedMode(filename);
} else {
this.startInteractiveMode();
}
});
}
public start(): void {
console.clear();
commandParser.parse(process.argv);
}
private async startAutomatedMode(filename: string) {
const fileStream = fs.createReadStream(filename);
const terminal = readline.createInterface({
input: fileStream,
crlfDelay: Infinity,
});
for await (const line of terminal) {
console.log(line);
this.processCommand(line);
}
}
private startInteractiveMode() {
console.log(
"Welcome to the Toy robot simulator (start typing commands below)"
);
const terminal = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
const prompt = () => {
terminal.question("", (command: string) => {
this.processCommand(command);
prompt();
});
};
prompt();
}
private processCommand(command: string): void {
const placeCommandParsingExpression =
/^(PLACE) (\d+),(\d+),(SOUTH|NORTH|WEST|EAST)$/gm;
const placeCommandParameters = placeCommandParsingExpression.exec(command);
const otherCommandParsingExpression = /^(MOVE|LEFT|RIGHT|REPORT)$/gm;
const otherCommandParameters = otherCommandParsingExpression.exec(command);
if (placeCommandParameters) {
this.simulator.run({
name: placeCommandParameters[1],
orientation: {
position: {
x: Number(placeCommandParameters[2]),
y: Number(placeCommandParameters[3]),
},
direction: <CompassDirection>placeCommandParameters[4],
},
});
} else if (otherCommandParameters) {
this.simulator.run({
name: otherCommandParameters[1],
});
}
}
}
const app = new App();
app.start();