Deck Of Cards

Published 2023-06-12



To load this program in Pico-8, type:

Shuffling a deck of cards on a computer has come a long way, hasn't it ?

The classic method is to go through each card one at a time and shuffle them by taking the index card and swapping it with a random card anywhere in the deck.

The problem with this method is that after a shuffle if the first card is say 2 of Spades, then you already know the next card will be Ace of Spades. So, yeah, it's not perfect.

Another way is to create a table picking a random number from 0-51 adding it to an array until the deck is filled. This will work but it can be slow once it gets near the end picking that random number from 0-51 to get that very last card that is not in the deck.

Thus future coding now has two interesting commands, ADD and DEL.

Add will do just that, add a value on to an existing array placing it right at the end. If it's the first item, obviously it goes in the first place. But each new successive item is placed on the end. So if you wrote code like this:

Then a would be an array starting with index 1 and contain 1, 2, and 3.

Now here is where DEL comes in and it's quite powerful what it does. In older code if we wanted to remove an item from an array you would have to create a reverse FOR/NEXT loop to copy all the older items one step above the item you were removing. I did this back in S2 and it was not speedy.

However, you do not need to do this in Pico-8, for instance, let's take our original code and remove the middle item:

Now the results are 1, 3. So with this in mind it does indeed ADD and DELETE items from the array. Doing so we can now make a proper SHUFFLE routine, where every single item in the array can be plucked out randomly, added to a separate array with ADD and neatly sealed closed from the original array with the DEL command.

And it does not swap existing items but actually pulls out each and every single item randomly to be placed in a 2nd growing array.

That is exactly what I am doing in this code, note two functions of use. SHUFFLE() which can shuffle a numeric or string array of any size as well as a function just for this code called PLOTCARD() which draws a small playing card on the screen.

Combining these functions you get a very good card shuffling routine that needs only one pass to make a perfect and completely random shuffle of a deck of cards, using our friend commands, ADD and DEL.