부트캠프/Unity [ 스파르타 ]

[팀원들과 함께] 행맨으로 페어 코딩

맏난거 2025. 1. 14. 18:01
/*
행맨

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

string secretWord = "hangman";

int attempts = 6; // 목숨 
Console.Write("사용자의 목숨을 입력해주세요 : ");
try{ attempts = Int32.Parse(Console.ReadLine()); }
catch { }


// 문자열의 길이를 가져와서 "_"로 출력해주기
char[] guessWord = new char[secretWord.Length];
bool[] boolWord = new bool[secretWord.Length];

for (int i = 0; i < guessWord.Length; i++)
    guessWord[i] = '_';

while (true)
{
    // 현재 단어를 보여지는 단계
    #region ShowCurrent

    Console.WriteLine($"현재 목숨 : {attempts}");
    foreach (char ch in guessWord)
    {
        Console.Write(ch);
        Console.Write(" ");
    }

    #endregion

    #region userInput

    Console.WriteLine("문자열로 입력시 앞글자를 빼서 확인");
    Console.WriteLine("문자를 입력해주세요 (문자열 x) : ");
    string c = Console.ReadLine().ToLower();

    char userInput = c[0]; // 사용자 입력 받아오기

    #endregion

    if(CheckWord(secretWord, userInput)) break;

    if (attempts <= 0) break;
}

if (attempts > 0)
    Console.Write("축하합니다.");
else
    Console.WriteLine("으악! 죽었다");

// 맞춰야되는 문자열과 사용자가 입력한 문자배열을 가져와서 맞춰보기
bool CheckWord(string str,char inputChar)
{
    bool isCheck = false;

    for(int i = 0; i < str.Length; i++)
    {
        if (str[i] == inputChar && boolWord[i] == false) // 사용자 입력한 값이 들어있으면
        {
            guessWord[i] = str[i]; // 채워넣기
            boolWord[i] = true;
            isCheck = true;
            break;
        }
    }

    bool checkWin = true;
    foreach (bool b in boolWord)
    {
        if (b == false)
        {
            checkWin = false;
            break;
        }
    }

    // 다 순회했을때 isCheck가 false면 목숨 하나 -1
    if(!isCheck) attempts--;

    return checkWin;
}

오늘 페어 코딩으로 작성한 코드입니다.

페어 코딩을 하면서 중요하게 느꼈던건 주석이 정말 좋다는걸 느꼈습니다.

누구 보는 앞에서 코드 시연할때 생각이 안나서 주석으로 차근차근 구현할려는 부분을 적어서 

작성을 했었습니다. 주석은 다른 프로그래머를 위해서 작성할 뿐만 아니라 나를 위한 부분도 있구나라는걸 

느꼈습니다.