我正在开发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);
不会改变List的索引,所以当说“ 10”被删除时,如果您知道我的意思,它将保持11的索引,而不是将所有值都下移一个。
我也尝试过将图像存储在列表中,但也无法使其正常工作,所以这就是我这样做的原因。对于C#来说仍然是新手,所以也许有更好的方法可以做到这一点。
如何解决从列表中删除的问题,所以我不会获得相同的图像两次或更多次,或者根本没有图像?
取而代之的是,它会得到一个介于0和可用数字的当前大小之间的随机数,
int i = r.Next(useableNumbers.Count());
我会这样做,
int i = useableNumbers[r.Next(useableNumbers.Count())];
因此,它从剩余的可用数字之一中选择,而不是当前的大小。目前您可以复制,因为您只是在缩小要选择的数字的范围-开始时是从零到53,但是经过一半的操作,您将范围缩小到一半,并且复制的可能性更大。最后,您肯定会得到1。该范围不应更改,您始终希望使用1-54的随机数,而不是已经选择的一个。因此,通过这种新方法,您可以在列表中获取随机索引以检索值,而不仅仅是获取随机索引并将其作为您的值。
与此类似,
useableNumbers.RemoveAt(i);
做这个,
useableNumbers.RemoveAt(useableNumbers.IndexOf(i));
然后它将从列表中删除该数字,而不是列表中该位置的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句