【问题标题】:Uneven grid with for loop(s)带有 for 循环的不均匀网格
【发布时间】:2014-07-27 15:45:30
【问题描述】:

所以这是我的问题:

我有一个 RPG 库存,它通过两个 for 循环在网格 (7x4) 中绘制项目:

[Update Method]

index = 0;
for (int x = 0; x < 7; x++)
{
    for (int y = 0; y < ItemList.Count / 7; y++)
    {
        ItemList[index].gridLocation = new Point(x, y);
        index++;
    }
}

*ItemList 只是 BaseItem 类的列表。

这就是我希望这段代码绘制网格的方式:

X X X X X X X
X X X X X X X
X X X X X X X
X X X X X

但这就是它的做法:

X X X X X X X
X X X X X X X
X X X X X X X

将不大于等于 7 的最后一行截掉。

现在,当我使用一个项目时(使用一个项目将其从列表中删除),它会将下一个隐藏项目添加到第三行的末尾。

如果有任何帮助,我将不胜感激。 谢谢,

编辑:感谢 Nico 的帮助,这就是我的代码现在的样子:

                if (ItemList.Count > 6)
                {
                    for (int index = 0; index < ItemList.Count; ++index)
                    {
                        ItemList[index].gridLocation = new Point(index % 7, (int)(index / 7));
                        ItemList[index].UpdateValues(ScreenLocation, itemSize, LocY);
                    }
                }
                else if (ItemList.Count < 7)
                {
                    for (int index = 0; index < ItemList.Count; ++index)
                    {
                        ItemList[index].gridLocation = new Point(index, 0);
                        ItemList[index].UpdateValues(ScreenLocation, itemSize, LocY);
                    }
                }

我发现有一个问题,如果 itemList 低于 7,它不会显示任何项目。上面的代码修复了它。再次感谢!

【问题讨论】:

    标签: c# for-loop xna-4.0


    【解决方案1】:

    您可以使用索引进行迭代:

    for(int index = 0; index < ItemList.Count; ++index)
        ItemList[index].gridLocation = new Point(index % 7, (int)(index / 7));
    

    请注意,我已经翻转了项目顺序。你的是按列的,现在是按行的。我假设,你的意思是,因为你有一个固定的网格宽度 7 和一个可变的行号。如果这不正确,请发表评论。

    【讨论】:

    • 首先感谢您的快速回复,其次,它立即生效。太感谢了!这个问题在我的代码中已经存在很长时间了。
    猜你喜欢
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2019-03-11
    • 1970-01-01
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多