我正在使用 C# 和 WPF 制作一个简单的太空探索游戏。我有一个错误,尽管我尽了最大努力来修复它,但它仍然存在。我有一个恒星类,其构造函数将通过 Random 类随机生成大量具有唯一名称的行星。问题是,尽管从包含它们的列表中删除了使用过的名称,但组合框中仍会出现重复的名称。
构造函数:
`public Star(List<Planet> _planetlist)
{
int range = _planetlist.Count;
int amountOfPlanets = random.Next(1, 6);
List<String> usableNames = new List<String>(PlanetNames);
for (int i = 0; i != amountOfPlanets; i++)
{
Planet planet = _planetlist[random.Next(0, range)];
planet.name = usableNames[random.Next(0, usableNames.Count)];
usableNames.Remove(planet.name);
systemPlanets.Add(planet);
}
}`
由于随机性的本质,这种情况不会在每次运行程序时发生,但表明代码无法正常工作。
我尝试了各种方法来尝试修复该错误。显示的解决方案很旧并且不起作用:
`public Star(List<Planet> _planetlist)
{
int range = _planetlist.Count - 1; // range stores the amount of planets within the passed planetList parameter
int totalPlanets = random.Next(1, 6); // The amount of planets within the system can range from 1 -> 6
int planetPointer; // Not initalized yet, but will store a random number from 0 to the length of the passed planet list. This is used to select a random planet from the planetlist among other uses.
int iteration = 0;
while (iteration < totalPlanets)
{
planetPointer = random.Next(0, range);
Planet planet = _planetlist[planetPointer]; // Random planet from the planet list is selected and passed to the Planet varible.
planet.Name = planet.PlanetNames[planetPointer]; // Random name is selected for the planet.
systemplanets.Add(planet);
for (int iterator = 0; iterator <= totalPlanets; iterator++) // This for loop is used to find if the current planets name is identical to other planets in the system.
{
if (planetlist.Count == 0)
{
break;
}
else if (systemplanets[iterator].Name == planet.Name)
{
planet.Name = planet.PlanetNames[random.Next(0, planet.PlanetNames.Count)];
iterator = 0;
}
}
iteration++;
}
}`
这是用每个行星名称填充组合框的代码部分:
`private void buttonTravel_Click(object sender, RoutedEventArgs e)
{
String uniAgeString = LabelUniAge.Content.ToString();
ComboBoxStar.Items.Clear();
ComboBoxPlanet.Items.Clear();
if (ulong.TryParse(uniAgeString, out ulong convertedAge) == true)
{
universe.ageUniverse(convertedAge);
}
else
{
throw new Exception();
}
LabelUniAge.Content = universe.universeage;
Star star = new Star(planetList);
foreach (Planet planet in star.SystemPlanets)
{
ComboBoxPlanet.Items.Add(planet.name);
}
}`
如果您需要访问整个项目,可以在这里找到:https://github.com/David-s2005/SpaceGame
解释为什么这不起作用将不胜感激!谢谢您的宝贵时间。
Planet planet = _planetlist[random.Next(0, range)];
可能会多次返回相同的行星对象。
然后行星物体上的最后一个
planet.Name = ...
将覆盖之前设置的名称。