【问题标题】:For loop that progressively adds more objects to List()For 循环逐渐将更多对象添加到 List()
【发布时间】:2016-03-06 19:20:57
【问题描述】:

我很难找到一种方法来在我的 for 循环中创建一个方程式,该方程式将根据角色所在的级别在列表 collectibleList 中生成许多对象。就像现在一样,我的列表每个级别只创建一个collectible。我猜这是因为i < currentLevel 绑定。但我不知道我应该应该使用什么样的绑定,或者如何在等式中实现i,以便可以根据currentLevel将更多collectibles添加到我的列表中。

    // Set up each level the player encounters
    public void NextLevel()
    {
        collectibleList.Clear();
        currentLevel++;
        timer = 10;
        player.LevelScore = 0;
        player.Position = new Rectangle(GraphicsDevice.Viewport.Width/2, GraphicsDevice.Viewport.Height/2, player.Position.Width, player.Position.Height);

        // Random number generator that will help generate a random position of the collectible sprite
        Random rng = new Random();
        for (int i = 0; i < currentLevel; i++)
        {
            Collectible collectible = new Collectible(rng.Next(0, GraphicsDevice.Viewport.Width), rng.Next(0, GraphicsDevice.Viewport.Height), 70, 91, true);
            collectible.ObjectSprite = collectibleSprite;
            collectibleList.Add(collectible);
        }
    }

【问题讨论】:

  • “创建公式”是什么意思?每个级别你想要多少个对象?计算您想要的数字,将其存储在变量中。然后在 for 循环中使用该变量而不是 currentLevel
  • 我同意@Blorgbeard:问题/任务定义模糊,问题需要澄清。谢谢和问候,
  • @Blorgbeard 我想我正在寻找一个依赖于i 的方程式,以便每个级别都有更多的收藏品,具体取决于级别。像collectibleList.Add(collectible + 2i) 之类的,但显然这是无效的
  • 我还是无法理解你的问题。 @Blorgbeard 的方法怎么样?
  • 据我所知,每个级别当前都有更多的收藏品,具体取决于级别。每个级别一个。更多关卡 = 更多收藏品。如果你想要不同的等式,请将 i &lt; currentLevel 替换为 i &lt; currentLevel * 4i &lt; Math.Pow(currentLevel, 2) 或其他任何内容。

标签: c# list for-loop monogame


【解决方案1】:

由于您基于 currentLevel(一次一个)进行迭代,您将在列表中的每个级别获得一个可收藏条目。

您需要确定每次迭代添加多少收藏品的另一个因素 - 然后您可以将内部循环放置在主循环中,以便在每个级别生成任意数量的收藏品。

即 2 个收藏品用于 1 级,5 个收藏品用于 2 级等。

【讨论】:

    【解决方案2】:

    您正在寻找一个好的递增整数函数,对吗?有很多选项可供选择。

    f(n) = nf(n) = 2*n + 1f(n) = n +log(n)⌋等

    n越大,f(n)就越大。

    获取给定 n 的数字的另一种方法是将随机数添加到 f(n - 1)

    【讨论】:

    • 但是如果我希望n 依赖于currentLevelf(n) 作为添加到currentList 的对象的数量,我该如何循环呢?跨度>
    • @crin,您可能会认为currentLevel 与我的回答中的n 相同。要添加 f(currentLevel) 项目,您只需更改循环 for (int i = 0; i &lt; f(currentLevel); i++)
    • 我觉得自己很蠢,因为我觉得这对我来说应该不难理解,但是f是什么?
    • @crin,意思是n的函数
    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    相关资源
    最近更新 更多