Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Threading;
- namespace Peldak
- {
- public class Blackjack
- {
- public struct Card
- {
- public string name;
- public int value;
- public Card(string name, int value)
- {
- this.name = name;
- this.value = value;
- }
- }
- Card[] cards = new Card[] {
- new Card("2", 2),
- new Card("3", 3),
- new Card("4", 4),
- new Card("5", 5),
- new Card("6", 6),
- new Card("7", 7),
- new Card("8", 8),
- new Card("9", 9),
- new Card("10", 10),
- new Card("J", 10),
- new Card("Q", 10),
- new Card("K", 10),
- new Card("A", 11)
- };
- Random rnd = new Random();
- List<Card> cardsInHand = new List<Card>();
- List<Card> cardsInDealerHand = new List<Card>();
- public void run()
- {
- deal();
- printHand("Cards in dealer hand:", cardsInDealerHand);
- while (true)
- {
- int valueInHand = printHand("Cards in hand:", cardsInHand);
- if (valueInHand > 21)
- {
- Console.WriteLine("GAME OVER - You lost!");
- return;
- }
- bool needMoreCards = askPlayer();
- if (needMoreCards)
- {
- addCard(cardsInHand);
- }
- else
- {
- printHand("Cards in dealer hand:", cardsInDealerHand);
- while (true)
- {
- Thread.Sleep(1500);
- addCard(cardsInDealerHand);
- int valueInDealerHand = printHand("Cards in dealer hand:", cardsInDealerHand);
- if (valueInDealerHand > 21)
- {
- Console.WriteLine("GAME OVER - You WON!");
- return;
- }
- if (valueInDealerHand >= valueInHand)
- {
- Console.WriteLine("GAME OVER - You lost!");
- return;
- }
- }
- }
- }
- }
- void deal()
- {
- addCard(cardsInHand);
- addCard(cardsInHand);
- addCard(cardsInDealerHand);
- }
- void addCard(List<Card> hand)
- {
- int i = rnd.Next(cards.Length);
- Card c = cards[i];
- hand.Add(c);
- }
- int printHand(string message, List<Card> hand)
- {
- Console.Write(message);
- int sum = 0;
- for (int i = 0; i < hand.Count; i++)
- {
- Console.Write(" " + hand[i].name);
- sum += hand[i].value;
- }
- if ((sum == 22) && (hand.Count == 2))
- {
- sum = 21;
- }
- Console.WriteLine(" (" + sum + ")");
- return sum;
- }
- bool askPlayer()
- {
- Console.Write("Need more cards? (Y/N) ");
- string answer = Console.ReadLine();
- if ((answer == "Y") || (answer == "y"))
- {
- return true;
- }
- return false;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement