MATLAB: While function is not working

functionif statementwhile loop

I'm creating a while function for my simple uno game. I have created a function called play to give each player a turn to play a card, and each card played will be deducted from a matrix called Deck, then it will be replaced in a other matrix called Draw_Deck. The idea is if a card was played by either player, it will be placed in the Draw_Deck and deleted from the Deck, because eventually the cards that can be drawed from Deck will run out, then I want the program to start allowing players to draw drom Draw_Deck. my idea is to inclued the function (play) in a while loop:
while Deck(:,1:10) ~= " "
[p1,p2,floor,Draw_Deck,Deck] = play(p1,p2,floor,Draw_Deck,Deck);
end
note that the 11th column in the matrix includes the color card name that's why i didn't write:
while Deck(:,:) ~= " "
[p1,p2,floor,Draw_Deck,Deck] = play(p1,p2,floor,Draw_Deck,Deck);
end
which means i don't want the 11th column to be checked, because it will always have the colors names in it.
the only problem is when i run the code, it skips the line where the function should be runned and directly goes to the line after end!
i also tried with if:
if Deck(:,1:10) ~= " "
[p1,p2,floor,Draw_Deck,Deck] = play(p1,p2,floor,Draw_Deck,Deck);
end
it also does the same thing, skips running the function and goes to the line after end,
if any one can help solving this problem I'll be happy.

Best Answer

I'd just check the height of Deck - the deck that contains the remaining cards. If it has zero rows (it's empty), quit the loop
maxIterations = 53; % ALL while loops must have a failsafe - it's just good programming practice.
loopCounter = 1;
while ~isempty(Deck) && loopCounter < maxIterations
[p1,p2,floor,Draw_Deck,Deck] = play(p1,p2,floor,Draw_Deck,Deck);
% Now Draw_Deck is one row taller, and Deck is one row shorter.
% Eventually, when all rows have been deleted, Deck will be empty
loopCounter = loopCounter + 1;
end
Note how I also used a failsafe. 90% of the while loop questions here (not yours though) are about infinite loops - a loop that never ends. That's because they didn't use a failsafe to prevent infinite loops. I added one to your code just to be safe and follow good programming practices.
Related Question