function playgame
%  PLAYGAME  Plays one game of Seven, updating the neural network weights.
%  PLAYGAME, takes no parameters and returns nothing.
%  THIS FUNCTION UPDATES GLOBAL VARIABLES.


global PLAYER HISTORY;


%
%  Shuffle the deck and determine the first player.
%
deck = randperm(51);
index = find(deck == 7);
deck(index) = 52;
turn = floor(3 * (index - 1) / 51) + 1;

%
%  Deal the cards.
%
PLAYER{1} = deck(1:17);
PLAYER{2} = deck(18:34);
PLAYER{3} = deck(35:51);

%
%  Start the table.
%
table(1, :) = [7 7];
table(2, :) = [8 6];
table(3, :) = [8 6];
table(4, :) = [8 6];

%
%  Encode the initial states of the three players.
%
HISTORY{1} = [encode(PLAYER{1}, table)];
HISTORY{2} = [encode(PLAYER{2}, table)];
HISTORY{3} = [encode(PLAYER{3}, table)];


%
%  Loop until the game is over; i.e. a player has no cards left or can
%  "go out" by playing all of his/her runs.
%
winner = iswinner(turn, table);
while (winner == 0)
    %
    %  Debug code.
    %
%    str1 = sprintf('%2d ', PLAYER{1});
%    str2 = sprintf('%2d ', PLAYER{2});
%    str3 = sprintf('%2d ', PLAYER{3});
%    disp(str1);
%    disp(str2);
%    disp(str3);
%    disp('---------------------------');
%    table


    %
    %  For each player in turn, let them make their move.
    %
    table = playcard(turn, table);

    %
    %  Move to the next player.
    %
    turn = mod(turn, 3) + 1;
    winner = iswinner(turn, table);
end


%
%  Final training pass is based on whether the player won or lost.
%
for i = 1:3
    if (i == winner)
        train(i, 1);
    else
        train(i, 0);
    end
end

%str = sprintf('Player%d wins.', winner);
%disp(str);
