c# 움직이는 적 구현과 총알충돌구현실험...ㅠㅠ

c# 움직이는 적 구현과 총알충돌구현실험...ㅠㅠ

작성일 2022.09.10댓글 1건
    게시물 수정 , 삭제는 로그인 필요

움직이는적 구현 과 총알 충돌 시험입니다. 버그가 잔뜩나오네요 ㅠㅠ.. 
=========================================================================
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Threading;
using System.Drawing;


namespace Project5

{
    public class play
    {
        //=플래이어 좌표====
        public int x = 10;
        public int y = 20;
        //=충돌좌표==========
        public int position1;
        public int position2;
     
        public Random random = new Random();
        // xposition  x, y point
        public Point xposition;
        public Point xposition2;
        // 총점수획득
        public int total = 0;
        public void enemyposition1()
   
        {
            xposition = new Point(random.Next(10, 60), 6);
           
            Console.CursorVisible = false;
            while (true)
            {
 
                    Console.SetCursorPosition(xposition.X, xposition.Y);
                   
                    Console.Write("#");

                   Console.SetCursorPosition(xposition.X - 1, xposition.Y);
                   Console.Write(" ");
                    
                    xposition.X++;
                    
                    Thread.Sleep(100);
                if (xposition.X == 70)//x 측 오른쪽 70 이면 원위치...외벽 통과 방지
                {

                    while (true)
                    {
                        Console.SetCursorPosition(xposition.X, xposition.Y);
                        Console.Write("#");

                        Console.SetCursorPosition(xposition.X + 1, xposition.Y);
                        Console.Write("  ");
                        xposition.X--;
                        
                        Thread.Sleep(100);
                        if (xposition.X == 6)
                        {
                            break; 
                        }

                        
                        if((xposition == new Point(x - 1, y) || xposition == new Point(x + 1, y)))
                        {
                            break;
                        }
                       
                    }
                  
                }
                if (xposition.X == 70)//x축이 6이면 원위치..외벽통과 방지
                {
                    while (true)
                    {
                        Console.SetCursorPosition(xposition.X, xposition.Y);
                        Console.Write("#");
                        Console.SetCursorPosition(xposition.X-1 , xposition.Y);
                        Console.Write(" ");
                        xposition.X++;
                    
                        Thread.Sleep(100);
                        if (xposition.X == 70)
                        {
                            break;

                        }
                       if ((xposition == new Point(x - 1, y) || xposition == new Point(x + 1, y)))
                        {
                            break;
                        }
                    }

                }
               
            }
           
           
        }
            
        public void startposition()
        {
        
            //===========점수판 표시=========================
            Console.SetCursorPosition(83, 9);
            Console.WriteLine("획득 점수");
            //============플래이어생성========================
            Console.SetCursorPosition(x, y);
            Console.Write("▲");
            Console.CursorVisible = false;
            bool run = true;
            do
            {
                var input = Console.ReadKey();
                switch (input.Key)
                {
                    case ConsoleKey.LeftArrow:
                        Console.SetCursorPosition(x, y);
                        int m = --x;
                        Console.Write("▲");
                        Console.SetCursorPosition((m + 2), y);
                        Console.Write("  ");
                        if (x == 6)//x 측 원쪽 6 이면 원위치...외벽 통과 방지
                        {
                            x = 10; y = 20;
                            Console.SetCursorPosition(x, y);
                            Console.Write("▲");
                            Console.SetCursorPosition(6, y);
                            Console.Write("  ");
                            Thread.Sleep(20);
                        }
                        break;
                    case ConsoleKey.RightArrow:
                        Console.SetCursorPosition(x, y);
                        int mm = ++x;
                        Console.Write("▲");
                        Console.SetCursorPosition((mm - 2), y);
                        Console.Write("  ");
                        if (x == 70)//x 측 오른쪽 70 이면 원위치...외벽 통과 방지
                        {
                            x = 65; y = 20;
                            Console.SetCursorPosition(x, y);
                            Console.Write("▲");
                            Console.SetCursorPosition(70, y);
                            Console.Write("  ");
                            Thread.Sleep(20);
                        }
                        break;
                    case ConsoleKey.Spacebar:
                        //  충돌후 랜덤 위치 재 생성시 xposition 에 다시 할당하여야 하는
                        //  point 로  x, y 좌표를 할당함
                        while (true)
                        {
                            Console.SetCursorPosition(x - 1, y);//1번 총알 좌표
                            Console.Write("*");
                            Console.SetCursorPosition(x + 1, y);//2번 총알 좌표
                            Console.Write("*");
                            y--;
                            Console.SetCursorPosition(x - 1, y + 2);//1번 총알 좌표 지워줌(y측 숫자늘리면 총알이 추가됨)
                            Console.Write(" ");
                            Console.SetCursorPosition(x + 1, y + 2);//2번 총알 좌표 지워줌(y측 숫자늘리면 총알이 추가됨)
                            Console.Write(" ");
                            Thread.Sleep(60);//총알 속도
                            // xposition 과 좌우 총알 중 하나라도 맞으면..
                            // 충돌 감지 후 적군 다이 시키고 .. 다시 좀비 적군 랜덤으로 재생성
                            if (xposition == new Point(x - 1, y) || xposition == new Point(x + 1, y))
                            {
                                total++;//맞춘 점수 더하기
                                xposition = new Point(random.Next(5, 30), 6);
                                Console.SetCursorPosition(xposition.X, 6);
                                //========랜덤 애니미 캐릭생성==========
                                char[] change = { 'A', 'B', 'C','D','E','F' };
                                Random changeenemy = new Random();
int key= changeenemy.Next(0, 5);
                                Console.Write(change[key]);
                                //======================================
                                Console.SetCursorPosition(87, 10);//점수표시 좌표
                                Console.WriteLine(total);
                            }
                            if(xposition2 == new Point(x - 1, y) || xposition2 == new Point(x + 1, y))
                            {
                                total++;//맟춘 점수 더하기
                                xposition2 = new Point(random.Next(31, 68), 6);//x측 31~68 로 위의 5~30 과 겹치기 방지
                                Console.SetCursorPosition(xposition2.X, 6);
                                //========랜덤 애니미 캐릭생성==========
                                char[] change = { 'G', 'H', 'I', 'J', 'K', 'L' };
                                Random changeenemy1 = new Random();
                                int key1 = changeenemy1.Next(0, 5);
                                Console.Write(change[key1]);
                                //======================================

                                Console.SetCursorPosition(87, 10);//점수표시 좌표
                                Console.WriteLine(total);
                             }
                            
                            if (y != 3) continue; // y 축 으로 총알 최대 도달 거리
                            Console.SetCursorPosition(x - 1, y + 1);//마지막 총알 자국 지워줌
                            Console.Write(string.Empty.PadLeft(1));
                            Console.SetCursorPosition(x + 1, y + 1);//마지막 총알 자국 지워줌
                            Console.Write(string.Empty.PadLeft(1));
                            y = 20;// y축 좌표 원위치
                            break;
                        }
                        break;

                    // 방향키 스페이스 키를 제외한 키를 누르면
                    // 게임종료 하기 기능
                    default: run = false; break;
                }
                Console.SetCursorPosition(x, y);//플래이어 지워지기 방지
                Console.Write("▲");
            } while (run);
        }
    }
    public class display
    {
        public int xx = 3;
        public int yy = 3;
        public void board()
        {
            char block = '■';
            Console.CursorVisible = false;
            Console.SetCursorPosition(xx, yy);
            for (int i = 0; i < 20; i++)
            {
                Console.SetCursorPosition(xx, yy++);
                Console.WriteLine(block);
            }
            Console.SetCursorPosition(xx, yy);
            for (int i = 0; i < 70; i++)
            {
                yy = 3;
                Console.SetCursorPosition(xx++, yy);
                Console.WriteLine(block);
            }
            Console.SetCursorPosition(3, 20);
            xx = 3; yy = 23;
            for (int i = 0; i < 70; i++)
            {
                Console.SetCursorPosition(xx++, yy);
                Console.WriteLine(block);
            }
            xx = 73; yy = 3;
            for (int i = 0; i < 21; i++)
            {
                Console.SetCursorPosition(xx, yy++);
                Console.WriteLine(block);
            }
            for (int i = 0; i < 13; i++)
            {
                Console.SetCursorPosition(81+i, 8);
                Console.WriteLine(block);
            }
            for (int i = 0; i < 4; i++)
            {
                Console.SetCursorPosition(81 , 8+i);
                Console.WriteLine(block);
            }
            for (int i = 0; i < 4; i++)
            {
                Console.SetCursorPosition(93, 8 + i);
                Console.WriteLine(block);
            }
            for (int i = 0; i < 13; i++)
            {
                Console.SetCursorPosition(81+i, 11 );
                Console.WriteLine(block);
            }
            Console.SetCursorPosition(75, 5);
            Console.WriteLine("# 맟히면 랜덤으로 알파뱃이 생성되며 ");
            Console.SetCursorPosition(83, 6);
            Console.WriteLine("1점을 획득합니다.");
        }
    }
    public class PlayGame
    {       
        public void Start()
        {
           
            play play = new play();
            display display = new display();//태스트를 위해 설정해 놓음
            Thread work = new Thread(new ThreadStart(play.enemyposition1));//태스트를 위해 설정해놓음
         
            display.board();
            work.Start();   
            play.startposition();
            
        }
        static void Main(string[] args)
        {        
            PlayGame playGame = new PlayGame();
            play play = new play();
           
            playGame.Start();
           

        }
    }
   
}


  


#c# 움직이는 이미지 #c# 움직이는 텍스트

profile_image 익명 작성일 -

안녕하세요..

약속드린대로 아래와 같이 작성하여 올려 드리오니..

테스트 하여 보세요..

코드 주석이 많다 보니 소스가 길어져서..자체를 압축하여 올려 드리고

영상도 만들어 보았는데, 문의 내용과 보니 적 움직임이 조금 다르군요.. 수정하시면 될 것 같고

시나리오와 흐름은 아래와 같습니다.

1. 적을 알파벳 숫자 만큼 생성하였으며

2. 10점이 되면 승리 처리

3. 끝난 후 재도전 추가

4. 총알은 하나가 아니라 모양상 로켓 모양 3행을 주었으며

5. 적을 맞추면 더이상 총알이 진행 되지 않게 하였으며

6. 적으 높이를 차등을 두었습니다.

7. 기타 나열하지 않은 것은 소스를 검토하여 주세요...

8. 발사 및 요격시 사운드 추가 (wav 파일 프로젝트 리소스에 첨부되어 있음)

9. 적 움직임에 비동기 처리 일부

// 프로그램 실행 영상 ///

// 소스 : 완전한 소스는 첨부 파일을 참조 하시고 ...

// 내용이 길어 ... 부분별로 쪼갠 코드 조각은 아래와 같습니다.

// 순서대로 보시면 됩니다...

(소스 조각 1 / )

1. Main

public class Program { public static int ConsoleWidth; public static int ConsoleHeight; private static DrawOutline rect; public static void Main() { // 콘솔에서 유니코드 텍스트 표시가능하게 하기 // 콘솔 폰트는 Consolar 등으로 설정 Console.OutputEncoding = Encoding.UTF8; // 콘솔제목설정 Console.Title = @"즐거운 슈팅게임"; // 커서 숨기기 Console.CursorVisible = false; // 콘솔 윈도우를 중앙에 배치 WindowUtility.MoveWindowToCenter(); // 콘솔 사이즈 설정 (모니터 화면의 절반 폭, 높이) ConsoleWidth = Console.LargestWindowWidth / 2; ConsoleHeight = Console.LargestWindowHeight / 2; // 콘솔 윈도우 사이즈 설정 Console.SetWindowSize(ConsoleWidth, ConsoleHeight); Console.SetBufferSize(ConsoleWidth, ConsoleHeight); rect = new DrawOutline(ConsoleWidth, ConsoleHeight); // (1) 게임 플레이 외곽선설정 rect.DrawOutLine(2); // (2) 게임플레이 _ = new GamePlay(ConsoleWidth, ConsoleHeight, ConsoleWidth / 2, Console.BufferHeight - 3); // game.Play(); Console.ReadLine(); } }

2. 게임 플레이 ( 2 / )

#region 게임 플레이 public class GamePlay { // 쓰레드 데이터 보호목적 필드 private static readonly object obj = new object(); // 적요격 시 사운드 public readonly SoundPlayer distroyWav = new SoundPlayer(Resources.beep_02); // 총발사 시 사운드 public readonly SoundPlayer shuttingWav = new SoundPlayer(Resources.shutting); // 적 랜덤위치 생성목적 필드 private readonly Random random = new Random(); // 스코어 제목 private const string ScoreTitle = @"Game Score"; // 콘솔넓이 public int ConsoleWidth { get; } // 콘솔높이 public int ConsoleHeight { get; } // 콘솔 좌/우, 상/하 패딩 (외곽선 그어지는 곳) public const int Padding = 2; // 적의 숫자 (알파벳 숫자 26개 이하설정) public const int EnemyCount = 26; // 총알 발사횟수 제목 private const string ShuttingTitle = "Shuttings Count"; // 승리 메시지 private const string winnerMessage = @"You Win...!!!! Press 'R' Replay...";

3. GamePaly ( 2 / )

/// <summary> /// 플레이어 X 좌표 /// </summary> private int playerX; public int PlayerX { get => playerX; set { // 좌 / 우 플레이어 움직임 방향 확인 // value : 새로운 좌표, playerX: 기존 좌표 // 즉, value 가 크면 오른쪽으로 움직였다는 의미로 (true= 우), (false = 좌) bool direction = value > playerX; // X 위치값 동기화, 지난위치를 새 위치로 덮어쓰기 playerX = value; // 오른쪽으로 움직였으면, 왼쪽 트레이스 지우고 // 왼쪽으로 움직였다면, 오른쪽 트레이스 지우기 RemovePlayerTrace(direction ? playerX - 1 : playerX + 1, playerY); // 왼쪽벽 + Padding + 2 지점에 도달하면 오른쪽 벽 - Padding - 2 X 좌표설정.. // 총알이 X 좌표에서 좌 / 우, + / - 1 에서 발사되는 것 감안 if (value == Padding + 2) playerX = ConsoleWidth - Padding - 2; // 오른쪽벽 -2 지점에 도달하면 왼쪽벽 + 2 지점에서 다시 시작 if (value == ConsoleWidth - Padding - 2) playerX = Padding + 2; // 총알좌표와 플레이어 좌표를 동기화 시킴 bullet.X = value; // 플레이어 삼각형 찍기 SetPositionWriteChar(playerX, playerY, "▲"); } } /// <summary> /// 플레이어 Y 좌표 /// </summary> private int playerY; public int PlayerY { get => playerY; set { playerY = value; // 총알이 플레이어 전면 +2 앞에서 발사 bullet.Y = value - 2; } } /// <summary> /// 좌/우 총알 좌표 /// </summary> private Point bullet; public Point Bullet { get => bullet; set => bullet = value; } // 10점 얻으면 승리 // 응용가능 : 총알 발사수 - winnerScore >= 10 이상도 가능하며 // 알파벳 적을 특정문자 순서대로 잡았을 때 승리 요건도 가능 private const int winnerScore = 10; /// <summary> /// 점수기록 /// </summary> private int score; public int Score { get => score; set { score = value; if (score >= winnerScore) { // 승리했을 메세지 표시, 화면 정 중앙 Console.SetCursorPosition((ConsoleWidth - winnerMessage.Length) / 2, ConsoleHeight / 2); Console.Write(winnerMessage); } // 점수판 제목과 점수 갱신 SetPositionWriteChar((Console.WindowWidth - ScoreTitle.Length) / 2, 1, $@"{ScoreTitle} : {score}"); } } // 전체 총알 발사횟수 () private int shuttings; public int Shuttings { get => shuttings; set { shuttings = value; SetPositionWriteChar(Padding, 1, $@"{ShuttingTitle} : {shuttings}"); } } public Point[] enemys; public Point this[int index] { get { if (index < 0 || index >= enemys.Length) throw new IndexOutOfRangeException(); return enemys[index]; } set { // 적 알파벳 기록시 데이터 침범방지 lock (obj) { if (index < 0 || index >= enemys.Length) return; enemys[index] = value; SetPositionWriteChar(enemys[index].X, enemys[index].Y, $"{(char)(index + 65)}"); } } }

3. GamePlay ( 3 / )

/// <summary> /// 게임플레이 생성자, 콘솔 및 플레이어, 적 초기화 후 /// 게임 시작 트리거 /// </summary> /// <param name="consoleWidth"></param> /// <param name="consoleHeight"></param> /// <param name="playerX"></param> /// <param name="playerY"></param> public GamePlay(int consoleWidth, int consoleHeight, int playerX, int playerY) { ConsoleWidth = consoleWidth; ConsoleHeight = consoleHeight; PlayerY = playerY; PlayerX = playerX; enemys = new Point[EnemyCount]; InitStage(); } /// <summary> /// 스테이지 초기화 /// </summary> public void InitStage() { // 승리 메세지 지우기 Console.SetCursorPosition((ConsoleWidth - winnerMessage.Length) / 2, ConsoleHeight / 2); Console.Write(string.Empty.PadRight(winnerMessage.Length)); // 제목행 지우기 SetPositionWriteChar(Padding, 1, $"{string.Empty.PadRight(ConsoleWidth - Padding)}"); Score = 0; Shuttings = 0; Console.SetCursorPosition((ConsoleWidth - winnerMessage.Length) / 2, ConsoleHeight / 2); Console.Write(string.Empty.PadRight(winnerMessage.Length)); // 적 좌표 초기화 enemys = new Point[EnemyCount]; // 적 생성 (중복위치 발생시 다시 생성 루핑) bool check = true; do { if (enemys?.Length > 0) for (int i = 0; i < enemys.Length; i++) SetPositionWriteChar(this[i].X, this[i].Y, string.Empty.PadLeft(1)); for (int i = 0; i < enemys?.Length; i++) this[i] = new Point(random.Next(Padding + 15, Console.BufferWidth - Padding * 2 - 15), random.Next(5, 15)); check = enemys.GroupBy(x => x).Any(g => g.Count() > 1); } while (check); // 플레이어 위치 초기화 SetPositionWriteChar(playerX, playerY, string.Empty.PadLeft(1)); // 플레이어 중앙에 위치시키기 PlayerX = Console.BufferWidth / 2; // 게임플레이 Play(); } /// <summary> /// Enemy Auto Movement /// </summary> public async void MoveEnemys() { // 승리 요건 발생 전까지 루프 while (Score < winnerScore) { for (int i = 0; i < enemys.Length; i++) { if (this[i].X == Padding + 4) // 왼쪽벽에 닿았을 때 { SetPositionWriteChar(this[i].X, this[i].Y, string.Empty.PadRight(1)); this[i] = new Point(ConsoleWidth - Padding - 4, this[i].Y); } else // 정상범위에서 움직임 { SetPositionWriteChar(this[i].X, this[i].Y, string.Empty.PadRight(1)); this[i] = new Point(this[i].X - 1, this[i].Y); } } // 적 이동속도 (작을 수록 빠른 속도) // 플레이어 움직임과 적 움직임의 비동기 처리 (핵심)로 프리징 현상 방지 // await 구문을 만나는 순간 제어권을 플레이어에게 넘어가고 // 0.5 초 시간 딜레이도 유지하기 await Task.Delay(500); } // 승리 후 적 일시에 모두 지우기 (병렬처리로 순서에 관계없이 빠르게 삭제) Parallel.ForEach(enemys, x => RemoveEnemyTrace(x.X, x.Y)); }

4. GamePlay ( 4 / )

/// <summary> /// Play /// </summary> public void Play() { Console.CursorVisible = false; MoveEnemys(); bool run = true; do { var input = Console.ReadKey(true); switch (input.Key) { case ConsoleKey.R: InitStage(); break; case ConsoleKey.LeftArrow: PlayerX--; break; case ConsoleKey.RightArrow: PlayerX++; break; case ConsoleKey.Spacebar: Shuttings++; PlaySound(0); while (true) { // 좌, 중, 우 기관단총 총알흔적 지우기 RemoveBulletTrace(Bullet.Y == PlayerY ? 0 : 1); // 좌, 중, 우 미사일 디자인 SetPositionWriteChar(Bullet.X - 1, Bullet.Y, "_"); SetPositionWriteChar(Bullet.X, Bullet.Y, "|"); SetPositionWriteChar(Bullet.X + 1, Bullet.Y, "_"); // 총알 움직임 bullet.Y--; // 총알 속도 Thread.Sleep(30); for (int i = 0; i < enemys.Length; i++) { // 충돌확인하기 if (this[i] != new Point(Bullet.X - 1, Bullet.Y) && this[i] != new Point(Bullet.X, Bullet.Y) && this[i] != new Point(Bullet.X + 1, Bullet.Y)) continue; // 총알에 맞아 죽은 Enenmy // 삭제를 위한 적 좌표 임시 저장 변수 // 아래 Enenmy 지우기 용도 int px = this[i].X; int py = this[i].Y; // 요격된 Enemy 지우기 RemoveaDestroyedEnemy(px, py); lock (obj) { // 동시에 두마리 잡았을 때 데이터 보호 Score++; // 점수올리기 } // 충돌힌 Bullet 지우기 RemoveBulletTrace(Bullet.X, Bullet.Y + 1); // 죽어서 지워진 Enenmy 다시 부활시키기 Point newPosition = default; bool exist = true; // 랜덤함수가 기존 살아있는 적 좌표와 동일한지 여부 저장 변수 while (exist) { // 기존의 Enenmy 위치와 중복되지 않도록 유니크 할 때 까지 루핑 // random.Next(Padding + 15, Console.BufferWidth - Padding * 2 - 15) // newPosition = new Point(random.Next(10, 60), random.Next(5, 15)); newPosition = new Point(random.Next(Padding + 15, Console.BufferWidth - Padding * 2 - 15), random.Next(5, 15)); exist = enemys.Any(x => x == newPosition); } // Enenmy 부활 this[i] = newPosition; // Enenmy 를 맞춘 Bullet 을 더이상 진행하지 않토록 초기화 bullet.Y = Padding; break; } // Bullet.Y 위치가 Padding 값고 같아지면 (즉, 최상단에 도달하면) // 더 진행을 중지하고 Player 발사위치로 원위치 시키기 if (Bullet.Y != Padding) continue; // 상단 마지막 총알 지우기 RemoveBulletTrace(1); // Bullet 위치를 Player 위치(-2 높은곳으로)로 ReLoad 짤칵... bullet.Y = playerY - 2; break; } break; default: run = false; break; } } while (run); }

5. GamePlay ( 5 / )

private void SetPositionWriteChar(int left, int top, string ch, ConsoleColor color = ConsoleColor.White) { lock (obj) { Console.SetCursorPosition(left, top); Console.Write(ch); Console.ForegroundColor = color; } } private void RemoveBulletTrace(int offset) { lock (obj) { Console.SetCursorPosition(Bullet.X - 1, Bullet.Y + offset); //마지막 총알 자국 지워줌 Console.Write(string.Empty.PadRight(2)); Console.SetCursorPosition(Bullet.X + 1, Bullet.Y + offset); //마지막 총알 자국 지워줌 Console.Write(string.Empty.PadLeft(1)); } } private void RemoveBulletTrace(int x, int y) { lock (obj) { Console.SetCursorPosition(x - 1, y); // 좌 충돌 총알 자국 지워줌 Console.Write(string.Empty.PadRight(2)); Console.SetCursorPosition(x + 1, y); // 우 충돌 총알 자국 지워줌 Console.Write(string.Empty.PadLeft(1)); } } private void RemovePlayerTrace(int x, int y) { lock (obj) { Console.SetCursorPosition(x - 1, y); Console.Write(string.Empty.PadRight(3)); } } private void RemoveEnemyTrace(int x, int y) { lock (obj) { Console.SetCursorPosition(x, y); Console.Write(string.Empty.PadLeft(1)); Console.Write(string.Empty.PadRight(1)); } } private void RemoveaDestroyedEnemy(int x, int y) { PlaySound(1); lock (this) { Console.SetCursorPosition(x, y); Console.Write(string.Empty.PadLeft(1)); Console.Write(string.Empty.PadRight(1)); } } /// <summary> /// 총알발사 및 적 요격시 사운드 /// 프로젝트의 Resource 에 등록필 /// </summary> /// <param name="div"></param> private void PlaySound(int div) { switch (div) { case 0: using (var stream = Resources.shutting) { SoundPlayer player = new SoundPlayer(stream); player.Load(); player.Play(); } break; case 1: using (var stream = Resources.beep_02) { SoundPlayer player = new SoundPlayer(stream); player.Load(); player.Play(); } break; } } } #endregion

6. 외곽선 그리기

#region 외곽선 그리기 public class DrawOutline { private readonly int width; private readonly int height; private readonly List<Point> allPoints = new List<Point>(); private readonly List<Point> wallPoints = new List<Point>(); public DrawOutline(int width, int height) { this.width = width; this.height = height; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { allPoints.Add(new Point(i, j)); } } } public void DrawOutLine(int padding) { Console.CursorVisible = false; try { foreach (Point point in allPoints) { Console.SetCursorPosition(point.X, point.Y); if ((point.Y == padding && point.X >= padding && point.X <= width - padding) // 상변 || (point.Y == height - padding && point.X >= padding && point.X <= width - padding) // 하변 || (point.X == padding && point.Y >= padding && point.Y <= height - padding) // 좌변 || (point.X == width - padding && point.Y >= padding && point.Y <= height - padding)) // 우변 { wallPoints.Add(point); } } foreach (Point point in wallPoints) { Console.SetCursorPosition(point.X, point.Y); Console.Write(@"*"); } } catch (Exception) { // } } } #endregion

7. 콘솔창 크기 및 위치 설정 ( 7 / )

#region 콘솔창 크기 및 위치설정 유틸리티 public static class WindowUtility { [DllImport("user32.dll", SetLastError = true)] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); private const uint SWP_NOSIZE = 0x0001; private const uint SWP_NOZORDER = 0x0004; private static Size GetScreenSize() => new Size(GetSystemMetrics(0), GetSystemMetrics(1)); private struct Size { public int Width { get; } public int Height { get; } public Size(int width, int height) { Width = width; Height = height; } } [DllImport("User32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] private static extern int GetSystemMetrics(int nIndex); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetWindowRect(HandleRef hWnd, out Rect lpRect); [StructLayout(LayoutKind.Sequential)] private struct Rect { public readonly int Left; public readonly int Top; public readonly int Right; public readonly int Bottom; } private static Size GetWindowSize(IntPtr window) { if (!GetWindowRect(new HandleRef(null, window), out Rect rect)) throw new Exception("콘솔창 핸들 찾기에 실패하였습니다."); int width = rect.Right - rect.Left; int height = rect.Bottom - rect.Top; return new Size(width, height); } /// <summary> /// 콘솔창 중앙에 배치 /// </summary> public static void MoveWindowToCenter() { IntPtr window = Process.GetCurrentProcess().MainWindowHandle; if (window == IntPtr.Zero) throw new Exception(@"콘솔창을 발견할 수 없습니다."); Size screenSize = GetScreenSize(); Size windowSize = GetWindowSize(window); int x = (screenSize.Width - windowSize.Width) / 2; int y = (screenSize.Height - windowSize.Height) / 2; SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } /// <summary> /// 콘솔창 전체화 /// </summary> public static void WindowToFullScreen() { IntPtr window = Process.GetCurrentProcess().MainWindowHandle; if (window == IntPtr.Zero) throw new Exception(@"콘솔창을 발견할 수 없습니다."); Size screenSize = GetScreenSize(); Size windowSize = GetWindowSize(window); int x = (screenSize.Width - windowSize.Width) / 2; int y = 0; SetWindowPos(window, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER); } } #endregion

이상입니다.

즐거운 명절 되셔요!!!

자바로 게임 만들 때 충돌처리

... 숙제로 총알을 발사하여 위쪽에 움직이는 적을 없애라는걸... 자바의 충돌처리와 배열에 대해서 자세히 좀 설명해주세요 ㅠㅠ 적과 주인공을 만들고 주인공이 총알을 발사...

2035년 ㅠㅠ ..

... 만약 이거 충돌하면 어떻게 되나요 //?? 지구 온도... 진짜 싫어요 ㅠㅠ 북한땜에 우리 다 죽게 생겼는데 ㅠㅠ... 그 총알보다 빠르게움직이는 지구를 소행성같이...

상지대 면접 문제..(급함ㅠㅠ)

... 나오나요??ㅠㅠ 지원동기나 자기소개 그런것도... 권리가 충돌하는 경우이다. 이에 대한 자신의 견해를... 이를 구현하는 기술인 가상현실(virtual reality)과 증강현실...

인상깊었던 구절이나 명언 제발요ㅠㅠ

제가 개학이 월요일인데 ㅠㅠ 독서구절을 10개... 구호 전쟁을 하려면 사랑의 총알이 필요하다. 구호 자금이... 나는 사람은 힘으로 움직이는 것이 아니라 진심과 감동으로...

사주풀이좀부탁드려요ㅠㅠ

알려주세요ㅠㅠ직업이특히궁금하네요 인생은 너무나... ‘나’가 강한 사주는 주변과 충돌하기 때문에 ‘나’를... 춤이나 음악, 스포츠가 아니라 언어를 통해 진리를 구현하...

주문 한글로 모두 적어주세요ㅠㅠ 내공500

친구랑 해리포터 주문 대결중 인데 한글로 가장 많이 적어주시면 내공500ㅠㅠ 가뭄... 위즐리 쌍둥이가 어릴 론 위즐리에게 이 맹세를 시키려고 했는데, 그 광경을...