using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 练习01
{
class A
{
private static void Main()
{
int[,] sz = new int[4, 4]
{
{ 0, 4, 0, 0 },
{ 2, 4, 0, 2 },
{ 4, 8, 4, 2 },
{ 4, 8, 8, 4 },
};
int[,] suzu = new int[4, 4];
suzu = hs1(sz);
Console.WriteLine(suzu);
Console.ReadKey ();
}
private static int[] Hs(int[] array)
{
int[] newarray = new int[array.Length ];
int c = 0;
for (int j = 0; j < array.Length ; j++)
{
if (array[j] != 0)
{
newarray[c++] = array[j];
}
}
return newarray;
}
private static int[] Hs1(int[] array)
{
array = Hs(array);
for (int i = 0; i < array.Length -1; i++)
{
if (array[i] != 0 && array[i] == array[i + 1])
{
array[i] = array[i] + array[i + 1];
array[i + 1] = 0;
}
}
array = Hs(array);
return array;
}
private static int[,] hs(int[,] sz)
{
int[] newsz = new int[sz.GetLength(0)];
for (int i = 0; i < sz.GetLength(1); i++)
{
for (int j = 0; j < sz.GetLength(0); j++)
{
newsz[i] = sz[j, i];
}
newsz = Hs1(newsz);
for (int j = 0; j < sz.GetLength(0); j++)
{
sz[j, i] = newsz[j];
}
}
return sz;
}
private static int[,] hs1(int[,] sz)
{
int[] newsz1 = new int[sz.GetLength(0)];
for (int i = 0; i < sz.GetLength(1); i++)
{
for (int j = sz.GetLength(0) - 1; j >= 0; j--)
{
newsz1[3 - j] = sz[j, i];
}
newsz1 = Hs1(newsz1);
for (int j = 0; j < sz.GetLength(0); j++)
{
sz[j, i] = newsz1[3 - j];
}
}
return sz;
}
}
}
函数已经写完了,但是不知道怎么用。
qwertyuiopasdfghjklzxcvbnm
这段代码可能是实现一个2048小游戏的逻辑,但是基于C#控制台程序,没有可视化界面,所以无法演示游戏的效果,只能在控制台输出结果。
为了调用这些方法并输出结果,可以在类A的Main方法中进行调用。具体实现如下:
using System;
namespace 练习01
{
class A
{
static void Main()
{
int[,] sz = new int[4, 4]
{
{ 0, 4, 0, 0 },
{ 2, 4, 0, 2 },
{ 4, 8, 4, 2 },
{ 4, 8, 8, 4 },
};
int[,] suzu = new int[4, 4];
suzu = hs1(sz);
// 遍历输出结果
for (int i = 0; i < suzu.GetLength(0); i++)
{
for (int j = 0; j < suzu.GetLength(1); j++)
{
Console.Write(suzu[i, j] + "\t");
}
Console.WriteLine();
}
Console.ReadKey();
}
private static int[] Hs(int[] array)
{
// ...
}
private static int[] Hs1(int[] array)
{
// ...
}
private static int[,] hs(int[,] sz)
{
// ...
}
private static int[,] hs1(int[,] sz)
{
// ...
}
}
}
上述Main方法首先定义了一个4x4的数组sz,然后调用hs1方法对其进行转置,然后调用Hs1方法进行左移合并,最后再调用hs1方法重新转置回来。将转置前后的数组打印输出,从控制台输出结果可知,输出结果是将sz进行左移合并之后的状态。
注意,在Main方法中,需要对suzu进行初始化,否则会出现空引用异常。另外,在输出数组的时候,需要遍历输出每个元素,最后加上换行符进行分行。输出结果每行之间使用Tab符进行分隔。