사용자로부터 알파벳을 입력 받아 숨겨진 단어를 맞추는 게임 프로그램을 작성하였다. 사용자가 단어의 모든 문자를 맞추거나 주어진 기회 내에 맞추지 못할 때까지 반복한다.
/*
7. 행맨 게임
string secretWord = 숨겨진 단어;
char[] guessWord = {'_' , '_' , '_' , ... , '_'); 단어길이만큼 '_'
int attempts = secretWord.Length;
bool wordGuessed = false;
while(attempts > 0) 남은 시도가 0보다 클 때 반복
{
Console.WriteLine(guessWord); _______ / _a___a_
Console.WriteLine(남은시도);
Console.Write(알파벳 입력);
string input = Console.ReadLine();
input의 길이가 1개가 아닐때는 다시 입력받기
{
Console.WriteLine(한 개의 알파벳을 입력해주세요.)
input = Console.ReadLine();
}
입력을 받으면 attempts --;
input.ToLower();로 소문자로 만들기
char alphabet = char.Parse(input);
for (i < secretWord.Length)
{
secretWord[i] == alphabet 일 때,
guessWord[i] = alphabet
}
사용자가 입력하여 만들어진 문자열이 secretWord와 같을 때,
{
wordGuessed = true;
break;
{
}
반복문이 끝나면 wordGuessed를 확인해서 결과 표시
*/
using System;
using System.Linq;
{
string secretWord = "hangman";
char[] guessWord = Enumerable.Repeat('_', secretWord.Length).ToArray();
/*
char[] guessWord2 = new char[secretWord.Length];
for (int i = 0; i < secretWord.Length; i++)
{
guessWord2[i] = '_';
}
char[] guessWord3 = new char[secretWord.Length];
Array.Fill(guessWord3, '_');
*/
// Array에 같은 값을 넣는 방법 3가지
int attempts = secretWord.Length;
bool wordGuessed = false;
Console.WriteLine($"SecretWord length: {secretWord.Length}");
Console.WriteLine($"Attempts: {attempts}");
while (attempts > 0)
{
Console.WriteLine();
Console.WriteLine("GuessWord: " + string.Join("", guessWord));
Console.WriteLine($"Remain attempts: {attempts}");
Console.Write("Enter an alphabet: ");
string input = Console.ReadLine();
while(input.Length != 1)
{
Console.Write("Please enter just one alphabet: ");
input = Console.ReadLine();
}
attempts--;
input = input.ToLower();
char alphabet = char.Parse(input);
for (int i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == alphabet)
{
guessWord[i] = alphabet;
}
}
string inputWord = new string(guessWord);
if (inputWord == secretWord)
{
wordGuessed = true;
break;
}
}
if (wordGuessed)
{
Console.WriteLine("Success! You guessed word!");
Console.WriteLine($"Word: {secretWord}");
}
else
{
Console.WriteLine("Failed... Try again?");
}
}