2016-07-31 67 views
1

我使用C#創建一個紙牌遊戲。我想爲我的卡片示例分配一個值:Ace(image)= 1;我想隨機選擇它。這裏是我的代碼:C#在圖片框中的隨機圖像,並分配值

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

您應該加載圖像到一個數組一次,然後從分配給pictureboxes,或者以前的圖像處置,如果有的話, – Plutonix

回答

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

然後,而不是在代碼中使用圖片框,使用此。

說實話,我喜歡封裝碼多一點,所以我更喜歡這樣的:

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, 
    ... 
    } 
+0

謝謝你,先生!如何分配一個值的形象?例如:我想要Ace(圖片)= 1? –

+0

@VyanAxel繼承自Picturebox,然後爲其添加一個int屬性。我將在回答中描述 –

0

雖然我沒有看到你的問題的實際問題,我想你想這樣做的更簡單的方法。

那麼首先,不創建Random每一個方法被調用時,使其成爲一個類級變量和初始化:目前,您使用的是switch決定

private static Random cards = new Random(); 

在兩個圖片框中顯示什麼。如果隨機數爲0,則放置這兩張卡片,如果數字爲1,則放置這兩張卡片......這表示從0到9的每個數字對應於兩個Bitmap s。

您可以使用字典將0到9映射到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方法降低。現在我們可以聲明我正在談論的數組。

這很簡單:

public static Tuple<Bitmap, Bitmap>[] CardCombinations => new[] { 
    new Tuple<Bitmap, Bitmap>(Properties.Resources.king_d, Properties.Resources.jack_s), 
    ... 
}; 

「但是,這仍然是冗長的!」你哭了。 Protip:您可以使用using static指令將位圖名稱縮短爲king_djack_s

using static SomeNamespace.Properties.Resources; 
+0

感謝您的回答,雖然我不熟悉這些單詞。嗯,如何分配圖像的價值?你能幫我先生嗎?謝謝你的回覆 –

+0

@VyanAxel當然我會幫你的!但是,在我能夠進一步解釋之前,您需要告訴我使用我提供的代碼和說明時遇到的問題! – Sweeper