我正在開發一個C#紙牌遊戲,我希望在點擊按鈕時隨機選擇圖像。一旦卡片被選中,它必須顯示給用戶,並且必須發生一些事情,因此不能再次選擇卡片。我得到了第一部分,隨機圖像被選中並顯示給用戶,但我無法完成,因此無法再次選擇它。有時會多次挑選一張名片,有時候根本沒有選擇圖片,我得到錯誤圖片。這是迄今爲止的代碼。從按鈕單擊文件夾中選擇隨機,獨特的圖像
public partial class Form1 : Form
{
private List<int> useableNumbers;
public Form1()
{
InitializeComponent();
// Creates a list of numbers (card names) that can be chosen from
useableNumbers = new List<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54};
settings = new Settings();
}
private void btnDrawCard_Click(object sender, EventArgs e)
{
this.setImage();
}
private void setImage()
{
// Checks if there are still numbers left in the List
if (useableNumbers.Count() == 0)
{
MessageBox.Show("The game has ended");
Application.Exit();
}
else
{
Random r = new Random();
int i = r.Next(useableNumbers.Count());
// Looks for the path the executable is in
string path = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + @"\images\";
// Looks up the image in the images folder, with the name picked by the Random class and with the extension .png
string image = path + i + ".png";
// Sets the image in the pictureBox as the image looked up
pictureBox1.ImageLocation = image;
// Removes the selected image from the List so it can't be used again
useableNumbers.RemoveAt(i);
}
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
{
settings.Show();
}
澄清一點;我在與可執行文件相同的文件夾中有一個名爲'images'的文件夾。在該文件夾內,有54個圖像,分別命名爲'1'到'54'(52張普通卡和兩個笑臉)。 useableNumbers
列表中的數字表示該文件夾內的圖像名稱。選擇圖像時,我想從列表中刪除該圖像的名稱,其中包含useableNumbers.RemoveAt(i);
。儘管我確實收到了「遊戲已經結束」的信息,但我也遇到了上述問題。
我覺得useableNumbers.RemoveAt(i);
不會改變列表的索引,所以當'10'被刪除時,它將保持索引爲11而不是將所有值向下移動一個,如果你知道什麼我的意思是。
我也嘗試將圖像存儲在列表中,但無法讓它工作,所以這就是爲什麼我這樣做。對C#來說還是新手,所以也許有更好的方法來實現它。
如何修復從列表中刪除,所以我沒有得到相同的圖像兩次或更多,或根本沒有圖像?
可能的重複[添加圖像到數組,隨機選擇一個並從數組中刪除](http://stackoverflow.com/questions/28240593/add-images-to-array-pick-one-at-random-並從數組中刪除) – Adrian 2015-01-31 22:34:38