【发布时间】:2015-01-31 20:28:03
【问题描述】:
我正在开发一个 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 张普通牌和 2 张小丑)。 useableNumbers 列表中的数字代表该文件夹中的图像名称。选择图像后,我想使用useableNumbers.RemoveAt(i); 从列表中删除该图像的名称。虽然我确实收到了“游戏已结束”的消息,但我也遇到了上述问题。
我觉得useableNumbers.RemoveAt(i); 不会更改列表的索引,所以当“10”被删除时,它会保留索引 11,而不是将所有值向下移动一个,如果你知道的话我的意思。
我也尝试将图像存储在列表中,但也无法使其正常工作,这就是我这样做的原因。对 C# 来说还是新手,所以也许有更好的方法。
如何解决从列表中删除的问题,这样我就不会两次或多次获得相同的图像,或者根本没有图像?
【问题讨论】: