C#프로그래밍

이차원 배열 맵 캐릭터 움직이기

노재두내 2023. 7. 25. 15:47
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;

namespace LearnDotnet
{
    internal class App
    {
        int[,] playerMap;
        int rowIdx;
        int colIdx;
        //생성자
        public App()
        {
            //배열의 인스턴스화
            int[,] map =
            {
                {1,1,1 },
                {1,1,2 }
            };
            this.playerMap = new int[map.GetLength(0), map.GetLength(1)];

            this.PrintMap(map);
            this.PrintSpace();
            this.PrintMap(playerMap);
            //초기 위치 설정
            this.rowIdx = 1;
            this.colIdx = 2;
            playerMap[this.rowIdx, this.colIdx] = 100;
            this.PrintSpace();
            this.PrintMap(playerMap);
            this.MoveLeft();
            PrintSpace();
            this.PrintMap(playerMap);
            PrintSpace();
            this.MoveRight();
            this.PrintMap(playerMap);
            this.MoveLeft();
            this.MoveLeft();
            this.MoveLeft();
            //Console.WriteLine(map.GetLength(0));
            //인덱스로 배열의 요소에 접근
            //배열의 순회(요소를 출력)

        }
        void MoveLeft()
        {
            int nextCol = this.colIdx - 1;
            if (nextCol < 0)
            {
                Console.WriteLine("갈 수 없는 곳입니다.");
                return;
            }
            playerMap[this.rowIdx, this.colIdx - 1] = 100;
            playerMap[this.rowIdx, this.colIdx] = 0;
            this.colIdx -= 1;
            Console.WriteLine("왼쪽으로 이동했습니다.[{0},{1}], {2}", this.rowIdx, this.colIdx, this.playerMap[this.rowIdx, this.colIdx]);
        }
        void MoveRight()
        {
            playerMap[this.rowIdx, this.colIdx + 1] = 100;
            playerMap[this.rowIdx, this.colIdx] = 0;
            this.colIdx += 1;
            Console.WriteLine("오른쪽으로 이동했습니다[{0},{1}] ,{2}", this.rowIdx, this.colIdx, this.playerMap[this.rowIdx, this.colIdx]);
        }
        void PrintSpace()
        {
            Console.WriteLine();
        }

        void PrintMap(int[,] arr)
        {
            for (int i = 0; i < arr.GetLength(0); i++)
            {
                for (int j = 0; j < arr.GetLength(1); j++)
                {
                    int element = arr[i, j];
                    Console.Write("[{0},{1}] : {2}\t", i, j, element);
                }
                Console.WriteLine();
            }
        }


    }
}