The Fisher-Yates Shuffle

using UnityEngine;
using System.Collections;

public class Shuffle : MonoBehaviour
{
   public static void ShuffleItems<T>(T[] items)
   {
      for (int i = items.Length - 1; i > 0; i--)
      {
         int r = Random.Range (0,i);
         T temp = items[i];
         items[i] = items[r];
         items[r] = temp;
      }
   }
}

If you’ve played Galactic Scholar you may have noticed the cards always come at the ship in a different order. I did this intentionally so that the player could not simply memorize the order thus making it more challenging. I achieved this by implementing the Fisher-Yates shuffle(above).

using UnityEngine;
using System.Collections;

public class PlayingCards : MonoBehaviour
{
   int[] deck = new int[52];

   void Start ()
   {
      InitializeDeck();
   }

   void Update ()
   {
      if (Input.GetKeyDown (KeyCode.Return))
      {
         Shuffle.ShuffleItems(deck);
         foreach(int card in deck)
         {
            print(card.ToString());
         }
      }
   }

   void InitializeDeck ()
   {
      for(int i = 0; i < 52; i++)
      {
         deck[i] = i + 1;
      }
   }
}

In this script we’ve created a standard deck of 52 cards with a numerical value assigned to each one. Then we call ShuffleItems() and print the result to the console.

Considerations

  1. ShuffleItems() is a generic function indicated by the <T> and T[] syntax.  This allows you to call this function with different types.
  2. Random.Range() is a Unity function that can return either an int or a float inclusive.  So if you have a range (0,5) it could return either 0 or 5.
  3. Because this is a generic function that allows you to use arrays of any length, it is very reusable thus good for modular game development.
Advertisements