Unity 개발 일지/달리기반 퀘스트

행맨 게임

ohty20012 2025. 4. 1. 18:54
  • 변수 선언에 대한 이해
  • 배열에 대한 이해
  • 조건문 ( if, else )에 대한 이해
  • 반복문 ( for, while )에 대한 이해
  • 데이터 타입과 문자열 처리

사용자로부터 문자를 입력받아 숨겨진 단어를 맞추는 행맨 게임을 작성하세요. 사용자가 단어의 모든 문자를 맞추거나 주어진 기회 내에 맞추지 못할 때까지 반복합니다.

  • 게임 설명 : 행맨 게임은 사용자가 단어를 추측하는 게임입니다. 사용자는 알파벳을 하나씩 입력하고, 맞출 때마다 단어의 해당 위치에 문자가 표시됩니다. 틀릴 경우, 기회가 줄어듭니다.
  • 배열 사용 : char[] 배열을 사용하여 단어를 저장하고, 추측된 문자를 저장합니다.
  • 반복문 사용 : 게임은 사용자가 단어를 맞추거나 기회가 끝날 때까지 반복됩니다.
  • 조건문 사용 : 각 입력된 문자가 단어에 포함되는 지 확인합니다.

사용 변수 설명

  • secretWord : 맞춰야 할 단어입니다. 예제에서는 "hangman"으로 설정되어 있습니다.
  • guessWord : 사용자가 맞춘 문자를 저장하는 문자 배열로, 초기에는 인더스코어( _ )로 채워져 있습니다.
  • attemts : 사용자가 틀릴 수 있는 기회의 수로, 초기에는 6으로 설정되어 있습니다.
  • wordGuessed : 사용자가 단어를 모두 맞췄는지를 나타내는 불리언 변수입니다.

 

 

< 코드 >

class Program {
    public static void Main() {
        string secretWord = "hangman";
        char[] guessWord = new char[secretWord.Length];
        for (int i = 0; i < guessWord.Length; i++) {
            guessWord[i] = '_';
        }
        int attempts = 6;
        int correct = 0;
        bool wordGuessed = false;
        string input;
        char inputchar;

        Console.WriteLine("안녕하세요 행맨 게임입니다. 단어를 맞추거나 Attempts가 0이되면 게임이 종료됩니다.\n");
        while (attempts != 0 && correct != secretWord.Length) {
            wordGuessed = false;

            Console.Write("Your guess : ");
            for (int i = 0; i < guessWord.Length; i++) {
                Console.Write(guessWord[i] + " ");
            }
            Console.Write(", Attempts : " + attempts);
            Console.Write("\nA 부터 Z 까지의 알파벳 중 하나를 입력하세요 : ");

            input = Console.ReadLine();
            if (!string.IsNullOrWhiteSpace(input)) {
                inputchar = input.ToLower()[0];
            } else {
                Console.WriteLine("공백 없이 문자를 입력해주세요");
                Console.WriteLine("--------------------------------------------------------------------------------------");
                continue;
            }

            for (int i = 0; i < secretWord.Length; i++) {
                if (inputchar == secretWord[i]) {
                    wordGuessed = true;
                    if (guessWord[i] == '_'){
                        guessWord[i] = inputchar;
                        correct++;
                    }
                }
            }

            if (wordGuessed) {
                Console.WriteLine("Correct!");
            } else {
                attempts--;
                Console.WriteLine("Wrong XD");
            }
            Console.WriteLine("--------------------------------------------------------------------------------------");
        }

        if (attempts == 0) Console.WriteLine("You Lose :(");
        else Console.WriteLine("You Win!! :)");
        Console.WriteLine("The Answer Is " + secretWord);
        Console.WriteLine("======================================================================================");
    }
}

 

 

 

< 결과 >

 

 

 

 

< 해설 >

    string secretWord = "hangman";  // 사용자가 맞춰야 할 단어
    
    // 현재 추측 중인 단어배열
    char[] guessWord = new char[secretWord.Length];
    for (int i = 0; i < guessWord.Length; i++) {
        guessWord[i] = '_';
    }
    
    int attempts = 6;  // 사용자가 틀릴 수 있는 횟수
    int correct = 0;   // 사용자가 맞춘 단어의 갯수
    bool wordGuessed = false;  // 사용자가 입력한 알파벳이 단어에 있는지 체크
    
    //사용자가 입력한 알파벳을 저장할 변수들
    string input;
    char inputchar;
  • secretWord의 길이 만큼 문자 배열 guessWord를 생성하고, guessWord를 인더스 코어 ( _ )로 초기화
  • ReadLine의 반환형은 string이기 때문에, input에 할당하고, 그 후 inputchar로 옮김

 

    while (attempts != 0 && correct != secretWord.Length) {
        wordGuessed = false;
        
        Console.Write("Your guess : ");
        for (int i = 0; i < guessWord.Length; i++) {
            Console.Write(guessWord[i] + " ");
        }
        Console.Write(", Attempts : " + attempts);
        Console.Write("\nA 부터 Z 까지의 알파벳 중 하나를 입력하세요 : ");
  • 사용자가 맞출 수 있는 횟수 ( attempts )가 0이 되거나, 단어의 모든 문자를 맞추면 게임 종료
  • 사용자가 현재 맞춘 단어와 맞출 수 있는 횟수를 표기

 

    input = Console.ReadLine();
    if (!string.IsNullOrWhiteSpace(input)) {
        inputchar = input.ToLower()[0];
    } else {
        Console.WriteLine("공백 없이 문자를 입력해주세요");
        Console.WriteLine("--------------------------------------------");
        continue;
    }
  • inputchar = Console.ReadLine()[0] 을 사용할 수 있지만, 입력이 공백일 경우 오류가 발생하기 때문에, 예외 처리
  • 입력이 공백일 경우 continue 함수를 사용해서 루프의 처음으로 복귀
  • ToLower 메서드를 사용해서 입력이 대문자일 경우 자동으로 소문자로 변경해서 비교

 

    for (int i = 0; i < secretWord.Length; i++) {
        if (inputchar == secretWord[i]) {
            wordGuessed = true;
            if (guessWord[i] == '_'){
                guessWord[i] = inputchar;
                correct++;
            }
        }
    }
    if (wordGuessed) {
        Console.WriteLine("Correct!");
    } else {
        attempts--;
        Console.WriteLine("Wrong XD");
    }
    Console.WriteLine("-----------------------------");
  • secretWord와 입력받은 알파벳을 비교
  • secretWord에 입력받은 값이 있을 경우, 그 갯수만큼 correct를 증가시키고, wordGuessed를 true로 변경
  • 틀렸을 경우, attemts값을 1 감소시킴
  • 맞췄는지 못맞췄는지 판별하게 사용자에게 출력

 

    if (attempts == 0) Console.WriteLine("You Lose :(");
    else Console.WriteLine("You Win!! :)");
    Console.WriteLine("The Answer Is " + secretWord);
    Console.WriteLine("=======================================================");
  • attempts가 0이되거나, 사용자가 단어를 모두 맞춰서 correct가 단어의 길이만큼 될 경우 게임 종료
  • attempts를 통해 게임의 승패를 판별하여 출력

 

 

< string.IsNullOrWhiteSpace( value ) >

  • string 변수 value 가 null, " ", "\t", "\n" 처럼 오로지 공백 문자로만 이루어져 있는지 판별하는 메서드
  • 비어있을 경우 true, 아니면 false 반환

 

< To.Lower() >

  • 문자열뒤에 붙여서 문자열을 소문자로 바꿔서 반환
  • 원본 문자열은 변경되지 않음 (다른 변수에 추가로 할당해 줘야함)

 

< continue >

  • 반복문 안에서 사용
  • continue를 만나면 밑에 코드를 무시하고 맨 위로 올라간다