2016-07-19 8 views
-2

私はビジュアルスタジオコミュニティ2015を使用して、2つのダイスをロールするフォームベースのプログラムを作成しています。私が得る乱数に応じて絵を変える必要があります。メソッドは、ループを使用してC#を呼び出します。

私はこれを行うことができる方法がある:

Random num = new Random(); 
int dice = num.Next(1,7); 

if (dice == 1)  { 
    pictureBox.Image = proj08.Properties.Resources._1; 
} else if (dice == 2) { 
    pictureBox.Image = proj08.Properties.Resources._2; 
} else if (dice == 3) { 
    pictureBox.Image = proj08.Properties.Resources._3; 
} else if (dice == 4) { 
    pictureBox.Image = proj08.Properties.Resources._4; 
} else if (dice == 5) { 
    pictureBox.Image = proj08.Properties.Resources._5; 
} else if (dice == 6) { 
    pictureBox.Image = proj08.Properties.Resources._6; } 

これは完璧に動作し、私がしたいだけで何行いますが、それは非常に厄介なコードです。私は何かをすることによってそれをきれいにしたい:

Random num = new Random(); 
int dice = num.Next(1,7); 
pictureBox.Image = proj08.Properties.Resources._dice; 

しかし、それは動作しません。 ピクチャボックスがpictureBox1またはpictureBox2であっても、同じコードを使用したいので、どちらのダイスにも使用できます。

+0

この質問は、ダイスについてよりも多くのリソースを参照することについてです。少なくとも次のようなより適切なものを複製してください。http://stackoverflow.com/questions/1190729/vb-net-dynamically-select-image-from-my-resources – Crowcoder

答えて

0

あなたはイメージのリストを持つことができます。

List<Image> images = new List<Image>() 
{ 
    proj08.Properties.Resources._1, 
    proj08.Properties.Resources._2, 
    proj08.Properties.Resources._3, 
    proj08.Properties.Resources._4, 
    proj08.Properties.Resources._5, 
    proj08.Properties.Resources._6 
}; 

Random num = new Random(); 
int dice = num.Next(1, images.Count + 1); 
pictureBox.Image = images[dice - 1]; // list starts from 0 

これは、私は考えることができる最もストレートフォワードエレガントな方法です。

複数のピクチャボックスの場合、ピクチャボックスを引数として渡してその中にイメージプロパティを設定するメソッドを作成できます。

関連する問題