3월 18일 #콘솔 프로젝트

sejun-Lee·2025년 3월 18일
post-thumbnail

✅콘솔 텍스트게임 제작하기

  • 게임 루프 구현
  • 기본 구조
namespace project_s
{
    internal class Program
    {
        struct Position
        {
            public int x;
            public int y;
        }

        static void Main(string[] args)
        {
            bool gameOver = false;
            Position playerPos;
            char[,] map;

            Start();
            while (gameOver == false)
            {
                Render();
                ConsoleKey key = Input();
                Update();
            }
            End();
        }

        static void Start()
        {
          
        }

        static void Render()
        {
            
        }

        static void PrintPlayer()
        {
            
        }

        static ConsoleKey Input()
        {
           return Console.ReadKey(true).Key;
        }

        static void Update()
        {
            
        }
        
		static void Move()
        {

        }
        static bool IsClear()
        {
            
        }

        static void End()
        {
        
        }

    }
}



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleProject
{
    class Program
    {
        struct Position
        {
            public int x;
            public int y;
        }

        static void Main(string[] args)
        {
            bool gameOver = false;

            Position playerPos;     // player 위치
            playerPos.x = 0;
            playerPos.y = 0;

            Position goalPos;

            bool[,] map;    // 맵 2차원 배열로

            // 게임 준비
            Start(ref playerPos, out goalPos, out map);   // ref -> out도 가능

            while (gameOver == false)
            {
                // 0. 콘솔만 Render->Input->Update. // 실시간 게임은 Input->Update->Render
                // 1. Render : 그리기
                Render(playerPos, goalPos, map);
                // 2. Input : 입력
                ConsoleKey key = Input();
                // 3. Update : 처리
                Update(key, ref playerPos, goalPos, map, ref gameOver);
            }
            
            // 게임 종료
            End();

        }

        static void Start(ref Position playerPos, out Position goalPos, out bool[,] map)        // 시작 작업
        {              // ref -> out도 가능
            // 게임 설정
            Console.CursorVisible = false; // false 일 경우 커서 깜박임 안보임

            // 플레이어 초기 위치 설정하기
            playerPos.x = 1;
            playerPos.y = 1;

            // 목적지 위치 설정하기
            goalPos.x = 13;
            goalPos.y = 8;

            // 맵 설정하기
            map = new bool[10, 15]
            {   
                    // 0     1     2     3     4     5     6     7     8     9     10    11    12    13    14
                /*0*/{false,false,false,false,false,false,false,false,false,false,false,false,false,false, false},
                /*1*/{false, true, true,false, true, true, true, true, true, true, true, true, true, true, false},
                /*2*/{false, true, true,false, true, true, true, true, true, true, true, true, true, true, false},
                /*3*/{false, true, true,false, true, true, true, true, true, true, true, true, true, true, false},
                /*4*/{false, true, true,false, true, true, true, true, true, true, true, true, true, true, false},
                /*5*/{false, true, true, true, true, true, true, true, true, true, true, true, true, true, false},
                /*6*/{false, true, true, true, true, true, true, true, true, true, true, true, true, true, false},
                /*7*/{false,false,false,false, true, true, true, true, true, true, true, true, true, true, false},
                /*8*/{true, true, true, false, true, true, true, true, true, true, true, true, true, true, false},
                /*9*/{true, true, true, false,false,false,false,false,false,false,false,false,false,false, false},
            };

            ShowTitle();
        }

        static void ShowTitle()
        {
            Console.WriteLine("----------------");
            Console.WriteLine(" 레전드 미로찾기 ");
            Console.WriteLine("----------------");
            Console.WriteLine();
            Console.WriteLine("아무키나 눌러서 시작하세요....");

            Console.ReadKey(true);
            Console.Clear();
        }

        static void Render(Position playerPos, Position goalPos, bool[,] map)        // 출력 작업
        {
            // 콘솔 지우기(백버퍼) -> 게임은 연속해서 그려주는 과정, 전 화면을 지워주는 것
            //Console.Clear();          // 맵을 지워서 다시그리기 -> 깜박거림
            Console.SetCursorPosition(0, 0);    // 맵을 덮어서 그리기 -> 깜박거리지 않으나 택스트등을 남기면 남아있을 수 있다.

            // 맵을 먼저 그린 후 플레이어를 그릴것!! 맵에 플레이어를 덮어버릴 수 있음
            PrintMap(map);              // 맵 출력
            PrintPlayer(playerPos);     // 플레이어 출력 이동
            PrintGoal(goalPos);
        }

        static void PrintMap(bool[,] map)
        {
            // 맵 출력     y -> x 순서 바꾸지 말것!
            for (int y = 0; y < map.GetLength(0); y++)
            {                // GetLength -> 0일경우 map[a,b] 의 a 값을 가져올 수 있음
                for (int x = 0; x < map.GetLength(1); x++)
                {                   // GetLength -> 1일경우 map[a,b] 의 b 값을 가져올 수 있음
                    if (map[y, x] == false)
                    {
                        Console.Write('■');     // 벽
                    }
                    else
                    {
                        Console.Write(' ');     // 빈 공간
                    }
                }
                Console.WriteLine();            // 행 마다 줄바꿈 -> 맵의 새로 완성을 위함
            }
        }
        
        static void PrintPlayer(Position playerPos)
        {
            // 플레이어 위치로 커서 옮기기
            Console.SetCursorPosition(playerPos.x, playerPos.y);
            // 플레이어 출력
            Console.ForegroundColor = ConsoleColor.Green;   // 글자 색상 변경
            Console.Write("★");
            Console.ResetColor();
        }

        static void PrintGoal(Position goalPos)
        {   // 골인 지점 
            Console.SetCursorPosition(goalPos.x, goalPos.y);

            Console.ForegroundColor = ConsoleColor.Red;   // 글자 색상 변경
            Console.Write("G");
            Console.ResetColor();
        }

        static ConsoleKey Input()         // 입력 작업
        {
            // 키를 눌렀을때 움직이게 하기 위해
            ConsoleKey input = Console.ReadKey(true).Key;   // true를 쓰지 않으면 내가 입력한 키 출력됨.
            return input;
        }

        static void Update(ConsoleKey key, ref Position plyerPos, Position goalPos, bool[,] map, ref bool gameOver)        // 처리 작업
        {
            // 이동
            Move(key, ref plyerPos, map);

            // 골에 도달했는지 확인
            bool isClear = CheckGameClear(plyerPos, goalPos);
            if (isClear)
            {
                // 게임 종료
                gameOver = true;
            }
        }

        static void Move(ConsoleKey key, ref Position plyerPos, bool[,] map)
        {
            switch (key)
            {
                case ConsoleKey.A:
                case ConsoleKey.LeftArrow:
                    //  이동하기 전 벽이 있는지 확인해서 벽이 있으면 못가게
                    if (map[plyerPos.y, plyerPos.x - 1] == true)
                    {
                        plyerPos.x--;
                    }
                    break;
                case ConsoleKey.D:
                case ConsoleKey.RightArrow:
                    if (map[plyerPos.y, plyerPos.x + 1] == true)
                    {
                        plyerPos.x++;
                    }
                    break;
                case ConsoleKey.W:
                case ConsoleKey.UpArrow:
                    if (map[plyerPos.y - 1, plyerPos.x] == true)
                    {
                        plyerPos.y--;
                    }
                    break;
                case ConsoleKey.S:
                case ConsoleKey.DownArrow:
                    if (map[plyerPos.y + 1, plyerPos.x] == true)
                    {
                        plyerPos.y++;
                    }
                    break;
            }
        }

        static bool CheckGameClear(Position plyerPos, Position goalPos)
        {
            // 플레이어가 골 위치에 도달했을 때
            // 플레이어의 x위치가 골 x위치랑 같으면서 동시에
            // 플레이어의 y위치가 골 y위치랑 같으면
            bool success = (plyerPos.x == goalPos.x) && (plyerPos.y == goalPos.y);

            // 게임은 클리어 되었다 라고 판정
            return success;
        }

        static void End()            // 종료 작업
        {
            Console.Clear();
            Console.WriteLine("축하합니다!! 미로 찾기에 성공하셨습니다!");
        }
    }
}

✅게임 실행파일 -> 프로젝트 폴더에서 bin 폴더 안에 게임 실행파일(.exe) 파일이 실행파일

profile
초보 개발자

0개의 댓글