forked from ChalmersGU-AI-course/shrdlite-course-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshrdlite-ajax.ts
79 lines (70 loc) · 2.39 KB
/
shrdlite-ajax.ts
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
///<reference path="Parser.ts"/>
///<reference path="SVGWorld.ts"/>
///<reference path="ExampleWorlds.ts"/>
///<reference path="lib/jquery.d.ts" />
// Replace this with the URL to your CGI script:
var ajaxScript = "cgi-bin/shrdlite_cgi.py";
$(function(){
var startWorld = 'small';
var useSpeech = false;
var world = new SVGWorld(ExampleWorlds[startWorld], useSpeech);
ajaxInteractive(world);
});
function ajaxInteractive(world : World) : void {
function endlessLoop(utterance : string = "") : void {
var inputPrompt = "What can I do for you today? ";
var nextInput = () => world.readUserInput(inputPrompt, endlessLoop);
if (utterance.trim()) {
var plan = ajaxParseUtteranceIntoPlan(world, utterance);
if (plan) {
world.printDebugInfo("Plan: " + plan.join(", "));
world.performPlan(plan, nextInput);
return;
}
}
nextInput();
}
world.printWorld(endlessLoop);
}
function ajaxParseUtteranceIntoPlan(world : World, utterance : string) : string[] {
world.printDebugInfo('Parsing utterance: "' + utterance + '"');
try {
var parses : Parser.Result[] = Parser.parse(utterance);
} catch(err) {
if (err instanceof Parser.Error) {
world.printError("Parsing error: " + err.message);
return;
} else {
throw err;
}
}
world.printDebugInfo("Found " + parses.length + " parses");
parses.forEach((res, n) => {
world.printDebugInfo(" (" + n + ") " + JSON.stringify(res.prs));
});
world.printDebugInfo('Calling interpreter/planner using AJAX');
var ajaxData = JSON.stringify(
{stacks: world.currentState.stacks,
holding: world.currentState.holding,
arm: world.currentState.arm,
objects: world.currentState.objects,
utterance: utterance,
parses: parses,
});
var xhReq = new XMLHttpRequest();
xhReq.open("GET", ajaxScript + "?data=" + encodeURIComponent(ajaxData), false);
xhReq.send();
var response : string = xhReq.responseText;
world.printDebugInfo("AJAX response: " + response);
try {
var result = JSON.parse(response);
} catch(err) {
world.printError("JSON error:" + err);
return;
}
if (result.plan) {
return result.plan;
} else {
return result;
};
}