C#随机图像在图片框中并分配值

时间:2016-07-31 09:41:13

标签: c#

我正在使用C#创建纸牌游戏。我想为我的卡片例子分配一个值:Ace(image)= 1;而我想随便它。这是我的代码:

 private void button1_Click(object sender, EventArgs e)
        {
            Random cards = new Random();
            card = cards.Next(0, 9);
            switch (card)
            {
                case 0:
                    pictureBox1.Image = Properties.Resources.king_d;
                    pictureBox2.Image = Properties.Resources.jack_s;

                    break;

                case 1:
                    pictureBox1.Image = Properties.Resources.ace_c;
                    pictureBox2.Image = Properties.Resources.ten_d;

                    break;
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

新随机出来的方法。你可以从一个单独的类(read this)中获取它,或者为了简单起见,如果你在windows应用程序中使它像这样静态:

static Random cards = new Random();
private void button1_Click(object sender, EventArgs e)

    {

        card = cards.Next(0, 9);
        switch (card)
        {
            case 0:
                pictureBox1.Image = Properties.Resources.king_d;
                pictureBox2.Image = Properties.Resources.jack_s;

                break;

            case 1:
                pictureBox1.Image = Properties.Resources.ace_c;
                pictureBox2.Image = Properties.Resources.ten_d;

                break;
        }
    }
}

<强>更新 拥有包含值,图片等的卡片的最佳方法是为此创建一个新类。由于PictureBox已经拥有您需要的大多数属性和行为,我建议使用它。

代码必须是这样的:

   Public Class MyCard:PictureBox
    {
      public int GamePoint {get;set;}
    }

然后,不要在代码中使用PictureBox,而是使用它。

老实说,我喜欢将代码封装得更多,所以我更喜欢这个:

   Public Class MyCard:PictureBox
    {
      public CardType CardType {set;get;}
      public int GamePoint {get{ return (int)this.CardType;  }}
      public MyCard(CardType _cardType)
      {
       CardType = _cardType;
        }
    }

    enum CardType
    { Ace=1,
    King=2,
    ...
    }

答案 1 :(得分:0)

虽然我在你的问题中没有看到实际问题,但我认为你想以更简单的方式做到这一点。

首先,每次调用方法时都不要创建http://companyName1.mycompany.com responce to client: "hello aaa companyName1 ..." http://companyName2.mycompany.com responce to client: "hello bbb companyName2 ..." http://companyName3.mycompany.com responce to client: "hello ccc companyName3 ..." ,使其成为类级变量并初始化它:

Random

目前,您正在使用private static Random cards = new Random(); 来决定在两个图片框中显示的内容。如果随机数为0,则将这两张卡放入,如果数字为1,则将这两张卡放入......这意味着0到9之间的每个数字对应两个switch s。

您可以使用字典将0到9映射到Bitmap,但我认为最好使用数组。

您基本上需要做的是声明一个存储Tuple<Bitmap, Bitmap>的数组。我们称之为Tuple<Bitmap, Bitmap>。我建议你把这个数组放在一个名为CardCombinations的实用程序类中。然后,您可以这样做:

CardUtility

正如您所看到的,这大大减少了card = cards.Next(0, 9); pictureBox1.Image = CardUtility.CardCombinations[card].Item1; pictureBox2.Image = CardUtility.CardCombinations[card].Item2; 方法中的代码。现在我们可以声明我正在讨论的数组。

这很简单:

button1_Click

“但那仍然很冗长!”你哭了Protip:您可以使用public static Tuple<Bitmap, Bitmap>[] CardCombinations => new[] { new Tuple<Bitmap, Bitmap>(Properties.Resources.king_d, Properties.Resources.jack_s), ... }; 指令将位图名称缩短为using staticking_d

jack_s
相关问题