diff --git a/src/lib/turtle/Printer.hx b/src/lib/turtle/Printer.hx new file mode 100644 index 0000000..67f9289 --- /dev/null +++ b/src/lib/turtle/Printer.hx @@ -0,0 +1,67 @@ +package lib.turtle; + +import lib.turtle.Structure.Layer; +import kernel.turtle.Turtle; + +class Printer { + var structure:Structure; + + public function new(s:Structure) { + structure = s; + } + + private function printRow(layer:Layer, x:Int, inverse:Bool) { + for (y in 0...layer.height()) { + var trueY = inverse ? ((layer.height() - 1) - y) : y; + var place = layer.get(x, trueY); + + if (place) { + Turtle.place(Down); + } + + if (y != layer.height() - 1) { + Turtle.forward(); + } + } + } + + private function printLayer(layer:Layer, inverse:Bool) { + for (x in 0...layer.width()) { + var trueX = inverse ? ((layer.width() - 1) - x) : x; + printRow(layer, trueX, inverse); + + if (x == layer.width() - 1) { + // Don't turn on the last row + continue; + } + + // Turn left or right + if (x % 2 == (inverse ? 1 : 0)) { + Turtle.turnRight(); + Turtle.forward(); + Turtle.turnRight(); + } else { + Turtle.turnLeft(); + Turtle.forward(); + Turtle.turnLeft(); + } + } + } + + public function execute() { + for (i in 0...structure.height()) { + var layer = structure.getLayer(i); + var inverse = i % 2 == 0; + + printLayer(layer, inverse); + + // Don't go up on the last layer + if (i != structure.height() - 1) { + Turtle.up(); + } + + Turtle.turnLeft(); + Turtle.turnLeft(); + } + } +} diff --git a/src/lib/turtle/Structure.hx b/src/lib/turtle/Structure.hx new file mode 100644 index 0000000..c5e9a9e --- /dev/null +++ b/src/lib/turtle/Structure.hx @@ -0,0 +1,25 @@ +package lib.turtle; + +abstract Structure(Array) from Array { + public inline function getLayer(i:Int):Layer { + return this[i]; + } + + public inline function height():Int { + return this.length; + } +} + +abstract Layer(Array>) from Array> { + public inline function get(x:Int, y:Int):Bool { + return this[y][x]; + } + + public inline function width():Int { + return this[0].length; + } + + public inline function height():Int { + return this.length; + } +}