부트캠프/본캠프

[내일배움캠프_2025JUL06] C# 종합 프로그래밍 챕터 2

Young_A 2025. 7. 6. 22:34

목차

    C# 종합 프로그래밍 챕터 2

     

     

    오늘 건너뛰려다가~ 집에 일찍 도착해서 그냥 바로 PC를 켰다.

    C# 종합 프로그래밍 챕터2 (2주차)를 진행했다.

    강의 지급 받자마자 유데미 강의는 뒷전이 되었으므로.. 이틀만에 기존 유데미 강의의 진도를 넘었다! (애초에 많이 듣지도 않았음)

    앞으로는 캠프에서 지급 받은 강의를 기준으로 정리하고, 복습으로 유데미 강의를 들으며 보충할 것 같다.

    지금 살짝 후회되는 게, 한 게시글에 모든 내용을 넣으려고 하나...? 싶다. 목차 정리가 힘들다!

    게시글 나누는 기준은 유데미 강의 목차 기준으로 나눴다! Fundamental, Object-Oriented, Advanced로 나뉘게 된다.

    2025.07.01 - [부트캠프/개인학습] - C# 프로그래밍 기초

     

    C# 프로그래밍 기초

    팀원들 기다리거나, 애매하게 남은 시간을 활용하기 위해 예전에 구매해놓고 완강하지 못한 강의를 동시에 진행하려고 한다.https://www.udemy.com/course/the-complete-c-sharp-developer-course/?couponCode=24T4MT30062

    j000.tistory.com

    3항 연산자, 반복문들(for, while, do-while, foreach, 중첩 반복문), break, continue, 배열, 컬렉션, 배열과 리스트 비교 항목을 학습했다.

    또한 이후의 내용은 기초보다는 객체 지향 프로그래밍에 적합한 것 같아 새 글을 팠다.

    2025.07.06 - [부트캠프/개인학습] - C# 객체 지향 프로그래밍

     

    C# 객체 지향 프로그래밍

    2025.07.01 - [부트캠프/개인학습] - C# 프로그래밍 기초 C# 프로그래밍 기초팀원들 기다리거나, 애매하게 남은 시간을 활용하기 위해 예전에 구매해놓고 완강하지 못한 강의를 동시에 진행하려고 한

    j000.tistory.com

    메서드(Method), 구조체(struct)를 학습했다.

    메서드를 자꾸 메소드라고 하게 된다ㅋㅋ


    C# 종합 프로그래밍 챕터2 숙제

    숫자 맞추기 게임 만들기

    public void Assignment1()
    {
        //숫자 맞추기 게임 만들기
        //자체룰: 틀렸을 때, up, down 힌트를 준다.
        //       결과가 끝난 후 시도 횟수를 받는다.
        Random random = new Random();
        int randomNumber = random.Next(1, 101);
        int userInput;
        int count = 0;
        do
        {
            Console.WriteLine("숫자를 입력해주세요. (1 ~ 100)");
            userInput = GetInteger();
            if(randomNumber > userInput)
            {
                Console.WriteLine("up!");
            }
            else
            {
                Console.WriteLine("down!");
            }
            count++;
        } while(randomNumber != userInput);
    
        Console.WriteLine($"{count}번 만에 성공했습니다.");
    }
    
    static int GetInteger()
    {
        bool isSuccessful = false;
        int integer;
    
        do
        {
            string input = Console.ReadLine();
            isSuccessful = int.TryParse(input, out integer);
            if (!isSuccessful)
            {
                Console.WriteLine("숫자(정수)만 입력해주세요.");
            }
        } while (!isSuccessful);
        return integer;
    }

     

    틱택토 게임 만들기

    우승 조건을 x, y를 이용해서 체크하고 싶었는데, 일단은 그냥 하드 코딩으로 넣었다.

    //보드 상황: 유저(O)와 컴퓨터(X)가 둔 말의 위치
    static string[] board = new string[9];
    
    //좌표
    static int[] coordinateX = { 0, 1, 2 };    //왼쪽부터
    static int[] coordinateY = { 0, 1, 2 };    //윗쪽부터
    public void Assignment2()
    {
        //틱택토 게임 만들기
        int userInput = 0;
    
        //보드 초기화
        int printIndex = 0;
        foreach (int x in coordinateX)
        {
            foreach (int y in coordinateY)
            {
                board[printIndex++] = ((x * 3) + (y + 1)).ToString();
            }
        }
    
        //유저 입력 받기. 1~9 숫자 중에 점유당하지 않은 숫자만 선택 가능.
        bool isEnd = false;
        bool isUsersTurn = true;
        bool isPlayerWin = false;
        Random random = new Random();
        do
        {
            PrintBoard();
            if (isUsersTurn)    //유저 턴
            {
                Console.WriteLine("상단의 보드에서 원하는 좌표를 선택해주세요.");
                userInput = GetInteger();
                if (IsValidCoordinate(userInput))
                {
                    Console.WriteLine($"당신은 {userInput}을 점유했습니다.");
                    board[userInput - 1] = "*";   //유저가 점유함.
                    isUsersTurn = false;
                }
                else
                {
                    Console.WriteLine($"{userInput}은 이미 점유된 좌표입니다.");
                    continue;
                }
            }
            else    //컴퓨터 턴
            {
                Console.WriteLine("컴퓨터의 차례입니다...");
                bool isValid = false;
                do
                {
                    int computerInput = random.Next(1, 10);
                    isValid = IsValidCoordinate(computerInput);
                    if (isValid)
                    {
                        Console.WriteLine($"컴퓨터가 {computerInput}을 점유했습니다.");
                        board[computerInput - 1] = "X";
                    }
                } while (!isValid);
                isUsersTurn = true;
            }
            isEnd = IsGameEnd(out isPlayerWin);
        } while (!isEnd);
    
        PrintBoard();
        if (isPlayerWin)
        {
            Console.WriteLine("축하합니다! 승리했습니다!");
        }
        else
        {
            Console.WriteLine("저런, 컴퓨터가 이겼습니다.");
        }
    }
    static int GetInteger()
    {
        bool isSuccessful = false;
        int integer;
    
        do
        {
            string input = Console.ReadLine();
            isSuccessful = int.TryParse(input, out integer);
            if (!isSuccessful)
            {
                Console.WriteLine("숫자(정수)만 입력해주세요.");
            }
        } while (!isSuccessful);
        return integer;
    }
    static void PrintBoard()
    {
        //출력하기 (좌표): 각 좌표별 인덱스 (x * 3) + (y + 1)
        //---------------------------
        //| 1, 1 | 1, 2 | 1, 3 |    
        //---------------------------
        //| 2, 1 | 2, 2 | 2, 3 |
        //---------------------------
        //| 3, 1 | 3, 2 | 3, 3 |
        //---------------------------
    
        int printIndex = 0;
        Console.WriteLine("\nYour tokens: *\nComputer's tokens: X");
        Console.WriteLine("\n--------------------");
    
    
        foreach (int x in coordinateX)
        {
            Console.Write(" | ");
            foreach (int y in coordinateY)
            {
                Console.Write(board[printIndex++]);
                Console.Write("  |  ");
            }
            Console.WriteLine("\n--------------------");
        }
    
    }
    static bool IsValidCoordinate(int userInput)
    {
        bool isValid = false;
        if (userInput < 1 || userInput > 10)    //범위 바깥의 좌표 선택 시
        {
            Console.WriteLine("1-9 범위 내의 좌표를 선택하세요.");
        }
        else
        {
            // O이거나, X이면 false
            if (int.TryParse(board[userInput - 1], out int result))
            {
                isValid = true;
            }
            else
            {
                isValid = false;
            }
        }
        return isValid;
    }
    static bool IsGameEnd(out bool isPlayerWin)
    {
        int[][] winConditions = 
        {
            [0, 1, 2], // 가로
            [3, 4, 5],
            [6, 7, 8],
            [0, 3, 6], // 세로
            [1, 4, 7],
            [2, 5, 8],
            [0, 4, 8], // 대각선
            [2, 4, 6]
        };
        bool isEnd = false;
        string mark = "";
    
        foreach(int[] condition in winConditions)
        {
            string a = board[condition[0]];
            string b = board[condition[1]];
            string c = board[condition[2]];
            if (board[condition[0]] == board[condition[1]] && board[condition[1]] == board[condition[2]])
            {
                mark = board[condition[0]];
                isEnd = true;
            }
        }
        isPlayerWin = (mark == "*") ? true : false;
        return isEnd;
    }

     

    User wins

     

    Computer wins

    시간이 너무 지나서... 못하고 넘어가는 부분들

    foreach 2차원 배열일때 사용 복습

    무승부 처리 빠뜨림.

     

    TryParse out 없이 쓸 수 없는 점 자꾸 까먹는다...ㅠㅠ


    느낀점

    주말 공부.. 중독될 것 같다.


    내일 학습 할 것은 무엇인지

    내일 드디어 새 챕터 발제 및 팀 재편성이다.

    4주차까지 학습 후 TextRPG 진행하는게 목표!