행맨 게임
using System;
using System.Linq;
namespace ConsoleApp1
{
public class program
{
/// <summary>
/// secretWord: 맞춰야 할 단어. 초기값 "hangman"
///guessWord: 사용자가 맞춘 문자를 저장하는 문자 배열, 초기값 언더스코어(_)
///attempts: 도전기회, 초기값 6
///wordGuessed: 모든 단어를 맞췄는지 여부
/// </summary>
public static void Main()
{
char[] secretWord = "hangman".ToCharArray();
char[] guessWord = new char[secretWord.Length].Select(x=> x ='_').ToArray();
bool wordGuessed = false;
int attempts = 6;
do
{
char curInput = (char)Console.Read();
if (curInput == '\n'|| curInput == '\r') continue;//\r \n 커서포인터 예외처리
bool curRight = false;
guessWord = secretWord.Select((x,idx) =>
{
if (x == curInput) curRight = true;
return x == curInput ? curInput : guessWord[idx]; }).ToArray();
if (!curRight) --attempts;
ClearAndPrint(guessWord, attempts, curInput);
wordGuessed = Enumerable.SequenceEqual(guessWord, secretWord);
} while (!wordGuessed && attempts > 0);
Console.WriteLine(wordGuessed ? "정답입니다!" : "모든 기회를 소진했습니다.");
}
public static void ClearAndPrint(char[] guessWord,int attempts,char curInput)
{
Console.WriteLine(new string(guessWord));
Console.WriteLine($"마지막 입력 { curInput} , 남은 도전 횟수{attempts}");
}
}
}
야구게임
using System;
using System.Linq;
namespace ConsoleApp1
{
public class program
{
public static void Main()
{
bool guessedCorrectly = false;
string targetNumber = new Random().Next(100, 1000).ToString();
int attempts = 0;
do
{
char[] userGuess = Console.ReadLine().ToArray();
attempts++;
if (userGuess.Length != targetNumber.Length)
{
Console.WriteLine("3자리수 숫자를 입력해 주십시오.");
continue;
}
byte strikes = 0;
byte balls = 0;
for (int i = 0; i < targetNumber.Length; i++)
{
if(targetNumber[i] != userGuess[i])
{
if (targetNumber.Contains(userGuess[i])) balls++;
}
else
{
++strikes;
}
}
Console.WriteLine($"{strikes} Strike(s), {balls} Ball(s)");
if (strikes == targetNumber.Length) guessedCorrectly = true;
} while (!guessedCorrectly);
Console.WriteLine($"Congratulations! You've guessed the number in {attempts} attempts.");
}
}
- 오늘 학습 키워드
- 오늘 학습 한 내용을 나만의 언어로 정리하기
- Console의 read함수는 앞에 하나가 아니라 한글자씩 가져온단걸 알았다
- 그렇기에 행맨게임 코드를 짤때 검출되었던 이스케이프 문자로 인해 예상치 못한 예외가 발생하였었다.
- 학습하며 겪었던 문제점 & 에러
- 문제&에러에 대한 정의
- Console.Write에서 검출되었던 이스케이프 문자로 인해 예상치 못한 예외가 발생하였다.
- 내가 한 시도와 해결 방법
- 나올 수 있는 예외가 한정되어 있기에 if문으로 해결하였다.
- 새롭게 알게 된 점
- 어제 학습하였던 read개념을 복습하여 제대로 알게 된 것 같다. 입력한 문자열의 한글자씩 떼어서 가져온단것을 제대로 알게 되었다.
- 이 문제&에러를 다시 만나게 되었다면?
- WriteLine함수를 사용하거나 해당 이스케이프 문자를 따로 처리하는 방안이 좋을 것 같다.
- 다음 학습 할 것은 무엇인지
- 기획과제가 있어서 오늘중으로 끝내고 내일은 인강 과제부터 끝낼 것 같다.