C#

[길찾기 알고리즘] 1. 미로 준비 (4) 플레이어 이동

binary는 호남선 2024. 11. 17. 20:33

- 목적지까지 현재 있는 좌표를 기준으로 상하좌우로 이동

Player.cs

class Player
{
    // 플레이어 좌표
    public int PosY { get; private set; }
    public int PosX { get; private set; }
    Random rand = new Random();

    Board _board;

    public void Initialize(int posY, int posX, int destY, int destX, Board board)
    {
        PosY = posY;
        PosX = posX;

        _board = board;
    }

    const int MOVE_TICK = 100;  // 0.1초
    int _sumTick = 0;
    public void Update(int deltaTick)
    {
        // 프레임 맞추기
        _sumTick += deltaTick;
        if (_sumTick >= MOVE_TICK)
        {
            _sumTick = 0;

            // 0.1 초마다 실행할 로직
            int randValue = rand.Next(0, 5);

            // 상하좌우 이동
            // 유효한 좌표인지 확인 && 갈 수 있는 좌표인지 확인
            switch (randValue)
            {
                case 0:     // 상
                    if ((PosY - 1 >= 0) && (_board.Tile[PosY - 1, PosX] == Board.TileType.Empty))
                        PosY = PosY - 1;
                    break;
                case 1:     // 하
                    if ((PosY + 1 < _board.Size) && (_board.Tile[PosY + 1, PosX] == Board.TileType.Empty))
                        PosY = PosY + 1;
                    break;
                case 2:     // 좌
                    if ((PosX - 1 >= 0) && (_board.Tile[PosY, PosX - 1] == Board.TileType.Empty))
                        PosX = PosX - 1;
                    break;
                case 3:     // 우
                    if ((PosX + 1 < _board.Size) && (_board.Tile[PosY, PosX + 1] == Board.TileType.Empty))
                        PosX = PosX + 1;
                    break;
            }
        }
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        Board board = new Board();
        Player player = new Player();
        board.Initialize(25, player);
        player.Initialize(1, 1, board.Size - 2, board.Size - 2, board);

        Console.CursorVisible = false;
        
        const int WAIT_TICK = 1000 / 30;
        int lastTick = 0;


        while (true)
        {
            #region 프레임 관리
            // 만약 경과한 시간이 1/30초보다 작으면
            int currentTick = System.Environment.TickCount;
            if (currentTick - lastTick < WAIT_TICK)
                continue;
            int deltaTick = currentTick - lastTick;
            lastTick = currentTick;
            #endregion

            // 입력

            // 로직
            player.Update(deltaTick);

            // 렌더링
            Console.SetCursorPosition(0, 0);
            board.Render();
        }
    }
}

내용 출처 : Inflearn Rookiss님 강의 [C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part2: 자료구조와 알고리즘

https://www.inflearn.com/course/%EC%9C%A0%EB%8B%88%ED%8B%B0-mmorpg-%EA%B0%9C%EB%B0%9C-part2