Turtle DSL, another little language
The latest revision of the Ludo game uses yet another DSL.
As you might recall, the Ludo game uses a fluent interface to create squares. This time, we are going to layout the squares on a grid for printing (or drawing).
The basic idea is to use a turtle that walks around the grid. The turtle can advance and change direction. With each step the turtle puts the next square on its current cell (unless told to not do so). Class SquareGrid provides a turtle that can be scripted to put squares on the grid. The turtle knows the sequence of linked squares and can do three things:
- It can turn 90 degrees.
- It can put the next square on the current cell, and advance one cell.
- It can advance one cell without putting a square.
Actually, the turtle can do two more things:
- It can memorize the begin of a branch.
- It can go back to that position.
This is all we need to layout squares on the grid. The following code creates a grid of 15 on 15 cells, and executes four times the same sequence of turtle movements. Once for each quarter of the game board.
public static SquareGrid makeGrid(Iteratorstart) { SquareGrid grid = new SquareGrid(15,15); makeQuarter(grid.getTurtle(5, 1, DOWN, start.next())); makeQuarter(grid.getTurtle(1, 9, LEFT, start.next())); makeQuarter(grid.getTurtle(9, 13, UP, start.next())); makeQuarter(grid.getTurtle(13, 5, RIGHT, start.next())); return grid; }
private static void makeQuarter(Turtle turtle) {
turtle
.move(1)
.turnLeft()
.move(5)
.turnLeft()
.skip()
.move(5)
.turnRight()
.move(1)
.branchHere()
.move(2)
.gotoBranch()
.turnRight()
.skip()
.move(5)
.skip()
.move(1);
}
This little DSL is obviously inspired by the LOGO programming language. For the full implementation, please refer to SquareGrid’s source code.
TLDR, fun with turtles.
