2012-09-09

And now?

When last we spoke, I was busy realigning my piece code with cold, hard reality. May I say again how much I love the agility of writing Erlang; I can change my mind as often as I want with little effort.

Or maybe it’s because I have so little code. Or maybe I have so little code because it’s Erlang. Or…

Anyway.

As I noted as I raced out the door yesterday (the pork buns were quite good) I hadn’t actually tested any of the code changes I made. So let’s do some quick shell work, if for no other reason than it’d be good to help me remember where things landed.

To spare anyone a trip to GitHub, here are the important bits of the current piece module (I expect all move functions and related calculations to be migrated to another module, and they’re not important for the current discussion anyway):

blank_square() ->
    piece_loop(blank_square, none, [],
               fun(Source, _Dest, _team) -> { Source, [] } end,
               fun(Source, _Dest, _team) -> { Source, [] } end).

piece_loop(Piece, Team, History, Move, Capture) ->
    receive
        { Pid, testmove, Start, End, Xtra } ->
            move_response(Pid, Piece, Start, End, Move(Start, End, Team), Xtra),
            piece_loop(Piece, Team, History, Move, Capture);
        { Pid, testcapture, Start, End, Xtra } ->
            move_response(Pid, Piece, Start, End, Capture(Start, End, Team), Xtra),
            piece_loop(Piece, Team, History, Move, Capture);
        { replace, NewPiece, NewTeam, NewHistory, NewMove, NewCapture } ->
            piece_loop(NewPiece, NewTeam, NewHistory, NewMove, NewCapture);
        { moveto, Start, End, CapturedPiece, NewSquarePid } ->
            NewSquarePid ! { replace, Piece, Team,
                             [ { Start, End, CapturedPiece } | History ], Move, Capture },
            blank_square();
        { Pid, what_am_i, Xtra } ->
            Pid ! { Piece, Team, History, Xtra };
        done ->
            done;
        Message ->
            throw({unknown_message, Message})
    end.

Verification

First things first, let’s run our test suite. All of my changes were applied to code outside the auxiliary movement-related functions, however, so this is basically a non-event:

7> piece:test().
  All 25 tests passed.
ok

Ooh, ahh.

Anyway.

What I really need to test is messaging. Functional tests, of which I have none.

8> [ B ] = [ X || {bishopmove, X} <- piece:movefuns() ].
[#Fun<piece.6.42012460>]
9> Bishop = spawn(piece, piece_loop, [ bishop, white, [], B, B ]).
<0.102.0>
10> Bishop ! { self(), what_am_i, nada }.
{<0.31.0>,what_am_i,nada}
11> flush().
Shell got {bishop,white,[],nada}
ok

Remembering to pass the extra argument1 is going to be tedious, I can tell.

12> Empty = spawn(piece, blank_square, []).
<0.106.0>
13> Empty ! { self(), what_am_i, zilch }.
{<0.31.0>,what_am_i,zilch}
14> flush().
Shell got {blank_square,none,[],zilch}
ok
15> Bishop ! { self(), testmove, { 3, 1 }, { 6, 4 }, nada }.
{<0.31.0>,testmove,{3,1},{6,4},nada}
16> flush().
ok
17> flush().
ok

Ok, first bug, and one I’ve made before: I forgot to include the recursive call to piece_loop/5 after answering the what_am_i message. Wonder if there’s a lint-like tool for Erlang that would help detect this gaffe.

19> f(Bishop).
ok
20> Bishop = spawn(piece, piece_loop, [ bishop, white, [], B, B ]).
<0.123.0>
21> Bishop ! { self(), what_am_i, nada }.
{<0.31.0>,what_am_i,nada}
22> flush().
Shell got {bishop,white,[],nada}
ok
23> Bishop ! { self(), testmove, { 3, 1 }, { 6, 4 }, [] }.
{<0.31.0>,testmove,{3,1},{6,4},[]}
24> flush().
Shell got {yes,bishop,{3,1},{6,4},[{4,2},{5,3}],[]}
ok

Now comes the new messaging: let’s move that bishop to the empty square. Rather, let’s move the state from the square represented by the Bishop process to the square represented by the Empty process.

5> Bishop ! { moveto, {3, 1}, {6, 4}, none, Empty }.
{moveto,{3,1},{6,4},none,<0.159.0>}
6> Empty ! { self(), what_am_i, nada }.
{<0.145.0>,what_am_i,nada}
7> flush().
Shell got {bishop,white,[{{3,1},{6,4},none}],nada}
ok
8> Bishop ! { self(), what_am_i, nada }.
{<0.145.0>,what_am_i,nada}
9> flush().
Shell got {blank_square,none,[],nada}
ok

Easy enough so far. Empty now has the bishop.

10> Empty ! { moveto, {6, 4}, {5, 5}, none, Empty }.
{moveto,{6,4},{5,5},none,<0.159.0>}
11> Empty ! { self(), what_am_i, nada }.
{<0.145.0>,what_am_i,nada}
12> flush().
Shell got {bishop,white,[{{6,4},{5,5},none},{{3,1},{6,4},none}],nada}
ok

Awesome. As predicted (quietly, to myself, as not to scare the dog) after I reviewed the code, I can move the piece state to the same process. As a reminder, here’s the relevant code:

{ moveto, Start, End, CapturedPiece, NewSquarePid } ->
    NewSquarePid ! { replace, Piece, Team,
                     [ { Start, End, CapturedPiece } | History ], Move, Capture },
    blank_square();

When I asked Empty to move its state to itself, it sent the message, looped through the blank_square function that replaced its current state with empty_square and other no-op functionality, then read its mailbox. Next in its mailbox is the replace message that it unknowingly sent itself, and so it happily rebuilds its state with the same information.

The piece history is accumulating: [{{6,4},{5,5},none},{{3,1},{6,4},none}] means that the piece last moved from {6,4} to {5,5} (while capturing nothing), after having previously moved from {3,1} to {6,4}.

Special moves

Note that the moveto message does not attempt to verify the legality of the move. This means that we could move a bishop like a rook, but it also means that we can keep hairier moves like en passant and castling out of the picture for this code.

However, as with the current move functions, those special moves would not need to check for blocking pieces or other conceptual obstacles.

In fact, en passant is already handled fine by the current pawncapture move function, because the move is identical to a normal capture; the only oddity is that there’s no piece in the targeted square. The only special move which lives entirely outside the current move functions is the king’s castle.

The trick is that currently there’s no way to incorporate castling into the move function paradigm. I can’t tell kingmove that this is a castle operation, and thus a two square move along the current rank is perfectly legitimate.

We do, however, already pass along additional metadata for all pawn moves, since pawn moves are unique: they are only allowed in one direction, and that direction is dependent on the team color. So we pass the team color along to each move function just in case that move function happens to be for a pawn.

So what’s to stop us from using what is, for every other piece on the board, a superfluous argument to the function?

There’s certainly some complexity here. The primary obstacle is that the team color is curried via the piece state, not passed in from the board, and so the testmove and moveto messages would have to be modified in some reasonable way to allow the board to express that “this is a castle operation.”

In and of itself that’s a trivial change, but I want to make sure it’s a clean, general solution.

I’d like some fresh, clear, well-seasoned perspective2

While I hate the redundancy of passing in the team color from the board for each move, I hate it much less than any other solution I can think of. So, each move-related message will now have a Context argument.

{ Pid, testmove, Start, End, Context, Xtra }
{ Pid, testcapture, Start, End, Context, Xtra }
{ moveto, Start, End, Context, CapturedPiece, NewSquarePid }

It’s tempting to turn the triad of Start, End, and Context into a tuple, and I may do so yet.

As I work on this new code, though, I think moveto is going to undergo more significant changes.

… much time passes, including discovering what a case_clause error means … 3

Before showing you the new code, let me illustrate the end results.

9> Bishop = spawn(piece, piece_loop, [ bishop, white, [], B, B ]).
<0.216.0>
10> Empty = spawn(piece, blank_square, []).
<0.218.0>
11> Bishop ! { moveto, {3, 1}, {6, 4}, none, Empty }.
{moveto,{3,1},{6,4},none,<0.218.0>}
12> flush().
ok
13> Empty ! { self(), what_am_i, none }.
{<0.188.0>,what_am_i,none}
14> flush().
Shell got {bishop,white,[{{3,1},{6,4},none}],none}
ok
15> Bishop2 = spawn(piece, piece_loop, [ bishop, white, [], B, B ]).
<0.224.0>
16> Bishop2 ! { moveto, {3, 1}, {6, 4}, none, Empty }.
{moveto,{3,1},{6,4},none,<0.218.0>}

=ERROR REPORT==== 9-Sep-2012::22:58:11 ===
Error in process <0.224.0> with exit value: {{nocatch,{capturing_same_team,bishop,bishop,{3,1},{6,4}}},[{piece,piece_loop,5,[{file,"/Users/jdaily/github/local/Erlang-Chessboard/piece.erl"},{line,43}]}]}

The second bishop, also white, is instructed to move to a square that already has a white piece, resulting in a thrown (and uncaught) exception.

Here is the new code for the moveto message. I regret that it’s significantly longer than the old, dumb code, but I’ve introduced comments to (hopefully) make it comprehensible.

{ moveto, Start, End, Context, NewSquarePid } ->
    %% Ask the target square for more information
    NewSquarePid ! { self(), what_am_i, none },
    receive
        %% If we're moving to a blank square, verify Move() before
        %% transferring
        { blank_square, _Team, _History, none } ->
            case Move(Start, End, Context) of
                { Start, _ } ->
                    throw({cannot_moveto, Piece, Start, End});
                { End, _ } ->
                    NewSquarePid ! { replace, Piece, Team,
                                     [ { Start, End, none } | History ], Move, Capture }
            end;

        %% If we're trying to capture the same team color, throw an exception
        { CapturedPiece, Team, _, _ } ->
            throw({capturing_same_team, Piece, CapturedPiece, Start, End});

        %% Successful capture
        { CapturedPiece, _Team, _, _ } ->
            case Capture(Start, End, Context) of
                { Start, _ } ->
                    throw({cannot_moveto, Piece, Start, End});
                { End, _ } ->
                    NewSquarePid ! { replace, Piece, Team,
                                     [ { Start, End, CapturedPiece } | History ], Move, Capture }
            end
    end,
    %% Now we've lost our piece, so reinitialize as a blank square
    blank_square();

Here’s an example of trying to force a bishop to move to a square which isn’t legal:

34> Bishop ! { moveto, {3, 1}, {6, 5}, none, Empty }.
{moveto,{3,1},{6,5},none,<0.244.0>}

=ERROR REPORT==== 9-Sep-2012::23:08:46 ===
Error in process <0.242.0> with exit value: {{nocatch,{cannot_moveto,bishop,{3,1},{6,5}}},[{piece,piece_loop,5,[{file,"/Users/jdaily/github/local/Erlang-Chessboard/piece.erl"},{line,36}]}]}

One concern about all of this message passing is that if any receiving process is not functioning properly, and thus is not able to reply, other processes will also end up in a waiting state. I assume this is a typical Erlang behavior pattern, and thus there’s a standard way to make sure those waiting states turn into exceptions.

Hardcastle4

By now I’ve almost forgotten where this all started, but now we can introduce castling, finally.

Again, the end result:

2> [ K ] = [ X || {kingmove, X} <- piece:movefuns() ].
[#Fun<piece.4.9735311>]
3> King = spawn(piece, piece_loop, [ king, white, [], K, K ]).
<0.277.0>
4> King ! { self(), testmove, {5, 1}, {7, 1}, white, none }.
{<0.265.0>,testmove,{5,1},{7,1},white,none}
5> flush().
Shell got {no,king,{5,1},{7,1},[],none}
ok

6> King ! { self(), testmove, {5, 1}, {7, 1}, castle, none }.
{<0.265.0>,testmove,{5,1},{7,1},castle,none}
7> flush().
Shell got {yes,king,{5,1},{7,1},[],none}
ok
8> Empty = spawn(piece, blank_square, []).
<0.283.0>
9> King ! { moveto, {5, 1}, {7, 1}, castle, Empty }.
{moveto,{5,1},{7,1},castle,<0.283.0>}
10> Empty ! { self(), what_am_i, none }.
{<0.265.0>,what_am_i,none}
11> flush().
Shell got {king,white,[{{5,1},{7,1},none}],none}
ok

The new kingmove anonymous function?

17> King ! { self(), testmove, {5, 1}, {7, 1}, white, none }.
{<0.265.0>,testmove,{5,1},{7,1},white,none}
18> flush().
Shell got {no,king,{5,1},{7,1},[],none}
ok

As expected, in the absence of a castle context, a 2-square move won’t work.

19> King ! { self(), testmove, {5, 1}, {7, 1}, {white, castle}, none }.
{<0.265.0>,testmove,{5,1},{7,1},{white,castle},none}
20> flush().
Shell got {yes,king,{5,1},{7,1},[],none}
ok
21> King ! { self(), testmove, {5, 1}, {8, 1}, {white, castle}, none }.
{<0.265.0>,testmove,{5,1},{8,1},{white,castle},none}
22> flush().
Shell got {no,king,{5,1},{8,1},[],none}
ok
23> King ! { self(), testmove, {6, 1}, {8, 1}, {white, castle}, none }.
{<0.265.0>,testmove,{6,1},{8,1},{white,castle},none}
24> flush().
Shell got {no,king,{6,1},{8,1},[],none}
ok
25> King ! { self(), testmove, {5, 8}, {7, 8}, {white, castle}, none }.
{<0.265.0>,testmove,{5,8},{7,8},{white,castle},none}
26> flush().
Shell got {no,king,{5,8},{7,8},[],none}
ok
27> King ! { self(), testmove, {5, 8}, {7, 8}, {black, castle}, none }.
{<0.265.0>,testmove,{5,8},{7,8},{black,castle},none}
28> flush().
Shell got {yes,king,{5,8},{7,8},[],none}
ok

However, if castle is sent along with the team, and the ranks and filed are correct, it works.

Unfortunately it doesn’t validate that the team color matches its own state, but I can live with that.

Here’s the new kingmove anonymous function. Note the hardcoded ranks and files.

fun({ 5, 1 }, { NewX, 1 }, {white, castle})
      when abs(NewX - 5) =:= 2 -> { { NewX, 1 }, [] };
   ({ 5, 8 }, { NewX, 8 }, {black, castle})
      when abs(NewX - 5) =:= 2 -> { { NewX, 8 }, [] };
   ({ OldX, OldY }, { NewX, NewY }, _)
      when abs(NewY - OldY) < 2, abs(NewX - OldX) < 2 -> { { NewX, NewY }, [] };
   (Loc, _, _) -> { Loc, [] } end

The corresponding rook move won’t change anything, because the rook is performing what it considers to be a perfectly legitimate move. It’s up to the board code (or some future delegate) to validate the final legality of any castle operation.


  1. On day 8, I decided that the board needed to be able to forward messages to pieces/squares on behalf of other processes without bottlenecking my code by waiting for a reply, and the only way to do that was to send the process ID of the originating request in the message so that it can be sent back to me.

    I really need a better name for that message argument than Xtra.↩︎

  2. Pixar rules.↩︎

  3. Error in process <0.200.0> with exit value: {{case_clause,{{6,4},[{4,2},{5,3}]}},[{piece,piece_loop,5,[{file,"/Users/jdaily/github/local/Erlang-Chessboard/piece.erl"},{line,34}]}]}

    The above means that the expression in the case statement on line 34 is failing to match any of the patterns provided.↩︎

  4. I can’t believe I remembered this old TV show.↩︎

erlang chessboard
Previous post
Erlang, Twitter, and OAuth Deconstruction, a prologue
Next post
Chessboard: Day 11 Board, board, I must a board to make