function rank = playgame_rand
%  PLAYGAME_RAND  Plays one game of Seven with two random players and the AI.
%  PLAYGAME_RAND, takes no parameters and returns the ranking of the AI.
%  Without loss of generality, the AI is assumed to be player with turn = 1.
%  THIS FUNCTION UPDATES GLOBAL VARIABLES.


global PLAYER;


%
%  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];


%
%  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)
    %
    %  For each player in turn, let them make their move.
    %
    table = playcard_rand(turn, table);

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


%
%  If the AI (player1) won, award the network a 1 (win), otherwise
%  return a 0 (lose).
%
if (winner == 1)
    rank = 1;
else
    rank = 0;
end
