forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanimateworld.js
54 lines (47 loc) · 1.82 KB
/
animateworld.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
// test: no
(function() {
"use strict";
var active = null;
function Animated(world) {
this.world = world;
var outer = __sandbox.output.div, doc = outer.ownerDocument;
var node = outer.appendChild(doc.createElement("div"));
node.style.cssText = "position: relative; width: intrinsic; width: fit-content;";
this.pre = node.appendChild(doc.createElement("pre"));
this.pre.appendChild(doc.createTextNode(world.toString()));
this.button = node.appendChild(doc.createElement("div"));
this.button.style.cssText = "position: absolute; bottom: 8px; right: -4.5em; color: white; font-family: tahoma, arial; " +
"background: #4ab; cursor: pointer; border-radius: 18px; font-size: 70%; width: 3.5em; text-align: center;";
this.button.innerHTML = "stop";
var self = this;
this.button.addEventListener("click", function() { self.clicked(); });
this.disabled = false;
if (active) active.disable();
active = this;
this.interval = setInterval(function() { self.tick(); }, 333);
}
Animated.prototype.clicked = function() {
if (this.disabled) return;
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
this.button.innerHTML = "start";
} else {
var self = this;
this.interval = setInterval(function() { self.tick(); }, 333);
this.button.innerHTML = "stop";
}
};
Animated.prototype.tick = function() {
this.world.turn();
this.pre.removeChild(this.pre.firstChild);
this.pre.appendChild(this.pre.ownerDocument.createTextNode(this.world.toString()));
};
Animated.prototype.disable = function() {
this.disabled = true;
clearInterval(this.interval);
this.button.innerHTML = "Disabled";
this.button.style.color = "red";
};
window.animateWorld = function(world) { new Animated(world); };
})();