Skip to content

Instantly share code, notes, and snippets.

@eviathan
Last active December 7, 2020 12:28
Show Gist options
  • Save eviathan/379e8164de94cd3d611759a4b9423757 to your computer and use it in GitHub Desktop.
Save eviathan/379e8164de94cd3d611759a4b9423757 to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public static class IListExtensions {
public static void Shuffle<T>(this IList<T> ts) {
var count = ts.Count;
var last = count - 1;
for (var i = 0; i < last; ++i) {
var r = UnityEngine.Random.Range(i, count);
var tmp = ts[i];
ts[i] = ts[r];
ts[r] = tmp;
}
}
}
public enum Suit { None, Diamonds, Hearts, Spades, Clubs }
public enum CardValue
{
Joker, Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Jaques, Queen, King,
}
public class Card
{
public CardValue Value { get; }
public Suit Suit { get; }
public Card(Suit suit, CardValue value)
{
Value = value;
Suit = suit;
}
public override string ToString()
{
return $"{Enum.GetName(typeof(CardValue), Value)}{(Suit == Suit.None ? string.Empty : $" of {Enum.GetName(typeof(Suit), Suit)}")}";
}
}
public class CardFactory
{
public IEnumerable<Card> GetSuit(Suit suit)
{
var cards = new List<Card>();
var cardValues = Enum.GetValues(typeof(CardValue))
.Cast<CardValue>();
foreach(var cardValue in cardValues)
{
if(cardValue != CardValue.Joker)
cards.Add(new Card(suit, cardValue));
};
return cards;
}
public IEnumerable<Card> GetDeck(bool withJokers = false)
{
var cards = new List<Card>();
var suits = Enum.GetValues(typeof(Suit))
.Cast<Suit>();
if(withJokers)
{
cards.Add(new Card(Suit.None, CardValue.Joker));
cards.Add(new Card(Suit.None, CardValue.Joker));
}
foreach(var suit in suits)
{
if(suit != Suit.None)
cards.AddRange(GetSuit(suit));
};
return cards;
}
}
public class CardGame : MonoBehaviour
{
public int DeckAmount = 2;
public List<Card> Cards = new List<Card>();
void Start()
{
var cardFactory = new CardFactory();
for (int i = 0; i < DeckAmount; i++)
Cards.AddRange(cardFactory.GetDeck(withJokers: true));
Cards.Shuffle();
Cards.ForEach(Debug.Log);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment