좀 더 코드를 간략하게 만들 수 있는 방법이 있을까요?
(그나저나 AI가 추천하는 코드의 품질이 상당히 좋아졌네요!)
static void PrintGrid(int[,] grid)
{
for (var y = 0; y < grid.GetLength(0); y++)
{
for (var x = 0; x < grid.GetLength(1); x++)
{
var v = grid[y, x];
Console.Write($"{(v is 0 ? " " : v)} ");
}
Console.WriteLine();
}
}
static void ShufflingGrid(int[,] grid, int count)
{
var r = Random.Shared;
var my = grid.GetLength(0);
var mx = grid.GetLength(1);
(int, int) func() => (r.Next(mx), r.Next(my));
for (var i = 0; i < count; i++)
{
var (ox, oy) = func();
var (nx, ny) = func();
(grid[nx, ny], grid[oy, ox]) = (grid[oy, ox], grid[nx, ny]);
}
}
static bool IsSameGrid(int[,] grid1, int[,] grid2) => grid1.Cast<int>().SequenceEqual(grid2.Cast<int>());
static (int x, int y) FindEmptyPos(int[,] grid)
{
for (var y = 0; y < grid.GetLength(0); y++)
for (var x = 0; x < grid.GetLength(1); x++)
if (grid[y, x] == 0) return (x, y);
return (-1, -1);
}
int[,] grid =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 0 },
};
var newGrid = (int[,]) grid.Clone();
ShufflingGrid(newGrid, 100);
while (IsSameGrid(grid, newGrid) is false)
{
Console.Clear();
PrintGrid(newGrid);
Console.WriteLine();
Console.WriteLine("WASD 키로 이동할 수 있어요.");
var key = Console.ReadKey().Key;
var (x, y) = FindEmptyPos(newGrid);
var (nx, ny) = key switch
{
ConsoleKey.W when y < newGrid.GetLength(0) - 1 => (x, y + 1),
ConsoleKey.A when x < newGrid.GetLength(1) - 1 => (x + 1, y),
ConsoleKey.S when y > 0 => (x, y - 1),
ConsoleKey.D when x > 0 => (x - 1, y),
_ => (x, y)
};
(newGrid[y, x], newGrid[ny, nx]) = (newGrid[ny, nx], newGrid[y, x]);
}