From cbada5bd2c84cc9d590474c0449e0e2e859a4a4f Mon Sep 17 00:00:00 2001 From: Manuel Friedli Date: Wed, 30 Sep 2020 23:31:53 +0200 Subject: [PATCH] Refactor TextRenderer a bit. --- .../ch/fritteli/labyrinth/TextRenderer.java | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/main/java/ch/fritteli/labyrinth/TextRenderer.java b/src/main/java/ch/fritteli/labyrinth/TextRenderer.java index 7b60640..253c1da 100644 --- a/src/main/java/ch/fritteli/labyrinth/TextRenderer.java +++ b/src/main/java/ch/fritteli/labyrinth/TextRenderer.java @@ -11,8 +11,11 @@ public class TextRenderer { private final Labyrinth labyrinth; private final int width; private final int height; + // column counter private int x = 0; + // row counter private int y = 0; + // line counter (top-, center- or bottom line of a row) private int line = 0; private TextRenderer(@NonNull final Labyrinth labyrinth, final int width, final int height) { @@ -23,10 +26,10 @@ public class TextRenderer { public static String render(@NonNull final Labyrinth labyrinth) { final int width = labyrinth.getWidth(); - if (width == 0) { + final int height = labyrinth.getHeight(); + if (width == 0 || height == 0) { return ""; } - final int height = labyrinth.getHeight(); final TextRenderer renderer = new TextRenderer(labyrinth, width, height); final StringBuilder sb = new StringBuilder(); @@ -40,13 +43,6 @@ public class TextRenderer { return this.y < this.height; } - private Tile getTileOrNull(final int x, final int y) { - if (x < 0 || y < 0 || x >= this.width || y >= this.height) { - return null; - } - return this.labyrinth.getTileAt(x, y); - } - private String next() { final Tile currentTile = this.labyrinth.getTileAt(this.x, this.y); final Tile leftTile = this.getTileOrNull(this.x - 1, this.y); @@ -66,21 +62,38 @@ public class TextRenderer { s = ""; break; } + this.prepareNextStep(); + return s; + } + + private void prepareNextStep() { // do some magic ... this.x++; if (this.x == this.width) { + // Reached the end of the row? + // On to the next line then! this.x = 0; this.line++; } if (this.line == 2 && this.y < this.height - 1) { + // Finished rendering the center line, and more rows available? + // On to the next row then! this.line = 0; this.y++; } if (this.line == 3) { + // Finished rendering the bottom line (of the last row)? + // Increment row counter one more time => this is the exit condition. this.line = 0; this.y++; } - return s; + } + + private Tile getTileOrNull(final int x, final int y) { + if (x < 0 || y < 0 || x >= this.width || y >= this.height) { + return null; + } + return this.labyrinth.getTileAt(x, y); } private String renderTopLine(@NonNull final Tile currentTile, @Nullable final Tile leftTile, @Nullable final Tile topTile) {