【问题标题】:Checking collisions 2D array connect 4检查碰撞 2D 阵列连接 4
【发布时间】:2013-01-22 07:59:15
【问题描述】:

我目前正在尝试用 C# 制作一个 2D 连接四游戏。你知道什么时候所有 4 种颜色都必须匹配。无论如何,我目前正试图让碰撞工作,但不断收到错误消息“索引超出数组范围”你知道这是为什么吗?谢谢

private void rules()
{
    int count = 0;

    if (btn[maxR, maxC].BackColor == Color.Red)
    {
        count = 1;
    }
    for (int i = 0; i <= btn.Length; i++)
    {

        if (btn[maxR, i].BackColor == Color.Red)
        {
            count++;
        }

    }
    if (count >= 4)
    {
        lbl2.Text = "winner";
    }
}

【问题讨论】:

  • 哪一行抛出exception?您确实应该使用try/catch 块并捕获exception object.Message 属性。
  • 您正试图访问一个负数或等于或大于数组长度的数的数组。例如,如果您声明一个大小为 [maxR] 的数组,则可用索引为 0、1、2...maxR-1(这是 maxR 个条目!),并且在 maxR 处访问将引发异常。跨度>

标签: c# arrays 2d collision


【解决方案1】:

你用过:

i <= btn.Length

这会导致超出范围异常,因为索引从零开始并以btn.Length-1 结束。

所以使用:

for (int i = 0; i < btn.Length; i++)

P.S:不知道有没有逻辑错误。

【讨论】:

  • 是的,你说得对。现在我收到错误:if (btn[maxR, i].BackColor == Color.Red) { count++; } -_-
  • @Das_burr,如果您修复了您的 i 探针,请检查您的 maxR 值,如果再次超出范围,请修复它。还有你的错误是什么?
  • 和之前一样“索引超出了数组的范围”
猜你喜欢
  • 1970-01-01
  • 2011-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多