-
Notifications
You must be signed in to change notification settings - Fork 320
/
app.js
252 lines (219 loc) · 9.1 KB
/
app.js
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
var createEditor = function() {
var lsKey = "elevatorCrushCode_v5";
var cm = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: false,
theme: "solarized light",
mode: "javascript",
autoCloseBrackets: true,
extraKeys: {
// the following Tab key mapping is from http://codemirror.net/doc/manual.html#keymaps
Tab: function(cm) {
var spaces = new Array(cm.getOption("indentUnit") + 1).join(" ");
cm.replaceSelection(spaces);
}
}
});
// reindent on paste (adapted from https://github.com/ahuth/brackets-paste-and-indent/blob/master/main.js)
cm.on("change", function(codeMirror, change) {
if(change.origin !== "paste") {
return;
}
var lineFrom = change.from.line;
var lineTo = change.from.line + change.text.length;
function reindentLines(codeMirror, lineFrom, lineTo) {
codeMirror.operation(function() {
codeMirror.eachLine(lineFrom, lineTo, function(lineHandle) {
codeMirror.indentLine(lineHandle.lineNo(), "smart");
});
});
}
reindentLines(codeMirror, lineFrom, lineTo);
});
var reset = function() {
cm.setValue($("#default-elev-implementation").text().trim());
};
var saveCode = function() {
localStorage.setItem(lsKey, cm.getValue());
$("#save_message").text("Code saved " + new Date().toTimeString());
returnObj.trigger("change");
};
var existingCode = localStorage.getItem(lsKey);
if(existingCode) {
cm.setValue(existingCode);
} else {
reset();
}
$("#button_save").click(function() {
saveCode();
cm.focus();
});
$("#button_reset").click(function() {
if(confirm("Do you really want to reset to the default implementation?")) {
localStorage.setItem("develevateBackupCode", cm.getValue());
reset();
}
cm.focus();
});
$("#button_resetundo").click(function() {
if(confirm("Do you want to bring back the code as before the last reset?")) {
cm.setValue(localStorage.getItem("develevateBackupCode") || "");
}
cm.focus();
});
var returnObj = riot.observable({});
var autoSaver = _.debounce(saveCode, 1000);
cm.on("change", function() {
autoSaver();
});
returnObj.getCodeObj = function() {
console.log("Getting code...");
var code = cm.getValue();
var obj;
try {
obj = getCodeObjFromCode(code);
returnObj.trigger("code_success");
} catch(e) {
returnObj.trigger("usercode_error", e);
return null;
}
return obj;
};
returnObj.setCode = function(code) {
cm.setValue(code);
};
returnObj.getCode = function() {
return cm.getValue();
}
returnObj.setDevTestCode = function() {
cm.setValue($("#devtest-elev-implementation").text().trim());
}
$("#button_apply").click(function() {
returnObj.trigger("apply_code");
});
return returnObj;
};
var createParamsUrl = function(current, overrides) {
return "#" + _.map(_.merge(current, overrides), function(val, key) {
return key + "=" + val;
}).join(",");
};
$(function() {
var tsKey = "elevatorTimeScale";
var editor = createEditor();
var params = {};
var $world = $(".innerworld");
var $stats = $(".statscontainer");
var $feedback = $(".feedbackcontainer");
var $challenge = $(".challenge");
var $codestatus = $(".codestatus");
var floorTempl = document.getElementById("floor-template").innerHTML.trim();
var elevatorTempl = document.getElementById("elevator-template").innerHTML.trim();
var elevatorButtonTempl = document.getElementById("elevatorbutton-template").innerHTML.trim();
var userTempl = document.getElementById("user-template").innerHTML.trim();
var challengeTempl = document.getElementById("challenge-template").innerHTML.trim();
var feedbackTempl = document.getElementById("feedback-template").innerHTML.trim();
var codeStatusTempl = document.getElementById("codestatus-template").innerHTML.trim();
var app = riot.observable({});
app.worldController = createWorldController(1.0 / 60.0);
app.worldController.on("usercode_error", function(e) {
console.log("World raised code error", e);
editor.trigger("usercode_error", e);
});
console.log(app.worldController);
app.worldCreator = createWorldCreator();
app.world = undefined;
app.currentChallengeIndex = 0;
app.startStopOrRestart = function() {
if(app.world.challengeEnded) {
app.startChallenge(app.currentChallengeIndex);
} else {
app.worldController.setPaused(!app.worldController.isPaused);
}
};
app.startChallenge = function(challengeIndex, autoStart) {
if(typeof app.world !== "undefined") {
app.world.unWind();
// TODO: Investigate if memory leaks happen here
}
app.currentChallengeIndex = challengeIndex;
app.world = app.worldCreator.createWorld(challenges[challengeIndex].options);
window.world = app.world;
clearAll([$world, $feedback]);
presentStats($stats, app.world);
presentChallenge($challenge, challenges[challengeIndex], app, app.world, app.worldController, challengeIndex + 1, challengeTempl);
presentWorld($world, app.world, floorTempl, elevatorTempl, elevatorButtonTempl, userTempl);
app.worldController.on("timescale_changed", function() {
localStorage.setItem(tsKey, app.worldController.timeScale);
presentChallenge($challenge, challenges[challengeIndex], app, app.world, app.worldController, challengeIndex + 1, challengeTempl);
});
app.world.on("stats_changed", function() {
var challengeStatus = challenges[challengeIndex].condition.evaluate(app.world);
if(challengeStatus !== null) {
app.world.challengeEnded = true;
app.worldController.setPaused(true);
if(challengeStatus) {
presentFeedback($feedback, feedbackTempl, app.world, "Success!", "Challenge completed", createParamsUrl(params, { challenge: (challengeIndex + 2)}));
} else {
presentFeedback($feedback, feedbackTempl, app.world, "Challenge failed", "Maybe your program needs an improvement?", "");
}
}
});
var codeObj = editor.getCodeObj();
console.log("Starting...");
app.worldController.start(app.world, codeObj, window.requestAnimationFrame, autoStart);
};
editor.on("apply_code", function() {
app.startChallenge(app.currentChallengeIndex, true);
});
editor.on("code_success", function() {
presentCodeStatus($codestatus, codeStatusTempl);
});
editor.on("usercode_error", function(error) {
presentCodeStatus($codestatus, codeStatusTempl, error);
});
editor.on("change", function() {
$("#fitness_message").addClass("faded");
var codeStr = editor.getCode();
// fitnessSuite(codeStr, true, function(results) {
// var message = "";
// if(!results.error) {
// message = "Fitness avg wait times: " + _.map(results, function(r){ return r.options.description + ": " + r.result.avgWaitTime.toPrecision(3) + "s" }).join("   ");
// } else {
// message = "Could not compute fitness due to error: " + results.error;
// }
// $("#fitness_message").html(message).removeClass("faded");
// });
});
editor.trigger("change");
riot.route(function(path) {
params = _.reduce(path.split(","), function(result, p) {
var match = p.match(/(\w+)=(\w+$)/);
if(match) { result[match[1]] = match[2]; } return result;
}, {});
var requestedChallenge = 0;
var autoStart = false;
var timeScale = parseFloat(localStorage.getItem(tsKey)) || 2.0;
_.each(params, function(val, key) {
if(key === "challenge") {
requestedChallenge = _.parseInt(val) - 1;
if(requestedChallenge < 0 || requestedChallenge >= challenges.length) {
console.log("Invalid challenge index", requestedChallenge);
console.log("Defaulting to first challenge");
requestedChallenge = 0;
}
} else if(key === "autostart") {
autoStart = val === "false" ? false : true;
} else if(key === "timescale") {
timeScale = parseFloat(val);
} else if(key === "devtest") {
editor.setDevTestCode();
} else if(key === "fullscreen") {
makeDemoFullscreen();
}
});
app.worldController.setTimeScale(timeScale);
app.startChallenge(requestedChallenge, autoStart);
});
});