Integrating It All
[ 320 ]
Looking back at the DSL code, you will note that the state: block where the
state variables are declared gets generated in the TicTacToeEngineSession class,
whereas the event handling code gets generated as part of the page class. We want
the event handling code to act like the state variables are in its local scope, which we
can achieve by using the delegate mechanism. We resolve this delegate relationship
in the setClosureDelegates method, which is called when the page is constructed.
Each page class extends PlayerService. There is a presumption in this game engine
that game rounds are played by automated player classes. The PlayerService class
provided some helper functions for accessing the available player bots. This is a test
version of the class designed to work with the Groovy pattern:
class PlayerService {
def getPlayers() {
[
[ playerClass: "NextFreeSpacePlayer"],
[ playerClass: "RandomPlayer"]
]
}
def getPlayer = { player ->
def instance
if (player == 'X')
instance = Class.forName("${playerX}").newInstance()
else
instance = Class.forName("${playerO}").newInstance()
instance.player = player
instance
}
}
Let's look in more detail at an event handler method. Here is an event handler block
from the DSL along with the event closure we expect to generate to implement it:
event: "play_round"
def player = getPlayer(event.player)
player.playRound(grid)
if (Grid.isSolved(grid)) {
page = "gameover"
} else {
if (event.player == 'X') {
page = "roundO"
http://www.ebook3000.com