새로새록

[c++]9. 숫자 야구 본문

소프트웨어융합/경희대 c++ 과제

[c++]9. 숫자 야구

류지나 2020. 7. 17. 00:16

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;


void startGame(int input[3], int answer[3]) {
	int trial = 1;
	while (trial<=9) {
		int strike = 0, ball = 0;
		cout << "===================== "<<trial<<" ==================" << endl;
		while (1) {
			cout << "1~9 범위의 숫자 세개를 입력해주세요 : ";
			for (int i = 0; i < 3; i++) {
				int num;
				cin >> num;
				input[i] = num;
			}
			if (input[0] == input[1] or input[1] == input[2] or input[0] == input[2])
				cout << "중복된 숫자를 입력하셨습니다." << endl;
			else 
				break;
		}
		
		for (int k = 0; k < 3; k++) {
			for (int j = 0; j < 3; j++) {
				if (input[k] == answer[j]) {
					if (k == j) strike++;
					else ball++;
					break;
				}
			}
		}

		if ((!strike) and (!ball)) cout << "Out!!" << endl << endl;
		else cout << strike << " Strike,  " << ball << " Ball" << endl << endl;

		trial++;

		if (strike == 3) {
			cout << "\n정답입니다!" << endl;
			break;
		}
	}
	if (trial == 10) {
		cout << "\n패배했습니다." << endl << "정답은 ";
		for (int i = 0; i < 3; i++) {
			cout << answer[i] << ' ';
		}
		cout << "입니다." << endl;
	}
}
int main() {
	int input[3];
	int answer[3];

	srand(time(NULL));
	for (int i = 0; i < 3;i++) {
		while (1) {
			int obj = rand() % 9 + 1;
			int sw = 1;
			for (int j = 0; j < i; j++) {
				if (obj == answer[j]) 
					sw = 0;
			}
			if (sw) {
				answer[i] = obj;
				cout << obj << endl;
				break;
			}
		}
	}
	
	
	startGame(input, answer);

	return 0;
}