Chapter 5: Semantic Actions

We're now back to the interesting part: working on your game code. We're going to add annotations in grammar file, to declare the custom actions we want to execute on decoding.

Adding Semantic Actions

ant addSemanticActions
adds empty annotations to your grammar file. THIS is resulting file.

Saving, Loading and Removing Semantic Actions

Use

ant saveSchema
ant loadSchema
to save and load your schema (copying the schema file) and
ant removeSemanticActions
to clean the schema from all semantic actions.

Global Declarations

Just under xsd:schema element are global declarations. B4J produces one decoding class with static fields only. This is the place you declare custom fields to add, and the main decoding method params and return type, and custom code to execute within.

The first element, quizz, has been configured as root element (config:root).
Let's add three static attributes to store Brian scores in each category, and one to store the team score.

We then add a main method to launch data decoding (In this tutorial, we use the generated Decoder class as our only game class).
The first param of decodeDocument is not declared, but a DataInputStream is expected, corresponding to binary data to decode.
We have to import java.io.FileInputStream and java.io.FileNotFoundException, but DataInputStream is already available.
Cheat: THIS is current grammar file.

As we don't build objects from decoded data, we have to comment out all a4j:onEachChildEnd annotations. HERE is resulting grammar file.
We can now generate the first version of our game.

Generating Decoder

ant generateDecoder
generates decoder class including your custom code, and copies it to your target project destination. In this tutorial, you should find this class in b4j\output\decoder as well as in GuessMeRight\src\com\example.

Testing the Game

Change dir to GuessMeRight and compile the game using

javac src\com\example\*.java -encoding ISO-8859-1 -d .
Rename game data file to gameData.b4j and copy it to GuessMeRight. Launch the game with
java com.example.B4JDecoder
We still have to write game actions on each element decoding.

Semantic Actions for Each Element

Semantic actions are defined in a very similar way for each element. Different tags correspond to the successive decoding steps.
You are now free to define your game actions.

The End

Cheat: HERE is the final grammar file, corresponding to working game.
Game data file was modified to add missing information.
Next lesson: Using the Power Pack for Id and Ref management...
back to Chapter 1 or Chapter 2 or Chapter 3 or Chapter 4.