전체 코드
using System.ComponentModel;
using System.Numerics;
using System.Threading;
namespace CSharp
{
class Map
{
int[,] tiles =
{
{ 1,1,1,1,1 },
{ 1,0,0,0,1 },
{ 1,0,0,0,1 },
{ 1,0,0,0,1 },
{ 1,1,1,1,1 }
};
public void Render()
{
ConsoleColor defaultColor = Console.ForegroundColor;
for (int y = 0; y < tiles.GetLength(1); y++)
{
for (int x = 0; x < tiles.GetLength(0); x++)
{
if (tiles[y, x] == 1)
{
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
}
Console.Write('\u25cf');
}
Console.WriteLine();
}
Console.ForegroundColor = defaultColor;
}
}
class Program
{
static void Main(string[] args)
{
int[] scores = new int[5] { 10, 30, 40, 20, 50 };
int[,] arr = new int[2, 3] { {1,2,3 },{1,2,3 } };
Map map = new Map();
map.Render();
int[][] a = new int[3][];
a[0] = new int[3];
a[1] = new int[6];
a[2] = new int[2];
}
}
}
🗺️ Map 클래스 분석 - 2차원 배열 활용
class Map
{
✅ 2D 배열 정의 및 초기화
int[,] tiles =
{
{ 1,1,1,1,1 },
{ 1,0,0,0,1 },
{ 1,0,0,0,1 },
{ 1,0,0,0,1 },
{ 1,1,1,1,1 }
};
| 숫자 | 의미 |
|---|
| 1 | 벽 (Wall) |
| 0 | 이동 가능 공간 (Walkable) |
int[,]는 2차원 배열을 의미
- 배열 초기화 시
{} 중첩으로 행/열 정의
- 이 배열은 5x5 크기이며, 외곽은 벽, 가운데는 이동 가능 공간
✅ 맵 렌더링 함수
public void Render()
{
색상 저장
ConsoleColor defaultColor = Console.ForegroundColor;
행/열 순회
for (int y = 0; y < tiles.GetLength(0); y++)
{
for (int x = 0; x < tiles.GetLength(1); x++)
{
GetLength(0) : 행의 개수 (5)
GetLength(1) : 열의 개수 (5)
타일 상태에 따른 색상 및 출력
if (tiles[y, x] == 1)
{
Console.ForegroundColor = ConsoleColor.Red;
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
}
Console.Write('\u25cf');
한 줄 끝날 때 줄 바꿈
Console.WriteLine();
색상 복원
Console.ForegroundColor = defaultColor;
📦 Program 클래스 분석 - 가변 배열 활용
class Program
{
static void Main(string[] args)
{
✅ 가변 배열 선언과 초기화
int[][] a = new int[3][];
a[0] = new int[3];
a[1] = new int[6];
a[2] = new int[2];
int[][]는 가변 배열 (Jagged Array)를 의미
- 행마다 서로 다른 열 길이를 가질 수 있음
- 초기화 예시:
- 첫 번째 행은 3칸
- 두 번째 행은 6칸
- 세 번째 행은 2칸
✅ 값 할당 예시
a[0][0] = 1;
✅ 맵 객체 생성 및 렌더링 호출
Map map = new Map();
map.Render();
- 2차원 배열로 구성된 맵을 렌더링
- 콘솔에 색상으로 시각적 표현
📋 주석 처리된 보너스 코드 분석 (2D 배열 초기화)
int[,] arr = new int[2, 3] { { 2, 3, 4 }, { 1, 2, 3 } };
다른 초기화 방법
int[,] arr2 = new int[,] { { 2, 3, 4 }, { 1, 2, 3 } };
int[,] arr3 = { { 2, 3, 4 }, { 1, 2, 3 } };
- 크기 명시 생략 가능
- 데이터만 보고 C# 컴파일러가 자동으로 크기 유추
특정 원소 접근 및 변경
arr[0, 0] = 1;
arr[1, 2] = 6;
2D 배열 순회 예시
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}