void main() { int save[3], input[3], strike, ball, i; srand((int)time(NULL)); save[0] = rand() % 10; back_1: save[1] = rand() % 10; if(save[1] == save[0])goto back_1; back_2: save[2] = rand() % 10; if((save[2] == save[0]) || (save[2] == save[1]))goto back_2; while(1) { cout << "세 개의 정수를 입력해 주세요 : "; cin >> input[0] >> input[1] >> input[2]; if((input[0] < 0) || (input[0] > 9) || (input[1] < 0) || (input[1] > 9) || (input[2] < 0) || (input[2] > 9)) { cout << "다시 입력해 주세요." << endl << endl; continue; } if((input[0] == input[1]) || (input[0] == input[2]) || (input[1] == input[2])) { cout << "다시 입력해 주세요." << endl << endl; continue; } strike = 0; ball = 0; for(i = 0; i < 3; i++) { if(save[i] == input[0]){ strike++; input[0] = 100; } if(save[i] == input[1]){ strike++; input[1] = 100; } if(save[i] == input[2]){ strike++; input[2] = 100; } if(((save[i] - input[0]) == 1) && (input[i] < 10)) { ball++; input[0] = 99; } else if(((save[i] - input[0]) == 1) && (input[i] < 10)) { ball++; input[0] = 99; } if(((save[i] - input[1]) == 1) && (input[i] < 10)) { ball++; input[1] = 99; } else if(((save[i] - input[1]) == 1) && (input[i] < 10)) { ball++; input[1] = 99; } if(((save[i] - input[2]) == 1) && (input[i] < 10)) { ball++; input[2] = 99; } else if(((save[i] - input[2]) == 1) && (input[i] < 10)) { ball++; input[2] = 99; } } cout << "strike = " << strike << ", ball = " << ball << endl; if(strike == 3)break; } }
프로그램 실행화면
C++로 구현한 야구게임이다. 규칙은 간단하다. 컴퓨터가 0~9까지의 숫자 중 3개의 숫자를 선택한다. 사용자는 이 세 개의 숫자를 맞춰야한다.
숫자를 입력할 때마다 약간의 힌트인 스트라이크와 볼이 나온다. 스트라이크는 사용자가 입력한 숫자와 컴퓨터가 선택한 숫자가 같은 것을 뜻한다.
난수를 생성해서 컴퓨터가 3개의 숫자를 선택하도록 했다. srand에 time을 넣어 똑같은 패턴의 난수가 생성되지 않도록 하여 주었다.
볼은 1을 적게 입력했을 때 카운트가 올라간다. if문을 신경써서 하지 않는다면 스트라이크와 볼의 갯수가 3을 넘어버릴 것이다.