Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Integrating It All


[ 314 ]

Events are received by the game server and dispatched to the game engine code,
which is generated from the DSL. The DSL itself is modeled on the state machine
DSL we built in Chapter 8, AST Transformations.


The game DSL includes the ability to define state variables. The current value of
these state variables is passed back to the UI after each event so that the UI can
update its state. Events are sent asynchronously so we need to persist some session
states between events. We do this in a MongoDB database which we access via
Spring Data mappings for MongoDB.


TicTacToe in a DSL


So let's look at some code. In this section we will look at the DSL representation of
a basic TicTacToe game. This DSL works in conjunction with the grid and player
classes we mentioned earlier to form the core game logic for the TicTacToe game.


When I build a relatively complex DSL like this one, which uses AST transforms,
I like to first get a non-DSL version working as a Java or Groovy implementation.
Let's first look at the TicTacToe DSL:


import com.dearle.game.engine.Grid

page: "welcome"
page: "players"
page: "roundX"
page: "roundO"
page: "gameover"

state:
String playerX
String playerO
List players
String winner
def grid = [
' ', ' ', ' ',
' ', ' ', ' ',
' ', ' ', ' '
]

event: "game_start"
players = getPlayers()
page = "players"

http://www.ebook3000.com
Free download pdf