4x4 数组中的元素与数字交换
我正在制作一款这样的游戏: https://i.sstatic.net/mnbFw.jpg。我在编写相互交换数字的算法时遇到困难。在我的游戏中,0 充当空块。该算法最初适用于 3x3 网格,但我只是将 3 切换为 4。我认为这就是引起问题的原因,但我似乎找不到原因。
{
int j, i;
for (i = 1; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i - 1, j];
t1[i - 1, j] = 0;
}
}
}
}
static void scan_above(int[,] t1)
{
int j, i;
for (i = 1; i >= 0; i--)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i + 1, j];
t1[i + 1, j] = 0;
}
}
}
}
static void scan_left(int[,] t1)
{
int j, i;
for (j = 1; j >= 0; j--)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j + 1];
t1[i, j + 1] = 0;
}
}
}
}
static void scan_right(int[,] t1)
{
int j, i;
for (j = 1; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j - 1];
t1[i, j - 1] = 0;
}
}
}
}```
I am making a game like this one : https://i.sstatic.net/mnbFw.jpg. I am having trouble coding the algorithm to swap numbers between each others. In my game , the 0 acts as the empty tile. This algorithm was originally for a 3x3 grid but I simply switched the 3's to 4's. I think that this is what's causing issues but I can't seem to find why.
{
int j, i;
for (i = 1; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i - 1, j];
t1[i - 1, j] = 0;
}
}
}
}
static void scan_above(int[,] t1)
{
int j, i;
for (i = 1; i >= 0; i--)
{
for (j = 0; j < 4; j++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i + 1, j];
t1[i + 1, j] = 0;
}
}
}
}
static void scan_left(int[,] t1)
{
int j, i;
for (j = 1; j >= 0; j--)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j + 1];
t1[i, j + 1] = 0;
}
}
}
}
static void scan_right(int[,] t1)
{
int j, i;
for (j = 1; j < 4; j++)
{
for (i = 0; i < 4; i++)
{
if (t1[i, j] == 0)
{
t1[i, j] = t1[i, j - 1];
t1[i, j - 1] = 0;
}
}
}
}```
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很困惑为什么你要循环遍历矩阵中的所有值。除非问题中未包含考虑因素,否则这就是应该采取的全部措施:
仅供参考,我匆忙地将矩阵放在一起,以便向后索引,其中 x 是行号,y 是 是列。您可以轻松地按照相同的步骤向各个方向移动。
I'm confused about why you're looping through all the values in the matrix. Unless there are considerations that aren't included in the question, this is all it should take:
FYI I hastily put together my matrix so it's indexed backwards, where
x
is the row number andy
is the column. You could easily follow the same steps to make a move for every direction.