숫자야구게임 로직
나를 혼란에 빠뜨렸던...숫자야구 게임 로직이다.
생각보다 논리 구성하는 게 어려웠다.
대략적으로 필요한 것들은 떠올라도, 코드로 어떻게 표현할지 바로 떠오르지 않아서 힘들었던 것 같다.
#include <iostream>
#include <time.h>
using namespace std;
void main()
{
srand(time(NULL));
//변수 선언
int pitcher1, pitcher2, pitcher3; //컴퓨터 숫자용 변수
int batter1, batter2, batter3; //내가 입력할 변수
int strike, ball; //스트라이크, 볼 카운트
int roundCount = 9;
strike = ball = 0;
//중복되지 않는 수를 선별하기 위한 반복문
while (true)
{
pitcher1 = rand() % 10;
if (pitcher1 == 0) continue;
pitcher2 = rand() % 10;
if (pitcher2 == pitcher1) continue;
pitcher3 = rand() % 10;
if (pitcher3 == pitcher1 || pitcher3 == pitcher2) continue;
break;
}
cout << pitcher1 << pitcher2 << pitcher3 << endl;
while (true)
{
cout << "첫번째 수 입력:";
cin >> batter1;
cout << "두번재 수 입력";
cin >> batter2;
cout << "세번째 수 입력";
cin >> batter3;
//볼인지, 스트라이크인지 연산한다
if(pitcher1 == batter1) strike++;
if(pitcher1 == batter2) ball++;
if(pitcher1 == batter3) ball++;
if(pitcher2 == batter1) ball++;
if(pitcher2 == batter2) strike++;
if(pitcher2 == batter3) ball++;
if(pitcher3 == batter1) ball++;
if(pitcher3 == batter2) ball++;
if(pitcher3 == batter3) strike++;
//결과에 대한 내용 출력
if (strike > 0 && ball < 1)
{
cout << strike << " 스트라이크 " << endl;
}
else if (strike < 1 && ball > 0)
{
cout << ball << " 볼" << endl;
}
else
{
cout << strike << " 스트라이크 " << ball << " 볼" << endl;
}
if (strike >= 3)
{
cout << "너의 승리" << endl;
break;
}
roundCount--;
cout << roundCount << " 회 남았다" << endl;
//사용했던 스트라이크, 볼 카운트는 초기화를 해야 또(?) 사용이 가능하다
strike = ball = 0;
if (roundCount < 0)
{
cout << "게임오버" << endl;
cout << pitcher1 << pitcher2 << pitcher3 << endl;
break;
}
}
}
이해가 안되면 다시 처음부터 보고 또 보고, 그래도 잘 모르겠으면 아예 외우는 식으로 공부해보자.
'C++' 카테고리의 다른 글
| C++ | 구조체, 배열, 셔플 (0) | 2025.07.14 |
|---|---|
| C++ | 공격으로 인한 체력 감소 로직을 구성해보자 (0) | 2025.07.14 |
| C++| 반복문과 업앤다운 게임 로직 (0) | 2025.07.14 |
| C++ | 연산자와 조건문 그리고 가위바위보 게임 로직 (3) | 2025.07.14 |
| C++ 첫 수업 | 프로젝트 생성과 변수 (2) | 2025.07.14 |