Chapter 12
[ 321 ]
} else {
page = "roundX"
}
}
def play_round = { Object event ->
def player = getPlayer(event.player)
player.playRound(grid)
if (Grid.isSolved(grid)) {
page = new GameOverPage(session)
} else {
if (event.player == 'X') {
page = new RoundOPage(session)
} else {
page = new RoundXPage(session)
}
}
}
You will notice that, for the most part, the statement block from the DSL is replicated
as the statement block in the closure. The one exception is where we assign the page
property. This is transformed to a constructor call statement for the corresponding
page class. We will see later how to use GroovyCodeVisitor to achieve this.
All these classes together with the Grid class and some player classes make
a rudimentary game engine that implements an automated TicTacToe game
engine. Let's look at this engine in action with a very dumb player class. The
NextFreeSpacePlayer class just looks for the next available space in the grid and
selects it. Two of these players against each other will always guarantee a win for X
in the fourth round:
class NextFreeSpacePlayer extends Bot {
def playRound(grid) {
if (!Grid.isSolved(grid)) {
Grid.playNextFreeCell grid, this.player
}
}
}