Filters

# Add a Way to Make a Move

Make sure you have all you need before proceeding:

In this section, you will:

  • Extend message handling - play the game.
  • Handle moves and update the game state.
  • Validate input.
  • Extend unit tests.

Your blockchain can now create games, but can you play them? Not yet...so what do you need to make this possible?

# Some initial thoughts

Before diving into the exercise, take some time to think about the following questions:

  • What goes into the message?
  • How do you sanitize the inputs?
  • How do you unequivocally identify games?
  • How do you report back errors?
  • How do you use your files that implement the checkers rules?
  • How do you make sure that nothing is lost?

# Code needs

When it comes to the code you need, ask yourself:

  • What Ignite CLI commands will create your message?
  • How do you adjust what Ignite CLI created for you?
  • How would you unit-test these new elements?
  • How would you use Ignite CLI to locally run a one-node blockchain and interact with it via the CLI to see what you get?

As before, do not bother yet with niceties like gas metering or event emission.

To play a game a player only needs to specify:

  • The ID of the game the player wants to join. Call the field gameIndex.
  • The initial positions of the pawn. Call the fields fromX and fromY and make them uint.
  • The final position of the pawn after a player's move. Call the fields toX and toY to be uint too.

The player does not need to be explicitly added as a field in the message because the player is implicitly the signer of the message. Name the object PlayMove.

Unlike when creating the game, you want to return:

  • The captured piece, if any. Call the fields capturedX and capturedY. Make then int so that you can pass -1 when no pieces have been captured.
  • The (potential) winner in the field winner.

# With Ignite CLI

Ignite CLI can create the message and the response objects with a single command:

Ignite CLI once more creates all the necessary Protobuf files and boilerplate for you. See tx.proto:

Copy message MsgPlayMove { string creator = 1; string gameIndex = 2; uint64 fromX = 3; uint64 fromY = 4; uint64 toX = 5; uint64 toY = 6; } message MsgPlayMoveResponse { int32 capturedX = 1; int32 capturedY = 2; string winner = 3; } proto checkers tx.proto View source

All you have to do is fill in the needed part in x/checkers/keeper/msg_server_play_move.go:

Copy func (k msgServer) PlayMove(goCtx context.Context, msg *types.MsgPlayMove) (*types.MsgPlayMoveResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) // TODO: Handling the message _ = ctx return &types.MsgPlayMoveResponse{}, nil } x checkers keeper msg_server_play_move.go View source

Where the TODO is replaced as per the following.

# The move handling

The rules represent the ready-made file containing the rules of the game you imported earlier. Declare your new errors in x/checkers/types/errors.go, given your code has to handle new error situations:

Copy var ( ... + ErrGameNotFound = sdkerrors.Register(ModuleName, 1103, "game by id not found") + ErrCreatorNotPlayer = sdkerrors.Register(ModuleName, 1104, "message creator is not a player") + ErrNotPlayerTurn = sdkerrors.Register(ModuleName, 1105, "player tried to play out of turn") + ErrWrongMove = sdkerrors.Register(ModuleName, 1106, "wrong move") ) x checkers types errors.go View source

Take the following steps to replace the TODO:

  1. Fetch the stored game information using the Keeper.GetStoredGame (opens new window) function created by Ignite CLI:

    Copy storedGame, found := k.Keeper.GetStoredGame(ctx, msg.GameIndex) if !found { return nil, sdkerrors.Wrapf(types.ErrGameNotFound, "%s", msg.GameIndex) } x checkers keeper msg_server_play_move.go View source

    You return an error because this is a player mistake.

  2. Is the player legitimate? Check with:

    Copy isBlack := storedGame.Black == msg.Creator isRed := storedGame.Red == msg.Creator var player rules.Player if !isBlack && !isRed { return nil, sdkerrors.Wrapf(types.ErrCreatorNotPlayer, "%s", msg.Creator) } else if isBlack && isRed { player = rules.StringPieces[storedGame.Turn].Player } else if isBlack { player = rules.BLACK_PLAYER } else { player = rules.RED_PLAYER } x checkers keeper msg_server_play_move.go View source

    This uses the certainty that the MsgPlayMove.Creator has been verified by its signature (opens new window).

  3. Instantiate the board in order to implement the rules:

    Copy game, err := storedGame.ParseGame() if err != nil { panic(err.Error()) } x checkers keeper msg_server_play_move.go View source

    Fortunately you previously created this helper (opens new window). Here you panic because if the game cannot be parsed the cause may be database corruption.

  4. Is it the player's turn? Check using the rules file's own TurnIs (opens new window) function:

    Copy if !game.TurnIs(player) { return nil, sdkerrors.Wrapf(types.ErrNotPlayerTurn, "%s", player) } x checkers keeper msg_server_play_move.go View source
  5. Properly conduct the move, using the rules' Move (opens new window) function:

    Copy captured, moveErr := game.Move( rules.Pos{ X: int(msg.FromX), Y: int(msg.FromY), }, rules.Pos{ X: int(msg.ToX), Y: int(msg.ToY), }, ) if moveErr != nil { return nil, sdkerrors.Wrapf(types.ErrWrongMove, moveErr.Error()) } x checkers keeper msg_server_play_move.go View source
  6. Prepare the updated board to be stored and store the information:

    Copy storedGame.Board = game.String() storedGame.Turn = rules.PieceStrings[game.Turn] k.Keeper.SetStoredGame(ctx, storedGame) x checkers keeper msg_server_play_move.go View source

    This updates the fields that were modified using the Keeper.SetStoredGame (opens new window) function, as when you created and saved the game.

  7. Return relevant information regarding the move's result:

    Copy return &types.MsgPlayMoveResponse{ CapturedX: int32(captured.X), CapturedY: int32(captured.Y), Winner: rules.PieceStrings[game.Winner()], }, nil x checkers keeper msg_server_play_move.go View source

    The Captured and Winner information would be lost if you did not get it out of the function one way or another. More accurately, one would have to replay the transaction to discover the values. It is best to make this information easily accessible.

This completes the move process, facilitated by good preparation and the use of Ignite CLI.

# Unit tests

Adding unit tests for this play message is very similar to what you did for the previous message: create a new msg_server_play_move_test.go file and declare it as package keeper_test. Start with a function that conveniently sets up the keeper for the tests. In this case, already having a game saved can reduce several lines of code in each test:

Copy func setupMsgServerWithOneGameForPlayMove(t testing.TB) (types.MsgServer, keeper.Keeper, context.Context) { k, ctx := keepertest.CheckersKeeper(t) checkers.InitGenesis(ctx, *k, *types.DefaultGenesis()) server := keeper.NewMsgServerImpl(*k) context := sdk.WrapSDKContext(ctx) server.CreateGame(context, &types.MsgCreateGame{ Creator: alice, Black: bob, Red: carol, }) return server, *k, context } x checkers keeper msg_server_play_move_test.go View source

Note that it reuses alice, bob and carol found in the file msg_server_create_game_test.go (opens new window) of the same package.

Now test the result of a move. Blacks play first, which according to setupMsgServerWithOneGameForPlayMove corresponds to bob:

Copy func TestPlayMove(t *testing.T) { msgServer, _, context := setupMsgServerWithOneGameForPlayMove(t) playMoveResponse, err := msgServer.PlayMove(context, &types.MsgPlayMove{ Creator: bob, GameIndex: "1", FromX: 1, FromY: 2, ToX: 2, ToY: 3, }) require.Nil(t, err) require.EqualValues(t, types.MsgPlayMoveResponse{ CapturedX: -1, CapturedY: -1, Winner: "*", }, *playMoveResponse) } x checkers keeper msg_server_play_move_test.go View source

Also test whether the game was saved correctly (opens new window). Check what happens when the game cannot be found (opens new window), the sender is not a player (opens new window), a player tries to play out of turn (opens new window), or makes a wrong move (opens new window). Check after two (opens new window) or three turns with a capture (opens new window).

As a special case, add a test to check what happens when a board is not parseable, which is expected to end up in a panic, not with a returned error:

Copy func TestPlayMoveCannotParseGame(t *testing.T) { msgServer, k, context := setupMsgServerWithOneGameForPlayMove(t) ctx := sdk.UnwrapSDKContext(context) storedGame, _ := k.GetStoredGame(ctx, "1") storedGame.Board = "not a board" k.SetStoredGame(ctx, storedGame) defer func() { r := recover() require.NotNil(t, r, "The code did not panic") require.Equal(t, r, "game cannot be parsed: invalid board string: not a board") }() msgServer.PlayMove(context, &types.MsgPlayMove{ Creator: bob, GameIndex: "1", FromX: 1, FromY: 2, ToX: 2, ToY: 3, }) } x checkers keeper msg_server_play_move_test.go View source

Note the use of defer (opens new window), which can be used as a Go way of implementing try catch of panics. The defer statement is set up right before the msgServer.PlayMove statement that is expected to fail, so that it does not catch panics that may happen earlier.

Try these tests:

# Interact via the CLI

Start your chain again:

If you restarted from the previous section, there is already one game in storage and it is waiting for Alice's move. If that is not the case, recreate a game via the CLI.

Can Bob make a move? Look at the play-move message and which parameters it expects:

This returns:

Copy Broadcast message playMove Usage: checkersd tx checkers play-move [game-index] [from-x] [from-y] [to-x] [to-y] [flags] ...

So Bob tries:

After you accept sending the transaction, it should complain with the result including:

Copy ... raw_log: 'failed to execute message; message index: 0: {red}: player tried to play out of turn' ... txhash: D10BB8A706870F65F19E4DF48FB870E4B7D55AF4232AE0F6897C23466FF7871B

If you did not get this raw_log, your transaction may have been sent asynchronously. You can always query a transaction by using the txhash with the following command:

And you are back on track:

Copy ... raw_log: 'failed to execute message; message index: 0: {red}: player tried to play out of turn'

Can Alice, who plays black, make a move? Can she make a wrong move? For instance, a move from 0-1 to 1-0, which is occupied by one of her pieces.

The computer says "no":

Copy ... raw_log: 'failed to execute message; message index: 0: Already piece at destination position: {0 1}: wrong move'

So far all seems to be working.

Time for Alice to make a correct move:

This returns:

Copy ... raw_log: '[{"events":[{"type":"message","attributes":[{"key":"action","value":"play_move"}]}]}]'

Confirm the move went through with your one-line formatter from the previous section:

This shows:

Copy *b*b*b*b b*b*b*b* ***b*b*b **b***** <--- Here ******** r*r*r*r* *r*r*r*r r*r*r*r*

Bob's piece moved down and right.

When you are done with this exercise you can stop Ignite's chain serve.

synopsis

To summarize, this section has explored:

  • How to use messages and handlers, in this case to add the capability of actually playing moves on checkers games created in your application.
  • The information that needs to be specified for a game move message to function, which are the game ID, the initial positions of the pawn to be moved, and the final positions of the pawn at the end of the move.
  • The information necessary to return, which includes the game ID, the location of any captured piece, and the registration of a winner should the game be won as a result of the move.
  • How to modify the response object created by Ignite CLI to add additional fields.
  • How to implement and check the steps required by move handling, including the declaration of the ready-made rules in the errors.go file so your code can handle new error situations.
  • How to add unit tests to check the functionality of your code.
  • How to interact via the CLI to confirm that correct player turn order is enforced by the application.