Click here to Skip to main content
15,894,003 members
Articles / Programming Languages / C#

War Card Game Simulation in C#

Rate me:
Please Sign up or sign in to vote.
4.77/5 (10 votes)
22 Jun 2009CPOL8 min read 85.4K   3.4K   40  
Windows Forms Application using LINQ expressions and Dictionary objects to recreate a classic card game
using System;
using System.Collections.Generic;
using System.Linq;

namespace WarGameSimulation
{
    public abstract class CardGame
    {
        protected const int sizeOfHandToDeal = 26;

        // Auto-Implemented Properties
        public Dictionary<string, int> NewCardDeck { get; protected set; }
        public Dictionary<string, int> ShuffledDeck { get; protected set; }
        public Dictionary<string, int> Player1Deck { get; protected set; }
        public Dictionary<string, int> Player2Deck { get; protected set; }
        public Dictionary<string, int> CardsOnTheTable { get; protected set; }

        protected string Player1CardKey { get; set; }
        protected int Player1CardValue { get; set; }
        protected string Player2CardKey { get; set; }
        protected int Player2CardValue { get; set; }

        protected int Player1DeckWeight { get; set; }
        protected int Player2DeckWeight { get; set; }

        protected int Player1TricksWon { get; set; }
        protected int Player2TricksWon { get; set; }
        protected int TotalTricksWon { get; set; }

        protected string StatusMessage { get; set; }
        protected int OutcomeCode { get; set; }

        /// <summary>
        /// Create a new deck of 52 unshuffled (ordered) playing cards
        /// </summary>
        /// <returns>Ordered deck of 52 cards</returns>
        protected Dictionary<string, int> CreateNewDeck()
        {
            Dictionary<string, int> tempNewDeck = new Dictionary<string, int>()
            {
                {"2 ♣", 2}, {"3 ♣", 3}, {"4 ♣", 4}, {"5 ♣", 5},
                {"6 ♣", 6}, {"7 ♣", 7}, {"8 ♣", 8}, {"9 ♣", 9},
                {"10 ♣", 10}, {"J ♣", 11}, {"Q ♣", 12}, {"K ♣", 13}, {"A ♣", 14},
                {"2 ♦", 2}, {"3 ♦", 3}, {"4 ♦", 4}, {"5 ♦", 5},
                {"6 ♦", 6}, {"7 ♦", 7}, {"8 ♦", 8}, {"9 ♦", 9},
                {"10 ♦", 10}, {"J ♦", 11}, {"Q ♦", 12}, {"K ♦", 13}, {"A ♦", 14},
                {"2 ♥", 2}, {"3 ♥", 3}, {"4 ♥", 4}, {"5 ♥", 5},
                {"6 ♥", 6}, {"7 ♥", 7}, {"8 ♥", 8}, {"9 ♥", 9},
                {"10 ♥", 10}, {"J ♥", 11}, {"Q ♥", 12}, {"K ♥", 13}, {"A ♥", 14},
                {"2 ♠", 2}, {"3 ♠", 3}, {"4 ♠", 4}, {"5 ♠", 5},
                {"6 ♠", 6}, {"7 ♠", 7}, {"8 ♠", 8}, {"9 ♠", 9},
                {"10 ♠", 10}, {"J ♠", 11}, {"Q ♠", 12}, {"K ♠", 13}, {"A ♠", 14}
            };
            return tempNewDeck;
        }

        /// <summary>
        /// Shuffle (randomize) a set of cards
        /// </summary>
        /// <param name="cardsToShuffle">Set of cards to shuffle</param>
        /// <returns>Shuffled set of cards</returns>
        protected Dictionary<string, int> ShuffleCards(Dictionary<string, int> cardsToShuffle)
        {
            Dictionary<string, int> ShuffledCards = new Dictionary<string, int>();
            Dictionary<string, int> CardsToShuffle = new Dictionary<string, int>(cardsToShuffle);
            int randomCard;
            int cardCount = CardsToShuffle.Count();
            Random RandomNumber = new Random();
            for (int counter = 0; counter <= cardCount - 1; counter++)
            {
                randomCard = RandomNumber.Next(0, cardCount - counter);
                ShuffledCards.Add(CardsToShuffle.ElementAt(randomCard).Key, CardsToShuffle.ElementAt(randomCard).Value);
                CardsToShuffle.Remove(CardsToShuffle.ElementAt(randomCard).Key);
            }
            return ShuffledCards;
        }

        /// <summary>
        /// Deal two hands of cards - assigns to Player1Deck and Player2Deck fields
        /// </summary>
        /// <param name="deckToDeal">Deck to deal cards from</param>
        /// <param name="sizeOfHand">Size of each hand of cards</param>
        protected void DealCards(Dictionary<string, int> cardsToDeal, int sizeOfHand)
        {
            Dictionary<string, int> CardsToDeal = new Dictionary<string, int>(cardsToDeal);
            Dictionary<string, int> tempPlayer1Deck = new Dictionary<string, int>();
            Dictionary<string, int> tempPlayer2Deck = new Dictionary<string, int>();
            int CardsDelt = (sizeOfHand * 2) - 1;
            int counter = 0;
            while (counter < CardsDelt)
            {
                tempPlayer1Deck.Add(CardsToDeal.ElementAt(counter).Key, CardsToDeal.ElementAt(counter).Value);
                tempPlayer2Deck.Add(CardsToDeal.ElementAt(counter + 1).Key, CardsToDeal.ElementAt(counter + 1).Value);
                counter += 2;
            }
            // Use Reverse() so last card delt is on the top of the player deck, 'face down'
            Player1Deck = (tempPlayer1Deck.Select(cards => cards).Reverse())
                .ToDictionary(item => item.Key, item => item.Value);
            Player2Deck = (tempPlayer2Deck.Select(cards => cards).Reverse())
                .ToDictionary(item => item.Key, item => item.Value);
        }

        /// <summary>
        /// Return a formatted list of cards for display
        /// </summary>
        /// <param name="deckToDisplay">Set of cards to format</param>
        /// <returns>Comma-separated list of cards</returns>
        public string DisplayDeck(Dictionary<string, int> deckToDisplay)
        {
            try
            {
                Dictionary<string, int> tempdDeckToDisplay = new Dictionary<string, int>(deckToDisplay);

                string tempDeckDisplay = "(" + tempdDeckToDisplay.Count().ToString() + ") ";
                int counter = 1;
                foreach (KeyValuePair<string, int> cards in tempdDeckToDisplay)
                {
                    tempDeckDisplay += cards.Key + ", ";
                    counter++;
                }
                char[] trimmer = { ',', ' ' };
                tempDeckDisplay = tempDeckDisplay.TrimEnd(trimmer);
                return tempDeckDisplay;
            }
            catch
            {
                return "(0)";
            }
        }

        /// <summary>
        /// Format game status as string for display
        /// </summary>
        /// <returns>Game status</returns>
        public virtual string DisplayResults()
        {
            string results = String.Format("Game Status: {0}", StatusMessage);
            return StatusMessage;
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paychex
United States United States
I am a senior software developer, architect, and project manager, specializing in .NET, JavaScript, Java, and database development, and build automation. I am currently a Lead Developer (.NET) / Developer IV for Paychex Enterprise Business Solutions. Paychex (PAYX) provides payroll, human resources, and benefits outsourcing and web-based solutions to business.

Prior to Paychex, I served as Lead Software Engineer, Operations Manager, and Technical Product Manager at Bio-Optronics. Bio-Optronics develops, deploys and operates information technology solutions to help healthcare professionals manage and optimize workflow to enhance quality, productivity, and patient and staff satisfaction and safety. Previously, I held positions of President, COO, Chief Technology Officer (CTO), and SVP of Technology for Lazer Incorporated. Lazer is a successful, digital imaging and Internet-based content management services provider.

Comments and Discussions