Esempio n. 1
0
 public Game(Deck deck)
 {
     this.deck   = deck;
     playerCards = deck.GetCard(2);
     dealerCards = new List <Card>();
     dealerCards.Add(deck.GetCard());
 }
Esempio n. 2
0
        private void StartGame()
        {
            scoreP1 = scoreP2 = 0;
            m_rootZ = 0;

            firstHand      = true;
            showP2Score    = false;
            isAskingToDraw = true;
            p1HasDrawn     = false;
            cpuHasStopped  = false;
            winner         = "";

            p1Hand = new CardHand();
            p2Hand = new CardHand();

            m_dataList = new BlackJackDataList();
            bjData     = new BlackJackData();

            // prepare the deck
            m_deck.RemoveAllCards();

            m_allCards = m_allCards_cpy.ToList();
            m_random   = new Random();

            // Source deck
            for (int i = 0; i < m_allCards.Count; i++)
            {
                m_deck.AddCard(GetRandomCard());
                i--;
            }

            // the card under the pile
            m_deck.GetCard(0).setTurned(false);

            m_dataList.AddDeckData(m_deck);

            Card drawn;

            // draw the first 2 cards
            for (int i = 0; i < 2; i++)
            {
                drawn = m_deck.RemoveLast();
                drawn.setTurned(true);
                p1Hand.AddCard(drawn);
                //System.Diagnostics.Debug.WriteLine("Giocatore 1 ha pescato : " + drawn.CardId() + " " + drawn.Suit());

                drawn = m_deck.RemoveLast();
                drawn.setTurned((i % 2 == 0) ? true : false);
                p2Hand.AddCard(drawn);
                //System.Diagnostics.Debug.WriteLine("Avversario ha pescato : " + drawn.CardId() + " " + drawn.Suit());
            }
        }
Esempio n. 3
0
        public void Shuffle()
        {
            List <Card> newDeck  = new List <Card>();
            Deck        ChkDck   = new Deck();
            List <bool> assigned = new List <bool>();  // keep track of what locs used in newDeck

            for (int i = 0; i < ChkDck.Cards.Count(); i++)
            {
                assigned.Add(false);
            }

            int seed = 0;

            Console.Write("Enter seed: ");
            seed = Convert.ToInt32(Console.ReadLine()); //user can break if they don't submit a valid integer
            Random rGen      = new Random(seed);
            int    shufIndex = 0;

            shufIndex = rGen.Next(52);
            for (int i = 0; i < ChkDck.Cards.Count(); i++)
            {
                while (assigned[shufIndex])
                {
                    shufIndex = rGen.Next(ChkDck.Cards.Count());
                }
                newDeck.Add(ChkDck.GetCard(shufIndex));
                assigned[shufIndex] = true;
            }
            Cards = newDeck;
        }
Esempio n. 4
0
        public void Loop()
        {
            //player one turn
            while (!PlayerOne.IsGameCompleted() && PlayerOne.WantCard())
            {
                PlayerOne.GiveCard(Deck.GetCard());
            }

            if (PlayerOne.CountPoints() > 21)
            {
                Console.WriteLine("Player one lost the game!");
            }

            else if (PlayerOne.CountPoints() == 21)
            {
                Console.WriteLine("Player wins!");
            }

            else
            {
                //player two turn
                Console.WriteLine("Dealers turn!");
                while (!PlayerTwo.IsGameCompleted() && PlayerTwo.WantCard())
                {
                    PlayerTwo.GiveCard(Deck.GetCard());
                }

                Console.WriteLine("Player one points: {0}", PlayerOne.CountPoints());
                Console.WriteLine("Dealer points: {0}", PlayerTwo.CountPoints());

                int playerPoints = PlayerOne.CountPoints();
                int dealerPoints = PlayerTwo.CountPoints();

                if (dealerPoints > 21 || playerPoints > dealerPoints)
                {
                    Console.WriteLine("Player one wins ");
                }

                else
                {
                    Console.WriteLine("Dealer wins!");
                }

                // īsā versija:
                // Console.WriteLine(dealerPoints > 21 || playerPoints > dealerPoints ? "You win" : "Dealer wins");
            }
        }
Esempio n. 5
0
        public Card TakeCard(Deck deck)
        {
            var card = deck.GetCard();

            Result += card.Point;
            _myCards.Add(card);
            return(card);
        }
Esempio n. 6
0
        public void StartNewGame()
        {
            PlayerOne = new Player();
            PlayerTwo = new Dealer();

            Deck = new Deck();
            Deck.Shuffle();

            PlayerOne.GiveCard(Deck.GetCard());
            PlayerOne.GiveCard(Deck.GetCard());

            PlayerTwo.GiveCard(Deck.GetCard());
            PlayerTwo.GiveCard(Deck.GetCard());

            //garākais variants:
            //Card card1 = Deck.GetCard();
            //PlayerOne.GiveCard(card1);
        }
Esempio n. 7
0
        public bool Hit(List <Card> cards)
        {
            cards.Add(deck.GetCard());
            if (isBust(cards))
            {
                return(true);
            }

            return(false);
        }
Esempio n. 8
0
 /// <summary>
 /// add Deck into BlackJackDataList
 /// </summary>
 /// <param name="deck"></param>
 public void AddDeckData(Deck deck)
 {
     for (int j = 0; j < deck.CardCount(); j++)
     {
         Card          card = deck.GetCard(j);
         BlackJackData data = new BlackJackData();
         data.AddCardData(card, deck.InternalDeckId());
         m_list.Add(data);
     }
 }
Esempio n. 9
0
        public void DealCards(int num, Deck deck)
        {
            string cardString = (num == 1) ? "card" : "cards";

            Console.WriteLine("Dealing new " + cardString);
            for (int i = 0; i < num; i++)
            {
                hand.AddCard(deck.GetCard());
            }
            Console.WriteLine(this.ToString());
        }
Esempio n. 10
0
static Card[] GetDeal(Deck d, Card[] Hand, ref int HandCounter, ref int TableCounter)         //gives a deal of a card to either the dealer or the player and reshuffles the deck
{
    bool x = true;

    if (x)
    {
        if (TableCounter >= 51)         //Checks current hand
        {
            d.Shuffle();
            TableCounter = 0;
        }
        Hand[HandCounter++] = d.GetCard(TableCounter++);
    }
    return(Hand);
}
Esempio n. 11
0
        protected void btnStart_Click(object sender, EventArgs e)
        {
            int st;

            if (int.TryParse(txtAmountToBet.Text, out st) && int.Parse(txtAmountToBet.Text) < 101 && int.Parse(txtAmountToBet.Text) > 0)
            {
                deck.LoadDeck();
                bet = double.Parse(txtAmountToBet.Text);
                Application["bet"] = bet;

                dealerCards = new List <Card>();
                playerCards = new List <Card>();
                dealerCards.Add(deck.GetCard());
                playerCards.Add(deck.GetCard());
                playerCardIndex = 1;
                Application["playerCardIndex"] = playerCardIndex;
                dealerCards.Add(deck.GetCard());
                playerCards.Add(deck.GetCard());

                Application["dealerCards"]      = dealerCards;
                Application["playerCards"]      = playerCards;
                Application["totalCardsDealer"] = dealerCards[0].CardValue + dealerCards[1].CardValue;
                AceValuePlayer(playerCards);
                AceValueDealer(dealerCards);

                playerPlace.InnerHtml  = playerCards[0].CardImage;
                playerPlace.InnerHtml += playerCards[1].CardImage;
                dealerPlace.InnerHtml  = dealerCards[0].CardImage;
                dealerPlace.InnerHtml  = dealerCards[1].CardImage;
                dealerPlace.InnerHtml += dealerCards[1].faceDown();

                btnHit.Enabled   = true;
                btnStand.Enabled = true;


                if (totalCardsPlayer == 21)
                {
                    playerMoney += (bet * 1.5);
                    Application["playerMoney"] = playerMoney;
                    lblPlayerMoney.Text        = playerMoney.ToString();
                    txtAmountToBet.Text        = 0.ToString();
                    lblInfo.Text = $"You win! You got {totalCardsPlayer}.";
                }
                if (totalCardsDealer == 21)
                {
                    playerMoney -= (bet * 1.5);
                    Application["playerMoney"] = playerMoney;
                    lblPlayerMoney.Text        = playerMoney.ToString();
                    txtAmountToBet.Text        = 0.ToString();
                    lblInfo.Text = $"You lose! Dealer got {totalCardsDealer}.";
                }
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            Deck deck = new Deck();

            deck.ShowAllDeck();

            Console.WriteLine("===================================");
            deck.Mix();
            deck.ShowAllDeck();
            Console.WriteLine("===================================");
            Console.WriteLine();

            Casino casino = new Casino();
            Player player = new Player();

            casino.AddCard(deck.GetCard());
            player.AddCard(deck.GetCard());
            casino.AddCard(deck.GetCard());
            player.AddCard(deck.GetCard());

            casino.ShowFirstCard();

            Console.WriteLine("Your cards:");
            int playerAmount = player.CalculateAmount();

            player.ShowCards();
            player.AskPlayer();
            while (player.Hit)
            {
                Console.WriteLine("Your cards:");
                player.AddCard(deck.GetCard());
                playerAmount = player.CalculateAmount();
                player.ShowCards();
                player.AskPlayer();
            }
            Console.WriteLine("===================================");
            Console.WriteLine("Casino's cards:");
            int casinoAmount = casino.CalculateAmount();

            while (casino.Hit)
            {
                casino.AddCard(deck.GetCard());
                casinoAmount = casino.CalculateAmount();
            }
            casino.ShowCards();
            if (playerAmount > 21 && casinoAmount > 21)
            {
                Console.WriteLine("Dead heat.");
            }
            else if (playerAmount > 21)
            {
                Console.WriteLine("LOOSER!!! You have more than 21 points.");
            }
            else if (casinoAmount > 21)
            {
                Console.WriteLine("You are win!!! Casino has more 21 poits");
            }
            else
            {
                if (playerAmount > casinoAmount)
                {
                    Console.WriteLine("You are win!!!");
                }
                else if (playerAmount == casinoAmount)
                {
                    Console.WriteLine("Dead heat.");
                }
                else
                {
                    Console.WriteLine("Casino is win.");
                }
            }
            Console.ReadKey();
        }
Esempio n. 13
0
        public static Hand dealerHand = new Hand();                                                 //Creating dealers hand
        static void Main(string[] args)
        {
            Console.WriteLine("*****BLACKJACK*****");
            bool play = true;                                                                       //Preparing game properties

            do
            {
                AddingCardsToDeck();                                                                //Adding cards to deck
                PlayerStartingHand();                                                               //Adding players starting cards
                DealerStartingHand();                                                               //Adding dealers starting cards

                Console.WriteLine($"Your cards: {playerHand.CardsInHand()}");
                Console.WriteLine($"Total Value: {playerHand.HandValue()}");
                Console.WriteLine($"Your account balance: {balance}$");
                int betValue = AddingBet();                                                         //Accepting players bet

                bool game = true;                                                                   //Main game logic loop
                while (game == true)
                {
                    bool validInput = false;
                    while (validInput == false)                                                     //Checking if user input is valid. If user unput is invalid, the loop will continue until it's valid
                    {
                        Console.WriteLine($"Your cards: {playerHand.CardsInHand()}");               //Presenting cards in players hand
                        Console.WriteLine($"Total Value: {playerHand.HandValue()}");                //Presenting players hand value
                        NewLine();
                        Console.WriteLine($"Dealers cards: {dealerHand.CardsInHand()}");            //Presenting cards in dealers hand
                        Console.WriteLine($"Total Value: {dealerHand.HandValue()}");                //Presenting dealers hand value
                        NewLine();
                        Console.WriteLine($"Your bet: {betValue}$");                                //Players current bet
                        Console.WriteLine($"Your account balance: {balance-betValue}$");            //Players current balance

                        Menu();                                                                     //Print game Menu with possible choices
                        string decision = Console.ReadLine().Trim().ToLower();                      //getting user input
                        Console.Clear();

                        switch (decision)                                                           //Makes action, depending on users choice
                        {
                        //Hit
                        case "h":
                            validInput = true;
                            playerHand.hand.Add(deck.GetCard());                                    //Adding card to players deck
                            Console.WriteLine($"You got: {playerHand.LastCardInHand().Name}");      //Presenting players new card
                            if (playerHand.BustCheck() == true)                                     //Checking for Bust
                            {
                                Console.WriteLine($"You Busted!\nYou lost {betValue}$");
                                PrintResults();
                                balance -= betValue;
                                game     = false;
                                break;
                            }
                            break;

                        //Stay
                        case "s":
                            validInput = true;
                            game       = false;                                                     //Stoping game logic loop, because game ends after player decides to stay with his hand
                            DealerPlay();                                                           //Simulating Dealers "logic"
                            if (dealerHand.BustCheck() == true)                                     //Checking for dealers Bust
                            {
                                Console.WriteLine($"Dealer Busted!\nYou won {2*betValue}$");
                                balance += 2 * betValue;
                                PrintResults();
                                break;
                            }
                            ResultCheck(betValue);                                                  //Checking game result and comparing hands
                            break;
                        }
                    }
                }

                play = PlayAgain();                                                                 //Asking user for next deal
                Console.Clear();
            }while (play == true);
        }
Esempio n. 14
0
        public static void StartGame()
        {
            /* Tries to open the file "Stats" but will not write anything to it, should it exist.
             * If it doesn't exist, the file will be created and its contents set to "0" + "0".
             * This is only done once per start-up. */
            Stats stats = new Stats();

            stats.StatsToFile(-1);

            // Welcomes the player, allowing him to input his/her name.
            Console.WriteLine("Welcome to Black Jack! (v1.2)\nCreated by: Fredrik Andreasson\n");
            Console.Write("Please enter your name: ");
            string playername = Console.ReadLine();

            /* This string needs to be outside the do-while in order to be recognized at the very bottom.
             * It is used to restart the game and recreate all the needed objects from scratch.
             * Otherwise, we'd be left with an incomplete deck to start with. */
            string Regame;

            do
            {
                /* Clears the console from junk. Useless at first-time run, amazing when playing
                 * more than one round in a row. */
                Console.Clear();

                /* Creates necessary objects: The deck, the player and the dealer.
                 *
                 * NOTE: Previously the creation of the player and dealer objects were
                 * above the do-while. While this was perfectly fine, I wanted to allow players
                 * to restart new rounds without entering a new name every time.
                 * This didn't work as the object would not be created anew and would remember the old Hands
                 * of both players. This solution fixed that while still allowing the player to play several rounds
                 * without having to enter his/her name every time. */
                Deck   deck   = new Deck();
                Player player = new Player()
                {
                    Name = playername
                };
                Player dealer = new Player();

                /* Needed variables. PlayerSum and DealerSum are used to calculate the total of
                 * the hands of both the Player and the Dealer. CardName is used to print the proper name
                 * of chosen card into the console. (i.e. "Ace of Hearts", rather than "1 of Hearts") */
                int    PlayerSum = 0, DealerSum = 0;
                string CardName;

                /* Explanations of the game. Hit 'f' to continue, 's' to stay, 'y' to play again when the game asks,
                 * 'n' to stop playing and exit the game. The player can alse press 'q' at any time to view recorded stats. */
                Console.WriteLine("\nSit down at the table " + player.Name + " and let me quickly explain how to play.");
                Console.WriteLine("It's simple. Just press 'F' to draw more cards or 'S' to stay where you are.");
                Console.WriteLine("When the game is over, press 'Y' to play again or 'N' to stop playing.");
                Console.WriteLine("\nYou can press 'Q' at any time to view recorded\nstats between the player and dealer.\n");
                Console.WriteLine("Let's begin!\n");

                // Player gets his first card.
                Console.WriteLine("------------------------------\n Your first card is:\n");
                Card playercard = deck.GetCard();
                CardName = deck.GetCardName(playercard);

                /* Card gets printed out into the console and gets added to the hand,
                 * it then removes the card from the deck. It also checks if the card is an Ace, Jack, Queen or King
                 * and properly outputs the names rather than "1", "11", "12" or "13" of <suit> */
                Console.WriteLine("    " + CardName);
                player.AddCard(playercard);
                deck.deck.Remove(playercard);
                // Gets the sum of the player's hand.
                PlayerSum = player.GetValue();
                Console.WriteLine("\n Total of your hand: " + PlayerSum + "\n------------------------------");

                // Same for the dealer.
                Console.WriteLine("\n------------------------------\n The dealer's first card is:\n");
                Card dealercard = deck.GetCard();

                CardName = deck.GetCardName(dealercard);
                Console.WriteLine("    " + CardName);

                dealer.AddCard(dealercard);
                deck.deck.Remove(dealercard);
                DealerSum = dealer.GetValue();
                Console.WriteLine("\n Total of the dealer's hand: " + DealerSum + "\n------------------------------");

                // Player starts making the choices here.

                /* Using 'ConsoleKeyInfo' and 'Console.ReadKey()' allows the player to simple hit the button
                 * he/she would like to press without having to press 'enter' every time afterwards to confirm. */
                ConsoleKeyInfo Choice;
                do
                {
                    Choice = Console.ReadKey();

                    /* If the player hits 'f', he gets a new card. Game checks for the total of his hand
                     * and determines if the player has won through Black Jack, lost through busting
                     * or neither, in which the player can choose to draw again */
                    if (Choice.Key == ConsoleKey.F)
                    {
                        Console.WriteLine(" - YOU DRAW!");

                        playercard = deck.GetCard();
                        CardName   = deck.GetCardName(playercard);
                        Console.WriteLine("------------------------------\n You got:\n");
                        Console.WriteLine("    " + CardName);
                        player.AddCard(playercard);
                        deck.deck.Remove(playercard);

                        PlayerSum = player.GetValue();
                        Console.WriteLine("\n Total of your hand: " + PlayerSum + "\n------------------------------");
                        if (PlayerSum >= 22)
                        {
                            Console.WriteLine("------------------------------\nBUST! Your hand exceeded 21!\n------------------------------");
                            stats.StatsToFile(1);
                            break;
                        }
                        else if (PlayerSum == 21)
                        {
                            Console.WriteLine("------------------------------\nBLACKJACK! You win!\n------------------------------");
                            stats.StatsToFile(0);
                            break;
                        }
                    }

                    /* The player has pressed the 's' key. The dealer draws cards.
                     * The dealer will continue drawing until he has at least a total hand-value of 17.
                     * The dealer will automatically lose if he busts. */
                    else if (Choice.Key == ConsoleKey.S)
                    {
                        Console.WriteLine(" - YOU STAY! DEALER'S TURN!");
                        while (DealerSum < 17)
                        {
                            dealercard = deck.GetCard();
                            CardName   = deck.GetCardName(dealercard);

                            Console.WriteLine("------------------------------\n The dealer draws:\n");
                            Console.WriteLine("    " + CardName);

                            dealer.AddCard(dealercard);
                            deck.deck.Remove(dealercard);

                            DealerSum = dealer.GetValue();
                            Console.WriteLine("\n Total of the dealer's hand: " + DealerSum + "\n------------------------------");
                            if (DealerSum >= 22)
                            {
                                Console.WriteLine("------------------------------\nThe dealer busts! You WIN!\n------------------------------");
                                stats.StatsToFile(0);
                                break;
                            }
                        }

                        /* If neither the player nor the dealer has gotten an instant win or loss through
                         * the written code above, the game will check the difference in hand-values between
                         * the player and the dealer to determine who is the winner. */
                        if (PlayerSum > DealerSum)
                        {
                            Console.WriteLine("------------------------------\nYou have the higher hand! You WIN!\n------------------------------");
                            stats.StatsToFile(0);
                        }
                        else if (PlayerSum < DealerSum && DealerSum <= 21)
                        {
                            Console.WriteLine("------------------------------\nThe dealer has the higher hand! Aww, you LOSE!\n------------------------------");
                            stats.StatsToFile(1);
                        }
                        else if (PlayerSum == DealerSum)
                        {
                            Console.WriteLine("------------------------------\nYou and the dealer stopped at the same total! It's a DRAW!\n------------------------------");
                            stats.StatsToFile(-1);
                        }
                    }

                    // If the player presses 'Q', the stats (from a file) will be shown on screen.
                    else if (Choice.Key == ConsoleKey.Q)
                    {
                        stats.GetStats();
                    }
                } while (Choice.Key != ConsoleKey.S);

                // Want to play again?
                Console.WriteLine("Do you want to play again? (y)es or (n)o.");
                Console.WriteLine("(You can also check stats now by pressing 'Q'.");
                Regame = null;

                /* Usually I wouldn't use a "never-ending loop" such as this, but I felt
                 * the impact it might've had was too insignificant to worry about.
                 * The loop will end immediately if a valid key was pressed, and will continue
                 * to loop until such action occurs. */
                while (1 != 0)
                {
                    ConsoleKeyInfo Rematch = Console.ReadKey();
                    if (Rematch.Key == ConsoleKey.Y)
                    {
                        Regame = "yes";
                        break;
                    }
                    else if (Rematch.Key == ConsoleKey.N)
                    {
                        Regame = "no";
                        break;
                    }
                    else if (Rematch.Key == ConsoleKey.Q)
                    {
                        stats.GetStats();
                    }
                    else
                    {
                        Console.WriteLine("Invalid key pressed!");
                    }
                }
            } while (Regame == "yes");
        }