숫자 야구 게임 설명
숫자 야구 게임은 3자리의 숫자를 맞추는 게임입니다. 컴퓨터가 고른 3자리 숫자는 모두 다른 숫자로 이루어져 있습니다. 사용자는 3자리 숫자를 입력하고, 컴퓨터는 입력한 숫자와 자리수를 비교하여 스트라이크와 볼의 개수를 알려줍니다.
스트라이크: 숫자와 자리수가 모두 맞는 경우
볼: 숫자는 맞지만 자리수가 다른 경우
예를 들어, 컴퓨터가 427을 선택하고 사용자가 123을 입력했을 때, 2는 맞지만 자리수가 다르므로 1볼, 1은 맞지 않으므로 0스트라이크입니다. 이 과정은 사용자가 정확한 숫자를 맞출 때까지 반복됩니다.
targetNumber
: 컴퓨터가 선택한 3자리의 숫자를 저장하는 배열입니다.userGuess
: 사용자가 추측한 숫자를 저장하는 배열입니다.strikes
: 자릿수와 숫자가 모두 맞는 경우의 개수를 저장합니다.balls
: 자릿수는 맞지 않지만 숫자가 포함된 경우의 개수를 저장합니다.guessedCorrectly
: 사용자가 숫자를 정확히 맞췄는지를 나타내는 불리언 변수입니다. Random random = new Random();
string targetNumber;
string userGuess;
int strikes = 0;
int balls = 0;
int attempts = 0;
int[] strike = new int[3];
int[] ball = new int[3];
bool guessedCorrectly = true;
targetNumber = random.Next(100,1000).ToString();
while (guessedCorrectly)
{
strikes = 0;
balls = 0;
Console.Write("Enter your guess (3 digits): ");
userGuess = Console.ReadLine();
for (int i = 0; i < 3; i++)
{
if (targetNumber[i] == userGuess[i])
{
strikes++;
strike[i] = 1;
continue;
}
else
{
for (int j = strikes; j < 3; j++)
{
if (strike[i] != 1&& ball[j] != 1 && targetNumber[i] == userGuess[j])
{
balls++;
ball[j] = 1;
}
}
}
}
Console.WriteLine(strikes + " Strike(s), " + balls + " Ball(s)");
attempts++;
if (strikes == 3)
{
Console.WriteLine("Congratulations! You've guessed the number in " + attempts + " attempts.");
guessedCorrectly = false;