<textarea id="inputtext" rows=15 cols=35 wrap="off" style="width:600px;">
var level = 8;
var axiom = 'Fl';
var rules = {
'F' : 'F',
'l' : 'l+rF+',
'r' : '-Fl-r',
'+' : '+',
'-' : '-'
};
var symbols = { 'F':'F',
'l':' ',
'r':' ',
'+':'+',
'-':'-',
'[':'[',
']':']'
} ;
var angle = 90;
var len = 1000/(level*level);
</textarea><br />
<input type="button" value="run" onClick="run()">
<input type="button" value="clear" onClick="clearturtle()">
<div id="board-0-wrapper" class="jxgbox-wrapper " style="width: 100%; ">
<div id="board-0" class="jxgbox" style="aspect-ratio: 1 / 1; width: 100%;" data-ar="1 / 1"></div>
</div>
<script type = "text/javascript">
/*
This example is licensed under a
Creative Commons Attribution 4.0 International License.
https://creativecommons.org/licenses/by/4.0/
Please note that you have to mention
The Center of Mobile Learning with Digital Technology
in the credits.
*/
const BOARDID = 'board-0';
var t;
const board = JXG.JSXGraph.initBoard(BOARDID, {
boundingbox: [-300, 300, 300, -300]
});
const turtle = board.create('turtle');
var expander = function(level, axiom, rules) {
this.axiom = axiom;
this.rules = rules;
this.source = (level > 1) ? new expander(level - 1, axiom, rules) : (new function() {
// Axiom:
this.code = axiom;
this.pos = 0;
this.next = function() {
if (this.pos >= this.code.length) return null;
return this.code.charAt(this.pos++);
}
});
this.code = '';
this.pos = 0;
this.next = function() {
while (this.pos >= this.code.length) { // produce new symbols from source
this.pos = 0;
var pattern = this.source.next();
if (!pattern) return null // Finished
this.code = this.rules[pattern];
}
return this.code.charAt(this.pos++);
}
}
var plotter = function(generator, symbols, len, angle, t, shrink) {
var c;
for (c; c = generator.next(); c) {
switch (symbols[c]) {
case 'F':
t.fd(len);
break;
case 'f':
t.penUp();
t.fd(len);
t.penDown();
break;
case '+':
t.lt(angle);
break;
case '-':
t.rt(angle);
break;
case '[':
t.pushTurtle();
len *= shrink;
break;
case ']':
t.popTurtle();
len /= shrink;
break;
default:
;
}
}
return null;
}
var shrink = 1.0;
var run = function() {
var code = document.getElementById('inputtext').value;
if (code === '') {
return;
}
t = turtle;
t.cs();
t.hideTurtle();
eval(code); // eval is considered insecure and should be used only in safe environments
var generator = new expander(level, axiom, rules);
plotter(generator, symbols, len, angle, t, shrink);
}
var clearturtle = function() {
turtle.cs();
}
</script>