1

作为要求的一部分,我正在尝试修改我的代码,以便它的行为方式与我的原始代码相同,但我似乎无法弄清楚。

我已经做了一些修改,它编译得很好但是我不能让堆栈类像列表一样运行:

清单(原件):

private List<Gem> gems = new List<Gem>();
private List<Enemy> enemies = new List<Enemy>();

private void UpdateGems(GameTime gameTime)
{
    for (int i = 0; i < gems.Count; ++i)
    {
        Gem gem = gems[i];
        gem.Update(gameTime);

        if (gem.BoundingCircle.Intersects(Player.BoundingRectangle))
        {
            gems.RemoveAt(i--);
            OnGemCollected(gem, Player);
        }
    }
}

堆栈(我的修改版本):

private Stack<Gem> gems = new Stack<Gem>();
private Stack<Enemy> enemies = new Stack<Enemy>();

/// <summary>
/// Animates each gem and checks to allows the player to collect them.
/// </summary>
private void UpdateGems(GameTime gameTime)
{
    Gem[] array = gems.ToArray();

    for (int i = 0; i < gems.Count; ++i)
    {
        Gem gem = array[i];
        gem.Update(gameTime);
        if (gem.BoundingCircle.Intersects(Player.BoundingRectangle))
        {
            gems.Pop();
            OnGemCollected(gem, Player);
        }
    }
}
4

1 回答 1

1

我能想到的最好的:

private Stack<Gem> gems = new Stack<Gem>();
private Stack<Enemy> enemies = new Stack<Enemy>();

/// <summary>
/// Animates each gem and checks to allows the player to collect them.
/// </summary>
private void UpdateGems(GameTime gameTime)
{
    var newGems = new Stack<Gem>(this.gems.Count);

    while (this.gems.Count > 0)    
    {
        var gem = this.gems.Pop();
        gem.Update(gameTime);

        if (gem.BoundingCircle.Intersects(Player.BoundingRectangle))
        {
            OnGemCollected(gem, Player);
        }
        else
        {
            newGems.Push(gem);
        }
    }

    this.gems = newGems;
}

不过也没多大意义。

于 2013-05-18T17:34:09.877 回答