简体   繁体   中英

How would I go about adding methods from another Class into My WindowsForms Class?

I am creating a blackjack game and have used a tutorial from the inte.net to get to this point. However, I have completed the tutorial and I have been left to add all the methods from other classes into the class where the blackjack game will be played and cannot figure out how to add the methods. I Would like to know how i would go about adding all the methods to the P1 Class.

{
    public class Card 
    {
        public enum CardValue
        {
            Ace = 1,
            Two = 2,
            Three = 3,
            Four = 4,
            Five = 5,
            Six = 6,
            Seven = 7,
            Eight = 8,
            Nine = 9,
            Ten = 10,
            Jack = 11,
            Queen = 12,
            King = 13
        }
        public enum CardSuit
        {
            Hearts = 1,
            Spades = 2,
            Clubs = 3,
            Diamonds = 4
        }
        Image image;
        CardValue cardValue;
        CardSuit suit;

        public Image Image
        {
            get
            {
                return this.Image;
            }
        }

        public CardValue Value
        {
            get
            {
                return this.cardValue;
            }
            set
            {
                this.cardValue = value;
                GetImage();
            }
        }

        public CardSuit Suit
        {
            get
            {
                return this.suit;
            }
            set
            {
                this.suit = value;
                GetImage();
            }
        }
        public Card()
        {
            cardValue = 0;
            suit = 0;
            image = null;

        }

        private void GetImage()
        {
            if (this.Suit != 0 && this.Value != 0)
            {
                int xAxis = 0;
                int yAxis = 0;
                int height = 97;
                int width = 73;

                switch (this.Suit)
                {
                    case CardSuit.Hearts:
                        yAxis = 196;
                        break;
                    case CardSuit.Spades:
                        yAxis = 98;
                        break;
                    case CardSuit.Clubs:
                        yAxis = 0;
                        break;
                    case CardSuit.Diamonds:
                        yAxis = 294;
                        break;
                }
                xAxis = width * ((int)this.Value - 1);

                Bitmap src = Resources.cards;
                Bitmap img = new Bitmap(width, height);
                Graphics gr = Graphics.FromImage(img);
                gr.DrawImage(src, new Rectangle(0, 0, width, height), new Rectangle(xAxis, yAxis, width, height), GraphicsUnit.Pixel);
                gr.Dispose();
                this.image = img;
            }
        }        
    }
    
}

 
{
    public class deck
    {
        private List<Card> cards;

        public List<Card> Cards
        {
            get { return cards; }
            set { Cards = value; }
        }

        public deck()
        {
            Cards = new List<Card>();
            ShuffleNewDeck();

        }

        public void ShuffleNewDeck()
        {
            cards.Clear();
            for (int i = 1; i < 5; i++)
            {
                for (int f = 1; f < 14; f++)
                {
                    Card card = new Card();
                    card.Value = (Card.CardValue)f;
                    card.Suit = (Card.CardSuit)i;
                }
            }
            Random r = new Random();
            cards = cards.OrderBy(x => r.Next()).ToList();
        }


        public Card DrawCard(Hand hand)
        {
            Card drawn = cards[cards.Count - 1];
            cards.Remove(drawn);
            hand.Cards.Add(drawn);
            return drawn;
        }

        [Serializable]
        internal class DeckException : Exception
        {
            public DeckException()
            {
                
            }

            public DeckException(string message) : base(message)
            {
            }

            public DeckException(string message, Exception innerException) : base(message, innerException)
            {
            }
        }
    }
}
{
    public class Hand
    {
        private List<Card> cards;

        public List<Card> Cards
        {
            get { return cards; }
        }

        public Hand(int startingHand, deck deck)
        {
            if (deck == null)
                MessageBox.Show("Deck Unavailable");
            else if (deck.Cards.Count == 0)
                MessageBox.Show("No More Cards to Show");
            else
            {
                cards = new List<Card>();
                for (int i = 0; i < startingHand; i++)
                {
                    deck.DrawCard(this);
                }
            }
        }
        public void AddValue (Card drw, ref int curScore)
        {
            if (drw.Value == CardValue.Ace)
            {
                if (curScore <= 10)
                {
                    curScore += 11;
                }
                else
                {
                    curScore += 1;
                }
            }
            else if (drw.Value == CardValue.Jack || drw.Value == CardValue.Queen || drw.Value == CardValue.King)
            {
                curScore += 10;
            }
            else
            {
                curScore += (int)drw.Value;
            }
        }
    }
}


// This is where I would enter the methods to run them in my windows forms 
{
    public partial class P1 : Form 
    {
        private readonly int StartingHand = 2;
        private readonly int MaxCards = 5;
        PictureBox p;
        PictureBox q;
        deck deck;
        Hand player;
        Hand computer;
        int computerSum;
        int playerSum;
        public P1()
        {
            InitializeComponent();
        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void P1_Load(object sender, EventArgs e)
        {

        }

        private void resetGameToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
        }

        private void clearTableToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void requestScoreToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void BtnStick_Click(object sender, EventArgs e)
        {
            
        }

        private void BtnTwist_Click(object sender, EventArgs e)
        {

        }
    }
}

In your post you ask how to add all the methods from other classes into the class where the blackjack game will be played .

Basically, when you declare an instance of something like the Deck class in your MainForm then all of its members have been "added" (in a manner of speaking) because you can access them using the member property that you declared. So that's the first thing we'll do in the MainForm. I will also mention that sometimes there are static or const members and these don't require an instance to use them, rather you would use the class name instead. You'll see examples of this in the MainForm constructor like Card.Spades .


Here's a small snippet of a working sample you can clone here that shows how the classes would be called from the main form using static methods and instances to shuffle and deal five cards to two players:

截屏


Set up the UI card "table":

public partial class MainForm : Form
{
    // Make instance of the card deck using the `Deck` class
    Deck DeckInstance = new Deck();
    public MainForm()
    {
        InitializeComponent();
        Text = "Card Game";
        tableLayoutCards.Font = new Font("Sergoe UI Symbol", 9);
        // Static or const members of a class do not require an
        // instance. Use the class name to reference these members.
        labelHandA1.Text = $"10 {Card.Spades}";
        labelHandA2.Text = $"J {Card.Spades}";
        labelHandA3.Text = $"Q {Card.Spades}";
        labelHandA4.Text = $"K {Card.Spades}";
        labelHandA5.Text = $"A {Card.Spades}";
        labelHandB1.Text = $"10 {Card.Hearts}";
        labelHandB2.Text = $"J {Card.Hearts}";
        labelHandB3.Text = $"Q {Card.Hearts}";
        labelHandB4.Text = $"K {Card.Hearts}";
        labelHandB5.Text = $"A {Card.Hearts}";
        buttonDeal.Click += dealTheCards;
    }

Deal the cards by dequeuing them from a "deck" instance.

    private async void dealTheCards(object sender, EventArgs e)
    {
        buttonDeal.Refresh(); UseWaitCursor = true;
        // When a non-UI task might take some time, run it on a Task.
        await DeckInstance.Shuffle();
        // Now we need the instance of the Desk to get the
        // cards one-by-one so use the property we declared.
        setCard(labelHandA1, DeckInstance.Dequeue());
        setCard(labelHandA2, DeckInstance.Dequeue());
        setCard(labelHandA3, DeckInstance.Dequeue());
        setCard(labelHandA4, DeckInstance.Dequeue());
        setCard(labelHandA5, DeckInstance.Dequeue());
        setCard(labelHandB1, DeckInstance.Dequeue());
        setCard(labelHandB2, DeckInstance.Dequeue());
        setCard(labelHandB3, DeckInstance.Dequeue());
        setCard(labelHandB4, DeckInstance.Dequeue());
        setCard(labelHandB5, DeckInstance.Dequeue());
        UseWaitCursor = false;
        // Dum hack to make sure the cursor redraws.
        Cursor.Position = Point.Add(Cursor.Position, new Size(1,1));
    }

Assign a card to the UI element that displays it.

    private void setCard(Label label, Card card)
    {
        label.Text = card.ToString();
        switch (card.CardSuit)
        {
            case CardSuit.Hearts:
            case CardSuit.Diamonds:
                label.ForeColor = Color.Red;
                break;
            case CardSuit.Spades:
            case CardSuit.Clubs:
                label.ForeColor = Color.Black;
                break;
        }
    }
}

Showing too much code here might distract from the actual question, but you might want to clone the full code and set breakpoints to see how it works. (It's not a Blackjack game - I'll leave that to you so I don't take away your fun.).


Uses the following simplified classes:

Card

public class Card
{
    // https://office-watch.com/2021/playing-card-suits-%E2%99%A0%E2%99%A5%E2%99%A6%E2%99%A3-in-word-excel-powerpoint-and-outlook/#:~:text=Insert%20%7C%20Symbols%20%7C%20Symbol%20and%20look,into%20the%20character%20code%20box.
    public const string Hearts = "\u2665";
    public const string Spades = "\u2660";
    public const string Clubs = "\u2663";
    public const string Diamonds = "\u2666";
    public CardValue CardValue { get; set; }
    public CardSuit CardSuit { get; set; }
    public override string ToString()
    {
        string value, suit = null;
        switch (CardValue)
        {
            case CardValue.Ace: value = "A"; break;
            case CardValue.Jack: value = "J"; break;
            case CardValue.Queen:  value = "Q"; break;
            case CardValue.King: value = "K"; break;
            default: value = $"{(int)CardValue}"; break;
        }
        switch (CardSuit)
        {
            case CardSuit.Hearts: suit = Hearts; break;
            case CardSuit.Spades: suit = Spades; break;
            case CardSuit.Clubs: suit = Clubs; break;
            case CardSuit.Diamonds: suit = Diamonds ; break;
        }
        return $"{value} {suit}";
    }
}

Deck

public class Deck : Queue<Card>
{
    // Instantiate Random ONE time (not EVERY time).
    private readonly Random _rando = new Random();
    private readonly Card[] _unshuffled;
    public Deck()
    {
        List<Card> tmp = new List<Card>();
        foreach(CardValue value in Enum.GetValues(typeof(CardValue)))
        {
            foreach (CardSuit suit in Enum.GetValues(typeof(CardSuit)))
            {
                tmp.Add(new Card { CardValue = value, CardSuit = suit });
            }
        }
        _unshuffled = tmp.ToArray();
    }
    public async Task Shuffle()
    {
        Clear();
        List<int> sequence = Enumerable.Range(0, 52).ToList();
        while (sequence.Count != 0)
        {
            // Choose a unique card index from the sequence at
            // random based on the number of ints that remain.
            int randomIndexInSequence = _rando.Next(0, sequence.Count());
            int cardNumberOutOfOf52 = sequence[randomIndexInSequence];
            Enqueue(_unshuffled[cardNumberOutOfOf52]);
            sequence.RemoveAt(randomIndexInSequence);
        }
        // Spin a wait cursor as a visual indicator that "something is happening".
        await Task.Delay(TimeSpan.FromMilliseconds(500)); 
    }
    public Card GetNext() => Dequeue();
}

Enums

public enum CardValue
{
    Ace = 1,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
    Ten,
    Jack,
    Queen,
    King,
}
public enum CardSuit
{
    Hearts,
    Spades,
    Clubs,
    Diamonds,
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM