如何正确使用带数组的循环?

时间:2018-02-21 04:00:21

标签: c# xna monogame

我正在尝试创建一个创建好收藏品和坏收藏品的程序,角色必须找到它们。

初​​始化:

{
    int width = GraphicsDevice.Viewport.Width;

    int height = GraphicsDevice.Viewport.Height;
    int xcoord = rnd.Next(width - 50);
    int ycoord = rnd.Next(height - 50);
    this.goodCollectibles = new Sprite[gC];
    this.badCollectibles = new Sprite[bC];
    for (int index = 0; index < gC; index++)
      goodCollectibles[index] = new Sprite(this, xcoord, ycoord, 50, 50, "gC");

    for (int index = 0; index < bC; index++)
      badCollectibles[index] = new Sprite(this, xcoord, ycoord, 50, 50, "bC");

    char1 = new ControllableSprite(this, xcoord, ycoord, 100, 100, "char1");
    char2 = new ControllableSprite(this, xcoord, ycoord, 100, 100, "char2");
}

如果你赢了游戏,抽取(通过收集更多好的收藏品/不太糟糕的收藏品,你会变成蓝色,如果你打成黄色,如果你输了红色)

{
   spriteBatch.Begin();

   for (int index = 0; index < gC; index++)
      goodCollectibles[index].Draw(spriteBatch);
   for (int index = 0; index < bC; index++)
      badCollectibles[index].Draw(spriteBatch);

   if (char1.score > char2.score && counter > 1800)
   {
      char1.scoreColor = Color.Blue;
      char2.scoreColor = Color.Red;
   }
   else if (char2.score > char1.score && counter > 1800)
   {
      char2.scoreColor = Color.Blue;
      char1.scoreColor = Color.Red;
   }
   else if (char1.score == char2.score && counter > 1800)
   {
      char1.scoreColor = Color.Yellow;
      char2.scoreColor = Color.Yellow;
   }
}

1 个答案:

答案 0 :(得分:1)

你的for-loop和数组连接没什么问题。

您的代码:

for (int index = 0; index < gC; index++)
      goodCollectibles[index] = new Sprite(this, xcoord, ycoord, 50, 50, "gC");

看起来已经足够让for循环在数组中正常工作了。

但是,我认为问题出在你的rnd.Next上,因为你已经在for-loop之前使用了它,因此它不会进行新的随机抛出。

相反,将您的rnd.Next语句放在for循环中。像这样:

for (int index = 0; index < gC; index++)
{
      goodCollectibles[index] = new Sprite(this, rnd.Next(width - 50), rnd.Next(height - 50), 50, 50, "gC");
}

这样它应该有用。