War Card Game v1.2

I decided to tackle the idea I’ve been having of a War Card type game. Since I’ve been playing around with lists and object properties I figured why not. Let’s see how this could turn out. This one took me awhile. About 3 weeks actually of gradually working on it a little each day. The goal was to have seperation between the player, card, and game objects. The is still in the very basic stages. No graphics, text only, and no real control over the game other than running it. A while loop takes care of creating a card deck, shuffling the cards, dealing the cards, and playing the game. I have a todo list to add more user friendly functionality in the next coming version(s). And graphics also.. 🙂

Source Code Download

WarDisplay WarDisplay2 WarDisplay3 WarSolutionExplorer

Default.aspx HTML Code File Contents

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WarCardGame.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp:Label ID="playerOneScoreIdLabel" runat="server" Text="Player 1 Score:"></asp:Label>
&nbsp;<asp:Label ID="playerOneScoreLabel" runat="server"></asp:Label>
        <br />
        <asp:Label ID="playerTwoScoreIdLabel" runat="server" Text="Player 2 Score:"></asp:Label>
&nbsp;<asp:Label ID="playerTwoScoreLabel" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Label ID="playerOneCardAmountIdLabel" runat="server" Text="Player 1 Cards:"></asp:Label>
&nbsp;<asp:Label ID="playerOneCardAmountLabel" runat="server"></asp:Label>
        <br />
        <asp:Label ID="PlayerTwoCardAmountIdLabel" runat="server" Text="Player 2 Cards:"></asp:Label>
&nbsp;<asp:Label ID="playerTwoCardAmountLabel" runat="server"></asp:Label>
        <br />
        <br />
        <asp:Label ID="playWarLabel" runat="server" Text="Play War!!!"></asp:Label>
        <br />
        <br />
        <asp:Button ID="playButton" runat="server" OnClick="playButton_Click" Text="Play" />
        <br />
        <br />
        <asp:Label ID="resultsLabel" runat="server"></asp:Label>

    </div>
    </form>
</body>
</html>

Nothing special here. Just some text label objects to display the player, card information, and the play button.

Default.aspx Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WarCardGame
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                resultsLabel.Text = "";
            }
            else
            {

            }
        }

        protected void playButton_Click(object sender, EventArgs e)
        {
            //
            // Getting some cards to play with.
            Cards cards = new Cards();
            List<Cards> deckOfCards = cards.CreateGenericCardDeck();

            // Create some players.
            Player playerOne = createPlayer("Player 1");
            Player playerTwo = createPlayer("Player 2");

            //
            // Creating the game and display objects.
            WarCardGame warCardGame = new WarCardGame(playerOne, playerTwo, deckOfCards);

            // Shuffling the cards for the game.
            warCardGame.ShuffleAndDealCards();

            // Showing the status of dealing the cards.
            resultsLabel.Text += String.Format("<h3>Dealing Cards...</h3></br>");

            // Showing what cards are dealt to each player.
            resultsLabel.Text += warCardGame.DisplayResults("DisplayDealtCards");

            // Running the card battle until one player reaches a certain score.
            resultsLabel.Text += String.Format("<h3>Begin Battle...</h3></br>");
            while(playerOne.PlayerScore < 5 && playerTwo.PlayerScore < 5)
            {
                // Showing what cards are being played for the round.
                resultsLabel.Text += warCardGame.DisplayResults("DisplayRound");

                // Start the behind the scenes work to play the game.
                warCardGame.StartWarGame();

                // Displaying the round winner.
                resultsLabel.Text += warCardGame.DisplayResults("DisplayWinner");
            }

            //
            // Updating the player score labels.
            playerOneScoreLabel.Text = playerOne.PlayerScore.ToString();
            playerTwoScoreLabel.Text = playerTwo.PlayerScore.ToString();

            // Updating the players card amount labels.
            playerOneCardAmountLabel.Text = playerOne.PlayerCards.Count().ToString();
            playerTwoCardAmountLabel.Text = playerTwo.PlayerCards.Count().ToString();
        }

        // Private methods.
        //
        // Method used to create game player objects and give them a list to take cards in.
        private Player createPlayer(string playerName)
        {
            Player player = new Player()
            {
                PlayerName = playerName,
                PlayerCards = new List<Cards> { }
            };
            return player;
        }
    }
}
// TODO Make it so you can show the players score and card count between rounds.

// TODO Look into the next version to implement more user control of the game.
// For example buttons to control the dealing of the cards, shuffling of the cards,
// and control of each round of play.

For now everything is tied to the playButton click event method. Since the program is pretty much a click, run, and done type program you can see how I’m creating and using the objects. I do have a private method that’s in charge of creating the Player objects and properties. The resultLabel I’m constantly adding too based on any particular part of the game. For now there’s a while loop running based on the first player reaching a score of 5 before the loop breaks out. I did make seperate labels for each players score. This is easier for me at this time. I might change it later. You can also see my TODO comments at the end.. 🙂

Cards.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WarCardGame
{
    public class Cards
    {
        // Public read-only properties
        //
        public string CardName { get; private set; }
        public string CardSuit { get; private set; }
        public int CardValue { get; private set; }

        // Public methods
        //
        // Method used to create a generic card deck.
        public List<Cards> CreateGenericCardDeck()
        {
            List<Cards> cards = new List<Cards>()
            {
                // 2 Card suit.
                new Cards { CardName = "2", CardSuit = "Clubs", CardValue = 2 },
                new Cards { CardName = "2", CardSuit = "Diamonds", CardValue = 2 },
                new Cards { CardName = "2", CardSuit = "Hearts", CardValue = 2 },
                new Cards { CardName = "2", CardSuit = "Spades", CardValue = 2 },

                // 3 card suit.
                new Cards { CardName = "3", CardSuit = "Clubs", CardValue = 3 },
                new Cards { CardName = "3", CardSuit = "Diamonds", CardValue = 3 },
                new Cards { CardName = "3", CardSuit = "Hearts", CardValue = 3 },
                new Cards { CardName = "3", CardSuit = "Spades", CardValue = 3 },

                // 4 card suit.
                new Cards { CardName = "4", CardSuit = "Clubs", CardValue = 4 },
                new Cards { CardName = "4", CardSuit = "Diamonds", CardValue = 4 },
                new Cards { CardName = "4", CardSuit = "Hearts", CardValue = 4 },
                new Cards { CardName = "4", CardSuit = "Spades", CardValue = 4 },

                // 5 card suit.
                new Cards { CardName = "5", CardSuit = "Clubs", CardValue = 5 },
                new Cards { CardName = "5", CardSuit = "Diamonds", CardValue = 5 },
                new Cards { CardName = "5", CardSuit = "Hearts", CardValue = 5 },
                new Cards { CardName = "5", CardSuit = "Spades", CardValue = 5 },

                // 6 card suit.
                new Cards { CardName = "6", CardSuit = "Clubs", CardValue = 6 },
                new Cards { CardName = "6", CardSuit = "Diamonds", CardValue = 6 },
                new Cards { CardName = "6", CardSuit = "Hearts", CardValue = 6 },
                new Cards { CardName = "6", CardSuit = "Spades", CardValue = 6 },

                // 7 card suit.
                new Cards { CardName = "7", CardSuit = "Clubs", CardValue = 7 },
                new Cards { CardName = "7", CardSuit = "Diamonds", CardValue = 7 },
                new Cards { CardName = "7", CardSuit = "Hearts", CardValue = 7 },
                new Cards { CardName = "7", CardSuit = "Spades", CardValue = 7 },

                // 8 card suit.
                new Cards { CardName = "8", CardSuit = "Clubs", CardValue = 8 },
                new Cards { CardName = "8", CardSuit = "Diamonds", CardValue = 8 },
                new Cards { CardName = "8", CardSuit = "Hearts", CardValue = 8 },
                new Cards { CardName = "8", CardSuit = "Spades", CardValue = 8 },

                // 9 card suit.
                new Cards { CardName = "9", CardSuit = "Clubs", CardValue = 9 },
                new Cards { CardName = "9", CardSuit = "Diamonds", CardValue = 9 },
                new Cards { CardName = "9", CardSuit = "Hearts", CardValue = 9 },
                new Cards { CardName = "9", CardSuit = "Spades", CardValue = 9 },

                // 10 card suit.
                new Cards { CardName = "10", CardSuit = "Clubs", CardValue = 10 },
                new Cards { CardName = "10", CardSuit = "Diamonds", CardValue = 10 },
                new Cards { CardName = "10", CardSuit = "Hearts", CardValue = 10 },
                new Cards { CardName = "10", CardSuit = "Spades", CardValue = 10 },

                // Jack card suit.
                new Cards { CardName = "Jack", CardSuit = "Clubs", CardValue = 11 },
                new Cards { CardName = "Jack", CardSuit = "Diamonds", CardValue = 11 },
                new Cards { CardName = "Jack", CardSuit = "Hearts", CardValue = 11 },
                new Cards { CardName = "Jack", CardSuit = "Spades", CardValue = 11 },

                // Queen card suit.
                new Cards { CardName = "Queen", CardSuit = "Clubs", CardValue = 12 },
                new Cards { CardName = "Queen", CardSuit = "Diamonds", CardValue = 12 },
                new Cards { CardName = "Queen", CardSuit = "Hearts", CardValue = 12 },
                new Cards { CardName = "Queen", CardSuit = "Spades", CardValue = 12 },

                // King card suit.
                new Cards { CardName = "King", CardSuit = "Clubs", CardValue = 13 },
                new Cards { CardName = "King", CardSuit = "Diamonds", CardValue = 13 },
                new Cards { CardName = "King", CardSuit = "Hearts", CardValue = 13 },
                new Cards { CardName = "King", CardSuit = "Spades", CardValue = 13 },

                // Ace card suit.
                new Cards { CardName = "Ace", CardSuit = "Clubs", CardValue = 14 },
                new Cards { CardName = "Ace", CardSuit = "Diamonds", CardValue = 14 },
                new Cards { CardName = "Ace", CardSuit = "Hearts", CardValue = 14 },
                new Cards { CardName = "Ace", CardSuit = "Spades", CardValue = 14 }
            };
            return cards;
        }
    }
}

The cards class only has one role. Create a deck of cards with a name property, suit property, and a card value property. There’s only one public method that creates a 52 card deck to be used by the game. I opted to keep this in it’s own class in the even I decided to expand this game to include other types of card games.

Player.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WarCardGame
{
    public class Player
    {
        // Public properties
        //
        public string PlayerName { get; set; }          // Property for the players name.
        public bool IsWinner { get; set; }              // Property flag for the winner.
        public int PlayerScore { get; set; }            // Property for the players score.
        public List<Cards> PlayerCards { get; set; }    // List property that holds the players cards.
        public Cards CardInHand { get; set; }           // Property that hold what current card the player is holding.
    }
}

The Player class holds all of the properties associated with players of the war card game. There isn’t any methods other than using the default contructor when an object is created. Almost all of the properties are self explanatory. I’m using a bool value to determine if the player is the winner. A Generic List property to hold the players cards. And a Cards property to simulate what card the players has in their hand at the time of being played.

WarCardGame.cs Code File Contents

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WarCardGame
{
    public class WarCardGame
    {
        // Public read-only properties.
        //
        public Player PlayerOne { get; private set; }
        public Player PlayerTwo { get; private set; }
        public List<Cards> Cards { get; private set; }              // List that holds the unshuffled deck of cards.
        public List<Cards> CardsShuffled { get; private set; }      // List that holds the shuffled deck of cards.
        public List<Cards> WarCards { get; private set; }           // List that holds the cards in the event of a war.
        public Random Random { get; private set; }
        public bool IsWar { get; private set; }                     // Bool flag used to indicate a war scenario.
        public bool RepeatWar { get; private set; }                 // Bool flag used to indicate a repeat war scenario.

        // Constructors
        //
        // Constructor method used for a 2 player game.
        public WarCardGame(Player playerOne, Player playerTwo, List<Cards> cardDeck)
        {
            this.PlayerOne = playerOne;
            this.PlayerTwo = playerTwo;
            this.Cards = cardDeck;
            this.Random = new Random();
            this.Cards = cardDeck;
            CardsShuffled = new List<Cards>();
            WarCards = new List<Cards>();
        }

        // Public methods.
        //
        // Method that takes care of shuffling the cards. I take the cards from the Cards list and
        // randomly adds them to the CardsShuffled list.
        public void ShuffleAndDealCards()
        {
            // Shuffling the deck of cards using the amount of cards in the list as the parmameter.
            shuffleCards(Cards.Count());

            // Dealing the cards out to the players.
            dealCards();
        }

        // Method that takes care of displaying various results.
        public string DisplayResults(string resultType)
        {
            string result = "";

            // Displaying the dealt cards.
            if (resultType == "DisplayDealtCards")
                result += displayDealtCards();
            else if (resultType == "DisplayRound")
                result += displayRound();
            else if (resultType == "DisplayWinner")
                result += displayWinner();
            return result;
        }

        // Method that takes care of doing the behind the scenes work for the game.
        public void StartWarGame()
        {
            startWarGame(IsWar);
        }

        //Private methods.
        //
        // Method that takes care of shuffling the cards.
        private void shuffleCards(int numOfCards)
        {
            // Modified version of the fisher-yates example on stack-overflow. *1
            int n = numOfCards;
            while (n > 0)
            {
                n--;
                int k = Random.Next(n + 1);
                CardsShuffled.Add(Cards[k]);
                Cards.RemoveAt(k);
            }
        }

        // Method that takes care of dealing the cards out to the players.
        private void dealCards()
        {
            int halfDeck = CardsShuffled.Count() / 2;
            for (int i = 0; i < halfDeck; i++)
            {
                PlayerOne.PlayerCards.Add(CardsShuffled[0]);     // Give the first card in the deck.
                CardsShuffled.RemoveAt(0);                       // Remove the card from the deck.
                PlayerTwo.PlayerCards.Add(CardsShuffled[0]);     // Give the next card in the deck.
                CardsShuffled.RemoveAt(0);                       // Remove the card from the deck.
            }
        }

        // Method that takes care of the back-end work of the wargame.
        private void startWarGame(bool isWar)
        {
            // If IsWar is true run one way.
            if (isWar)
            {
                // This is if after a round of war the next selected cards are also the same.
                // Basically re-running the war until a winner is declared.
                if (RepeatWar)
                    playWar();

                // Otherwise run the war round once.
                else
                    playWar();
            }

            // If IsWar is false run another way.
            else
            {
                // Taking a card from the players deck and putting it in their hand.
                PlayerOne.CardInHand = PlayerOne.PlayerCards[0];
                PlayerTwo.CardInHand = PlayerTwo.PlayerCards[0];

                // Run the war round.
                playWar(PlayerOne.CardInHand, PlayerTwo.CardInHand);
            }
        }

        // Default method to play the war game. This one takes care of functions in the event of the same card
        // being drawn by both players.
        private void playWar()
        {
            // Adding the cards that will be played and compared to the WarCards list.
            for (int i = 0; i < 5; i++)
            {
                WarCards.Add(PlayerOne.PlayerCards[i]);
                PlayerOne.PlayerCards.RemoveAt(0);
                WarCards.Add(PlayerTwo.PlayerCards[i]);
                PlayerTwo.PlayerCards.RemoveAt(0);
            }

            // Comparing the next available cards from each players deck.
            compareCards(PlayerOne.PlayerCards[0], PlayerTwo.PlayerCards[0]);

            // Check and make sure the RepeatWar flag isn't true. If not distribute the winnings
            // and clean up the WarCards list.
            if (!RepeatWar)
            {
                distributeWinnings();
                WarCards.Clear();
            }
        }

        // Overloaded method to play the war game for one round.
        private void playWar(Cards playerOneCard, Cards playerTwoCard)
        {
            // Removing the played cards from the players deck.
            PlayerOne.PlayerCards.RemoveAt(0);
            PlayerTwo.PlayerCards.RemoveAt(0);

            // Calling the method to compare the players card values.
            compareCards(PlayerOne.CardInHand, PlayerTwo.CardInHand);

            // Call the distributeWinnings method to see who won and give the cards to the winner.
            distributeWinnings(PlayerOne.CardInHand, PlayerTwo.CardInHand);
        }

        // Method that takes care of comparing the players cards.
        private void compareCards(Cards playerOneCard, Cards playerTwoCard)
        {
            // Resetting the player and game flags.
            PlayerOne.IsWinner = false;
            PlayerTwo.IsWinner = false;
            RepeatWar = false;
            IsWar = false;

            // Comparing the card values to determine the winner.
            // If both cards are the same return.
            if (playerOneCard.CardValue == playerTwoCard.CardValue)
            {
                RepeatWar = true;
                IsWar = true;
            }
            else if (playerOneCard.CardValue > playerTwoCard.CardValue)
            {
                PlayerOne.IsWinner = true;
                PlayerOne.PlayerScore++;
            }
            else
            {
                PlayerTwo.IsWinner = true;
                PlayerTwo.PlayerScore++;
            }
        }

        // Default method that takes care of distributing the cards to the war round winner.
        private void distributeWinnings()
        {
            if (PlayerOne.IsWinner)
            {
                // Distribute winnings to player one.
                foreach (Cards cardItems in WarCards)
                    PlayerOne.PlayerCards.Add(cardItems);

                // Taking the war card from playerTwo's deck and adding to playerOne's deck.
                PlayerOne.PlayerCards.Add(PlayerTwo.PlayerCards[0]);
                PlayerTwo.PlayerCards.RemoveAt(0);
            }
            else
            {
                // Distribute winning to player two.
                foreach (Cards cardItems in WarCards)
                    PlayerTwo.PlayerCards.Add(cardItems);

                // Taking the war card from playerOne's deck and adding to playerTwo's deck.
                PlayerTwo.PlayerCards.Add(PlayerOne.PlayerCards[0]);
                PlayerOne.PlayerCards.RemoveAt(0);
            }
        }

        // Overloaded method that takes care of distributing the war round winnings.
        private void distributeWinnings(Cards playerOneCard, Cards playerTwoCard)
        {
            if (PlayerOne.IsWinner)
            {
                // Adding the cards to player one's deck.
                PlayerOne.PlayerCards.Add(playerOneCard);
                PlayerOne.PlayerCards.Add(playerTwoCard);
            }
            else
            {
                // Adding the cards to player two's deck.
                PlayerTwo.PlayerCards.Add(playerOneCard);
                PlayerTwo.PlayerCards.Add(playerTwoCard);
            }
        }

        // Display methods.
        // Method that takes care of displaying the dealt cards to each player.
        private string displayDealtCards()
        {
            string result = "";

            // Iterating thru 2 lists at the same time to display the cards that are being dealt.
            // StackOverflow solution *2.
            using(var playerOne = PlayerOne.PlayerCards.GetEnumerator())
            using(var playerTwo = PlayerTwo.PlayerCards.GetEnumerator())
            {
                while(playerOne.MoveNext() && playerTwo.MoveNext())
                {
                    var playerOneCard = playerOne.Current;
                    var playerTwoCard = playerTwo.Current;
                    result += String.Format("{0} was dealt a {1} of {2}</br>{3} was dealt a {4} of {5}</br></br>",
                        PlayerOne.PlayerName, playerOneCard.CardName, playerOneCard.CardSuit,
                        PlayerTwo.PlayerName, playerTwoCard.CardName, playerTwoCard.CardSuit);
                }
            }
            return result;
        }

        // Method that takes care of displaying the cards for the round of war.
        private string displayRound()
        {
            string result = "";

            // If statement that compares the first card from each players deck to be played. If the same
            // then proceed with figuring out what is needed for war. If not the same then proceed with
            // doing something else.
            if (PlayerOne.PlayerCards[0].CardValue == PlayerTwo.PlayerCards[0].CardValue)
            {
                // Setting is IsWar property flag to true.
                IsWar = true;

                if (RepeatWar)
                {
                    // Displaying the next set of battle cards for the war.
                    result += String.Format("Battle Cards: {0} of {1} versus {2} of {3}</br>",
                        PlayerOne.PlayerCards[5].CardName, PlayerOne.PlayerCards[5].CardSuit,
                        PlayerTwo.PlayerCards[5].CardName, PlayerTwo.PlayerCards[5].CardSuit);
                }
                else
                {
                    // Displaying the WAR message notification.
                    result += String.Format("Battle Cards: {0} of {1} versus {2} of {3}</br>*****WAR*****</br></br>",
                        PlayerOne.PlayerCards[0].CardName, PlayerOne.PlayerCards[0].CardSuit,
                        PlayerTwo.PlayerCards[0].CardName, PlayerTwo.PlayerCards[0].CardSuit);

                    // Displaying the battle cards for the round.
                    result += String.Format("Battle Cards: {0} of {1} versus {2} of {3}</br>",
                        PlayerOne.PlayerCards[5].CardName, PlayerOne.PlayerCards[5].CardSuit,
                        PlayerTwo.PlayerCards[5].CardName, PlayerTwo.PlayerCards[5].CardSuit);
                }

                // Displaying the next 4 cards from each player that will be played.
                result += String.Format("Bounty...</br>&nbsp&nbsp{0} of {1}</br>&nbsp&nbsp{2} of {3}</br>&nbsp&nbsp{4} of {5}</br>&nbsp&nbsp{6} of {7}</br>&nbsp&nbsp{8} of {9}</br>&nbsp&nbsp{10} of {11}</br>&nbsp&nbsp{12} of {13}</br>&nbsp&nbsp{14} of {15}</br>",
                    PlayerOne.PlayerCards[1].CardName, PlayerOne.PlayerCards[1].CardSuit,
                    PlayerTwo.PlayerCards[1].CardName, PlayerTwo.PlayerCards[1].CardSuit,
                    PlayerOne.PlayerCards[2].CardName, PlayerOne.PlayerCards[2].CardSuit,
                    PlayerTwo.PlayerCards[2].CardName, PlayerTwo.PlayerCards[2].CardSuit,
                    PlayerOne.PlayerCards[3].CardName, PlayerOne.PlayerCards[3].CardSuit,
                    PlayerTwo.PlayerCards[3].CardName, PlayerTwo.PlayerCards[3].CardSuit,
                    PlayerOne.PlayerCards[4].CardName, PlayerOne.PlayerCards[4].CardSuit,
                    PlayerTwo.PlayerCards[4].CardName, PlayerTwo.PlayerCards[4].CardSuit);
            }
            else
            {
                // Setting the IsWar property to false.
                IsWar = false;

                // Displaying the cards for the battle round.
                result += String.Format("Battle Cards: {0} of {1} versus {2} of {3}</br>",
                    PlayerOne.PlayerCards[0].CardName, PlayerOne.PlayerCards[0].CardSuit,
                    PlayerTwo.PlayerCards[0].CardName, PlayerTwo.PlayerCards[0].CardSuit);

                // Displaying the bounty for the war round.
                result += String.Format("Bounty...</br>&nbsp&nbsp{0} of {1}</br>&nbsp&nbsp{2} of {3}</br>",
                    PlayerOne.PlayerCards[0].CardName, PlayerOne.PlayerCards[0].CardSuit,
                    PlayerTwo.PlayerCards[0].CardName, PlayerTwo.PlayerCards[0].CardSuit);
            }
            return result;
        }

        // Method that takes care of displaying the winner.
        private string displayWinner()
        {
            string result = "";

            if (PlayerOne.IsWinner)
                result += String.Format("<strong>{0} Wins!</strong></br></br>", PlayerOne.PlayerName);
            else if (PlayerTwo.IsWinner)
                result += result += String.Format("<strong>{0} Wins!</strong></br></br>", PlayerTwo.PlayerName);
            else
                result += String.Format("<strong>War Again!</strong></br></br>");

            return result;
        }
    }
}
// *1 : http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp
// *2 : http://stackoverflow.com/questions/18395943/using-foreach-to-iterate-simultaneously-through-multiple-lists-syntax-sugar

This class is where the game all starts to come together. There are various properties, methods, and overloaded methods being used to play the game. For now the game is only played by two players. There is a Random property that’s used to give me a random variable to use in methods.

There are two bool flag properties being used to signal a war and repeat war state of the game. This is for when the players draw the same card and if they happen to draw the same card during a already running war game.

The three generic List properties hold the deck of cards, the cards after they’re shuffled, and any cards that need be held during a war or repeat war game. I’ve overloaded the default constructor to create a two player game. This is done by taking the two player parameters and a List parameter. From these parameters the player objects, random object, cardDeck list object, CardShuffled, and WarCards list objects to be used at various points of the game.

You will notice that I’m using various public methods as simple pointers to the private methods. My thinking behind this was to hide the actual work being done from the other classes while still making the trigger methods available to call upon. The DisplayResult methods gets a little creative by taking a string value as a parameter and deciding what method to call based on the value.

Now onto the the private methods where the work takes place. The shuffleCards method was a slight modification of the fisher-yates shuffle method found on stack-overflow. This takes the cards from the Cards list, uses the random object to shuffle them, then add them to the CardShuffled list. I could just re-add them to the same Cards list. However I want to be able to re-feed cards into that list and re-shuffle at a later date in a later version maybe.

The dealCards methods does just that. It deals the cards to each players deck of cards to be used to play the game. Basically I’m cutting the shuffled deck in half and adding the cards to the players card list with a for loop.

The startWarGame method took some time to figure out. I needed a way to determine if the same card was drawn to start a war, determine if the same card was drawn again in the war scenario, or just run a normal game comparing two cards. Throughout the entire game I’m relying on the nature of lists that when you take an item from the first index that the rest basically move up. This is simulating taking a card from the top of the deck and returning cards at the bottom of the deck. The war and repeatWar flags are used here to determing if a normal wargame is to be played or the players start putting out cards for an all out war. You will see calls to the playWar methods and those methods are overloaded with different signatures. Again this was done because I try and keep my methods as specific as possible while keeping them within 8-10 lines of code for simple tasks.

The compareCards method does just that. It takes the two players cards and compares the values of them, determines the winner, adjusts the players score by one point, and sets the win flag to true. The distributeWinnings method is overloaded. This was done to serve the normal single war round along with the all out war game in the event of a same card draw. One method cycles thru the WarCards list and distributes the cards to the appropriate winners cards list. The other method just takes the single cards and adds them to the winners cards list.

The displayDealtCards method is kinda cool. I found a solution in stack-overflow that I modified to cycle thru more than one list with a using statement and the GetEnumerator method of the List object. Then nesting a while statement with the MoveNext method of GetEnumerator to cycle thru, get the card value, store the data in a result variable, and return it.

The displayRound method got a little tricky. I might go back and split it up into some helper stub methods and re-factor. Lots going on here based on if the isWar and repeatWar flags have been tripped. If not then just a regular round is stored in a result string variable and returned. I’m taking advantage of the String.Format method to construct the way I want the string to look.

And finally the displayWinner method determines the winner based on the IsWinner property of the player. Then returns a String.Format result.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s