Toss Game
This sample demonstrates a very simple use of the framework.
In a toss game the player chooses between head and tail, then tosses a coin and either wins or looses depending on whether the coin side matches his choice or not.
Modeling and implementing this very simple turn-based game highlights the Model-View-Controller design of games using the framework and the straight-forward process from the game rules to the architecture and code.
Model
Data
This game does not need neither a context (therefore no update either) nor any user.
Order
The sole order is the player choice :
- player choice : head or tail
Result
The result is either a win or a loss :
- player wins
- player looses
Units
This game does not require any security, synchronization or visibility units.
Serialization
Two handlers provide the input/output operations :
- an input handler querying for the player choice on standard input
- an output handler writing the result to standard output
Computation
The only computation handler receives the player order, computes then sends the result :
- a toss computation handler
Diagrams
Class diagrams
First for the Model (as in Model-View-Controller) which handles the core of the game, a strategy is required in order to properly handle the player order :
fig. 1 Toss-game Model classes diagram
Then the View-Controller deals with the input/output :
fig. 2 Toss-game View and Controller classes diagram
Sequence diagrams
In the sequence diagram the control loop is inside TossInput, which read() method returns when the player ends the game :
fig. 3 Toss-game sequence diagram
The creation diagram is straight-forward, classes are instanciated in the reverse order of the flow of control :
fig. 4 Toss-game creation diagram
Implementation
As described above an implementation is required only for the following objects :
- Choice : specialize a Command to encapsulate player choice
- Input : read player choice from the standard input and create a Choice object accordingly
- CoinToss : override the Consumer#handle() method, generate a random coin toss and compare it to the received player choice, finally create a Win or Loss result accordingly
- Output : override the Strategy#apply() method in order to display the result
The modularity of the design appears clearly and drives the implementation process safely.
The complete source code for this sample can be found in the jtge.sample.toss package.