我正在制作一个C#练习计划,涉及3个决斗者,每个人都有不同的准确度。他们轮流按预设顺序拍摄,直到其他2人死亡,然后重复10k次,每次都为胜利者增添一场胜利。我的问题是,由于某种原因,一旦在if语句之一上给出了true,那个dueler将获得所有10k的胜利。我认为这是随机课的一个问题,但直到上周我才开始学习C#。这也是我在这个网站上的第一篇文章。我经常使用它,但我以前从未问过,通常是其他人已经有过。
class MainClass
{
public static void Main(string[] args)
{
//sets up objects and the won boolean
bool won = false;
Random shot = new Random();
Duelist a = new Duelist();
Duelist b = new Duelist();
Duelist c = new Duelist();
//sets names
c.SetName("Charlie");
a.SetName("Aaron");
b.SetName("Bob");
//loops through 10k times
for (int i = 10000; i > 0; i--)
{
//resets won to false
won = false;
while (!won)
{
//Aarons turn
if (a.GetAlive())
{
//If Charlie is alive, shoot at him
if (c.GetAlive())
{
if (shot.Next(1, 4) == 1)
{
c.SetAlive(false);
}
}
//If bob is alive, shoot at him
else if (b.GetAlive())
{
if (shot.Next(1, 4) == 1)
{
b.SetAlive(false);
}
}
//if neither of them are alive, aaron wins, and end of while loop
else
{
a.AddWin();
won = true;
}
}
//Bobs turn
if (b.GetAlive())
{
if (c.GetAlive())
{
if (shot.Next(1, 3) == 1)
{
c.SetAlive(false);
}
}
else if (a.GetAlive())
{
if (shot.Next(1, 3) == 1)
{
a.SetAlive(false);
}
}
else
{
b.AddWin();
won = true;
}
}
//Charlies turn
if (c.GetAlive())
{
if (b.GetAlive())
{
b.SetAlive(false);
}
else if (a.GetAlive())
{
a.SetAlive(false);
}
else
{
c.AddWin();
won = true;
}
}
}
}
//prints results
Console.WriteLine(a.GetName() + ": " + a.GetWin());
Console.WriteLine(b.GetName() + ": " + b.GetWin());
Console.WriteLine(c.GetName() + ": " + c.GetWin());
Console.Read();
}
}
class Duelist
{
private string name;
private int wins;
private bool alive;
public Duelist()
{
name = "Name";
wins = 0;
alive = true;
}
public void SetName(string n)
{
name = n;
}
public string GetName()
{
return name;
}
public void AddWin()
{
wins++;
}
public int GetWin()
{
return wins;
}
public void SetAlive(bool al)
{
alive = al;
}
public bool GetAlive()
{
return alive;
}
}
答案 0 :(得分:3)
你忘了在每次迭代中设置每个角色。
//resets won to false
a.SetAlive(true);
b.SetAlive(true);
c.SetAlive(true);
won = false;