[내일배움캠프] 달리기반 Quest8 (숫자 야구 게임)

Dreamer·2024년 9월 4일

8. 숫자 야구 게임

Quest7과 동일하게 원래는 팀 미션으로 출제된건데 사전캠프 기간도 얼마 안남았고 각자 해야할 미션들이 아직 남은듯 하여 혼자서 작성하게 되었다.

해당 게임은 중복없는 숫자를 주어진 자릿수 만큼(기본 3자리) 뽑아서 targetNumber에 저장하게되면 사용자가 이를 맞추는 게임이다.
숫자가 정해지면 사용자는 아무 숫자나 3자리를 입력하고
입력받은 숫자중에 하나의 숫자가 targetNumber에 해당하는 자리와 숫자 모두 일치하면 strikes 를 1 증가 시킨다.
입력받은 숫자중에 하나의 숫자가 targetNumber에 포함된 숫자라면 balls 를 1 증가 시킨다.
3 strikes가 되면 게임은 종료된다.
게임이 종료되면 몇번의 시도로 성공했는지도 알려준다.

public class Quest8
{
    /// <summary>
    ///  랜덤한 숫자를 뽑기 위한 Random 객체
    /// </summary>
    Random rand = new Random();
    /// <summary>
    /// 랜덤으로 length만큼 겹치지 않는 숫자를 뽑는다.
    /// 결과를 char[] 배열로 반환하는 이유는 사용자 입력 값이 기본 string이기 때문에 파싱하지 않기 위함이다.
    /// </summary>
    /// <param name="length">길이</param>
    /// <returns>생성한 숫자를 char[] 로 바꿔서 반환</returns>
    char[] GetTargetNumbers(int length)
    {
        // 주어진 length 만큼 숫자를 하나씩 겹치지 않게 뽑는다.
        int[] numbers = new int[length];
        int count = 0;
        while(count < length)
        {
            int num = rand.Next(1, 10);
            if (numbers.Contains(num)) continue;
            numbers[count] = num;
            count++;
        }

        // 뽑은 숫자들을 char형으로 반환한다.
        return string.Join("", numbers).ToCharArray();
    }

    public void Run(int length = 3)
    {
    	if(length > 9)
		{
    		Console.WriteLine("Please enter a number less than 10.");
    		return;
		}
        Console.WriteLine("---8. 숫자 야구 게임");
        // 찾아야할 숫자
        char[] targetNumber = GetTargetNumbers(length);
        // 사용자가 입력한 숫자
        char[] userGuess;
        // 시도 횟수
        int attempts = 0;
        // 스트라이크 수
        int strikes = 0;
        // 볼 수
        int balls = 0;
        // 사용자가 숫자를 맞췄는지 여부
        bool guessedCorrectly = false;
        while (true)
        {
            // 매 시도마다 스트라이크, 볼 수 초기화
            strikes = 0; balls = 0;
            Console.Write($"Enter your guess ({length} digits): ");
            // 숫자 length 자리 만큼 입력을 받는다.
            string input = Console.ReadLine();
            // 자리수가 다르면 다시 입력 받는다.
            if (input.Length != length)
            {
                Console.WriteLine($"Please enter a {length}-digit number.");
                continue;
            }
            // 입력받았다면 시도횟수를 증가시키고, 입력받은 숫자를 char 배열로 변환한다.
            attempts++;
            userGuess = input.ToCharArray();

            for (int i = 0; i < userGuess.Length; i++)
            {
                // 같은 위치의 숫자가 같다면 스트라이크 수를 증가시키고, 아니라면 볼 수를 증가시킨다.
                if (userGuess[i] == targetNumber[i])
                    guessedCorrectly = ++strikes == length; // 여기서 스트라이크가 length만큼 증가 했다면 guessedCorrectly를 true로 변경한다.
                else if (targetNumber.Contains(userGuess[i]))
                    balls++;
            }
            // 게임 현황을 표시해준다.
            // 디테일을 살려 게임 현황의 색깔을 바꿔보았다.
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write($"{strikes} Strike(s)");
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(", ");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.Write($"{balls} Ball(s)");
            Console.ForegroundColor = ConsoleColor.White;
            Console.WriteLine();

            // 최종적으로 guessedCorrectly가 true라면 게임을 종료하고 몇번의 시도가 있었는지 표시한다.
            if (guessedCorrectly)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine($"Congratulations! You've guessed the number in {attempts} attempts.");
                Console.ForegroundColor = ConsoleColor.White;
                break;
            }
        }
        Console.WriteLine("------------------------------");
    }
}
profile
새로운 시작

0개의 댓글