【问题标题】:moving an element in 2d array with arrow keys and having border restricting movement使用箭头键移动二维数组中的元素并限制移动
【发布时间】:2020-03-06 06:44:47
【问题描述】:

我不知道之前是否已经回答过这个问题,但是如何使用箭头键移动二维数组中的元素?说这样的话,如果不可能,就让它不动,因为在显示的图像中 0 可以交换并向上、向下、向左和向右,但下一步你只能使用向上、向下和向左三个选项

C# 新手,所以如果网上有关于我的问题的有用示例,请将它们发布在评论中

using System;

namespace moveElement
{
    public class move
    {
        static void Main(string[] args)
        {
            int[,] arr = { { 9, 1, 4 }, { 5, 0, 3 }, { 6, 8, 2 } };
            for (int i = 0; i < 3; i++)
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            Console.Write(arr[i, j] + " ");
                        }

                        Console.WriteLine();
                    }
        }
    }
}

接受建议并让它像这样工作

            ConsoleKeyInfo info = Console.ReadKey();
            if (info.Key == ConsoleKey.RightArrow)
            {
                int temp = arr[1, 1];
                arr[1, 1] = arr[1, 2];
                arr[1, 2] = temp;
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        Console.Write(arr[i, j] + " ");

                    }
                    Console.WriteLine();

                }

            }

在处理代码一段时间后,我在第 41 行(y)和 47(x)上收到错误 "use of unassigned local variable x and y",我已经完成了大部分问题,但仍然遇到此错误

using System;

namespace moveElement
{
    public class move
    {
        static void Main(string[] args)
        {
            int x, y;
            int[,] arr = { { 0, 1, 4 }, { 3, 9, 5 }, { 6, 8, 2 } };
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(arr[i, j] + " ");

通过为xy 赋予0 的值来解决问题。

【问题讨论】:

    标签: c# arrays


    【解决方案1】:

    您可以尝试类似于this post 的答案,将位置 1 的变量放入临时变量中,然后将位置 1 设置为位置 2 的值,最后将位置 2 的值设置为临时变量中有什么:

    var t = a;
    a = b;
    b = t;
    

    要真正确定您是否可以朝特定方向移动,您需要检查您是否处于边界,例如,边界将是(其中 i 是任何有效位置):

    arr[0, i]
    arr[arr.getLength(0)-1, i]
    arr[i, 0]
    arr[i, arr.getLength(1)-1]
    

    如果你当前的位置和其中一个相同,你需要添加一些条件,让你不能往特定的方向移动,例如,如果你有arr[0, i],你就不能往上移动一个因为它将转到不存在的 arr[-1, i] 。

    我建议阅读 Array.getLength(Int32 维度) method 以找到边界(它本质上是获取指定维度的数组长度)

    【讨论】:

    • 我能够解决我的问题非常感谢您的建议
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多