Creative Code

baseball.c(숫자 야구게임) 본문

C Programming

baseball.c(숫자 야구게임)

빛하루 2023. 8. 2. 12:32
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
	srand(time(NULL));
	int question[3];
	while(1){ // 정답이 unique하게 3개 생성될 때 까지 생성
		for (int i = 0; i<3; i++){
			question[i] = rand()%10 +1;
		}
		if (question[0] != question[1] && question[1] != question[2] && question[0] != question[2]){
			break;
		}
	}
	
	int count = 1; // 시도 횟수
	while (1) {
		int strike = 0;   // strike의 갯수
		int ball = 0;     // ball 의 갯수
		
		int answer[3];
		printf("정답 입력: ");        // 사용자에게 숫자 입력 받기
		for (int i = 0; i<3; i++){
			scanf("%d",&answer[i]);
		}
		
		for (int i = 0; i<3; i++){                 // 사용자로부터 입력받은 숫자중 숫자가 포함되는 것의 갯수
			for (int j = 0; j<3; j++){
				if (answer[i] == question[j]){
					ball++;
				}
			}
		}                    
		
		for (int i = 0; i<3; i++){                 // 숫자와 위치가 정확하게 일치하는 것의 갯수( ball갯수에 포함되므로 그만큼 빼주기)
			if (answer[i] == question[i]){
				strike++;
				ball--;
			}
		}
		printf("strike : %d , ball : %d  ----- %d 번째 도전\n",strike,ball,count);  // 결과 출력
		printf("\n");
		
		if (strike == 3) {    // strike가 3개면 while문 빠져나가기
			printf("정답입니다!\n");
			break;
		}
		
		count++;   // 시도 횟수 +1
	}	
	return 0;
}