-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsimple.js
More file actions
365 lines (306 loc) · 11.1 KB
/
simple.js
File metadata and controls
365 lines (306 loc) · 11.1 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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
// Copyright (c) 2012 Pontus Walck, Mikael Tylmad
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy,
// modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
// BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
window.onload = init;
Function.prototype.bind || (Function.prototype.bind = function(thisObj/*, ...boundArgs*/)
{
var fn = this
var boundArgs = Array.prototype.slice.call(arguments, 1)
return function(/*...args*/)
{
var args = Array.prototype.slice.call(arguments)
return fn.apply(thisObj, boundArgs.concat(args))
}
})
// Loads the given URL as javascript, and runs the passed callback when
// the script has loaded.
function loadScript(url, callback)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
// Prepares the global `canvas` to occupy the whole page.
function prepareCanvas()
{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvas.style.width = window.innerWidth;
canvas.style.height = window.innerHeight;
totalWidth = canvas.width;
totalHeight = canvas.height;
}
function init()
{
// Prepare the global `canvas`.
canvas = document.createElement('canvas');
canvas.id = 'canvas';
canvas.style.position = 'absolute';
canvas.style.left = '0';
canvas.style.top = '0';
document.body.setAttribute("oncontextmenu", "return false");
document.body.appendChild(canvas);
// Hide the address bar on iPhone/iPad
var head = document.getElementsByTagName('head')[0];
var iOSMeta = document.createElement('meta');
iOSMeta.name = "apple-mobile-web-app-capable";
iOSMeta.content = "yes";
head.appendChild(iOSMeta);
updatesPerSecond = 30;
suppressErrors = false;
// Prepare the canvas
prepareCanvas();
var simplify = function()
{
c = new RoboroCanvas('canvas');
k = new RoboroKeyboard();
math = new RoboroMath(totalWidth/2, totalHeight/2, totalHeight/6, c);
trig = math;
turtle = new RoboroTurtle(totalWidth/2, totalHeight/2, c);
var roboroSound = new RoboroSound();
window.playSound = function(url, volume) { roboroSound.playSound(url, volume) };
window.setVolume = function(url, volume) { roboroSound.setVolume(url, volume) };
window.loopSound = function(url, volume) { roboroSound.loopSound(url, volume) };
window.stopSound = function(url) { roboroSound.stopSound(url) };
window.preloadSound = function(url) { roboroSound.preloadSound(url) };
window.gps = c.gps;
window.mouse = c.mouse;
window.keyboard = k;
// Import some common things from `Math` to the global namespace.
importMethods(window, Math, ["sin", "cos", "tan", "asin", "acos", "atan", "round",
"sqrt", "floor", "ceil", "PI", "abs", "pow"], true)
// Also import a bunch of canvas-related functions from the special canvas
// that occupies the whole page into the global namespace.
var functions =
["circle",
"rectangle",
"triangle",
"ring",
"arc",
"text",
"random",
"randomAlternative",
"shuffle",
"promptNumber",
"picture",
"clearScreen",
"fill",
"distance",
"distance3D",
"mixColor",
"randomColor",
"save",
"restore",
"translate",
"scale",
"rotate",
"rotateRadians",
"line",
"arrow",
"getPixel",
"stopUpdate",
"store",
"load",
"startGPS",
"stopGPS",
"distanceGeoCoord",
"calculateGeoCoord",
"randomGeoCoord"];
importMethods(window, c, functions)
window.touchscreen = c.touchscreen;
window.hideMouse = function() { canvas.style.cursor = 'none'; };
window.showMouse = function() { canvas.style.cursor = 'default'; };
loadAndEvalScript()
// See if the special entry-points `start` and `update` are defined, and if
// so, make sure to either execute `start` or setup a timer that keeps
// running `update`.
if (typeof(start) != "undefined")
start();
if (typeof(update) != "undefined")
c.update = function()
{
c.updatesPerSecond = window.updatesPerSecond;
update();
}
// Imports the given methods from object `source` to object `target`, being
// attached to `target` and with their 'this' bound to `source`.
// If `lowercaseNames` is true, then the names of the methods being added
// to `target` are transformed to lowercase. If `source[name]` for a given
// name isn't a function, then it is just copied over.
function importMethods(target, source, methods, lowercaseNames)
{
methods.forEach(function(name)
{
var newName = (lowercaseNames ? name.toLowerCase() : name);
if (typeof source[name] == 'function')
target[newName] = source[name].bind(source);
else
target[newName] = source[name];
});
return target;
}
// Find the script tag that included simple.js, and eval its body.
function loadAndEvalScript()
{
var elems = document.getElementsByTagName('script')
for (var i=0; i<elems.length; i++)
{
var el = elems[i];
var globalEval = wrapWithTryCatch(eval);
if (el.src.match(/simple\.js$/))
globalEval(el.innerHTML);
}
// Patch global `start` or `update` with a try-catch that prints stuff to
// our custom error console.
if (window.start)
window.start = wrapWithTryCatch(window.start);
if (window.update)
window.update = wrapWithTryCatch(window.update);
function wrapWithTryCatch(fn)
{
return function(/*...args*/)
{
try
{
fn.apply(this, arguments);
}
catch (err)
{
console.log("Caught error! Do we have appendErrorToConsole?",
Boolean(window.appendErrorToConsole));
// Append error, if errorconsole has loaded.
if (window.appendErrorToConsole)
appendErrorToConsole(err);
throw err; // re-throw the error so the browser's console can also
// catch it.
}
};
}
}
};
loadErrorConsole();
loadScript("https://www.koda.nu/advanced.js", simplify);
}
function loadErrorConsole() {
var errorConsole;
var global = this;
global.appendErrorToConsole = function(err) {
if (!errorConsole)
{
errorConsole = createErrorConsole();
}
var li = createErrorLi(err);
errorConsole.ul.appendChild(li);
// Creates a list element for the given Error `err`.
function createErrorLi(err) {
var timestampEl = span('timestamp', [ formatDate(new Date()) ]);
var messageEl = span('message', [ err.message ]);
var metadataEl = span('metadata', ('lineNumber' in err)
&& [ String(err.lineNumber) ]);
var li = createElement('li', {}, [ timestampEl,
messageEl,
metadataEl ]);
return li;
// Helpers
function span(className, children) {
return createElement('span', {className:className}, children)
}
function formatDate(date) {
return [ date.getHours(),
date.getMinutes(),
date.getSeconds() ].map(pad2).join(":")
// pads a number to two digits.
function pad2(num) {
return (num < 10 ? "0" : "") + num
}
}
}
};
function createErrorConsole() {
var ul = createElement('ul');
var container = createElement('div', {className:'error-console'}, [ ul ]);
addStyle([
".error-console {",
" position: fixed;",
" top: 80%;",
" bottom: 0.5em;",
" left: 0.5em;",
" right: 0.5em;",
"",
" overflow: auto;",
"",
" border-radius: 0.4em;",
" background: rgba(0,0,0, 0.8);",
" border: 1px solid #DDD;",
" box-shadow: 0 0 10px #000;",
" color: #DDD;",
"}",
"",
".error-console ul {",
" list-style-type: none;",
" padding: 0.4em;",
" font-family: monospace;",
"}",
"",
".error-console .timestamp::before { content: '[' }",
".error-console .timestamp::after { content: '] ' }",
".error-console .timestamp, .error-console .metadata { color: #888 }",
".error-console .metadata { float: right }",
].join("\n"));
document.body.appendChild(container);
return { ul: ul,
container: container }
}
function addStyle(css) {
var style = createElement('style', {type:'text/css'});
style.innerHTML = css;
document.head.appendChild(style);
return style;
}
// Creates an element, with optional parameters for attributes and children.
// If `children` is given, `attrs` must also be given. Strings in the
// `children` array gets converted to string nodes.
function createElement(name, attrs, children) {
if (!attrs) attrs = {};
if (!children) children = [];
var el = document.createElement(name);
extend(el, attrs);
children.forEach(function(child) {
if (typeof child == 'string')
el.appendChild(document.createTextNode(child));
else if (typeof child == 'object')
el.appendChild(child);
else
throw new Error("createElement: invalid child: '" + child + "'.");
});
return el;
// Performs a shallow copy of properties in `source` to `target`.
function extend(target, source) {
for (var k in source) {
target[k] = source[k];
}
}
}
}