繁体   English   中英

我 go 如何将另一个 Class 中的方法添加到我的 WindowsForms Class 中?

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

我正在创建一个二十一点游戏,并使用了来自 inte.net 的教程来达到这一点。 然而,我已经完成了教程,我已经将其他类的所有方法添加到将玩二十一点游戏的 class 中,但无法弄清楚如何添加这些方法。 我想知道如何将所有方法添加到 P1 Class go。

{
    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)
        {

        }
    }
}

在您的帖子中,您询问如何将其他类的所有方法添加到将玩 21 点游戏的 class 中

基本上,当您在MainForm中声明Deck class 之类的实例时,其所有成员都已“添加”(以某种方式),因为您可以使用声明的成员属性访问它们。 所以这是我们将在 MainForm 中做的第一件事。 我还会提到有时有staticconst成员,它们不需要实例来使用它们,而是您可以使用 class 名称。 您将在MainForm构造函数中看到这方面的示例,例如Card.Spades


这是您可以在此处克隆的工作示例的一小段,它显示了如何使用 static 方法和实例从主窗体调用这些类,以将五张牌洗牌并发给两名玩家:

截屏


设置UI卡“表”:

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;
    }

通过从“牌组”实例中出队来发牌。

    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));
    }

将卡片分配给显示它的 UI 元素。

    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;
        }
    }
}

此处显示过多代码可能会分散实际问题的注意力,但您可能希望克隆完整代码并设置断点以查看其工作原理。 (这不是二十一点游戏——我会把它留给你,这样我就不会带走你的乐趣。)。


使用以下简化类:

卡片

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}";
    }
}

甲板

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();
}

枚举

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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