본문 바로가기
C 언어

C 언어로 숫자 야구 게임 만들기

by treeCoder 2021. 7. 15.

C 언어로 숫자 야구 게임을 만들어 보았다.

 

#include <stdio.h>
#include <stdlib.h> 
#include <time.h>

int main() {

    int num[3];
    int set[3];
    int cnt = 0;
    int s =0; int b =0;
 
    set[0] = 4;
    set[1] = 1;
    set[2] = 2;

    for( int i = 0 ; i < 3 ; i++) {
        srand(time(NULL)); 
        set[i] = rand() % 10;

        for(int j = 0; j < i;  j++ ) {
            if( set[i] == set[j] ) {
                i--;
                break;
            }
        }
    }

    while( s != 3 ) {
        puts("3개의 숫자를 입력하세요");
    
        int test = scanf("%1d%1d%1d", &num[0], &num[1], &num[2]); getchar();
        if( test != 3 ) {
             puts("숫자를 입력해야 합니다.");
             continue;
        }
    
        if( num[0] == 9 && num[1] == 9 && num[2] == 9 ) {
           for( int i = 0 ; i < 3; i++ ) {
                printf("%d", set[i]);
           }
           printf(" <-- Hint \n");
           continue;
        }
    
        if( num[0] == num[1] || num[1] == num[2] ||  num[2] == num[0] ) {
             puts("서로 다른 숫자를 입력해야 합니다.");
             continue;
        }
    
        s = 0; 
        b = 0;
    
        for( int i = 0; i < 3; i++)   {
            for (int j = 0; j < 3; j++) {
                if ( set[i] == num[j])  {
                   if (i == j) {
                      s++;
                   } else {
                      b++;
                   } //if
                } //if
             } // for
        } //for
    
        printf("%dS %dB \n", s, b);
    
        cnt++;
    }// while

    printf("\n%d 번 만에 해냈습니다.\n", cnt);
    return 0;
}

실행결과는 아래와 같다.

 

특이한 점은 999를 입력하면 정답을 알려 준다는 점이다.

댓글