전함 게임을 만들고 있는데이 문제를 해결하는 방법에 대한 조언이 필요합니다.while 루프를 깨는 방법에 대한 C++ 조언
Okey 그래서 두 플레이어 모두 플레이어가 모든 배를 격추 시켰을 때 게임이 끝나는 것이 문제입니다. 이것은 while 루프로 제어되며 한 선수가 상대방을 격추시킨만큼 빠르게 깨고 싶습니다.
문제는 void ShootAtShip(int board1[], int board2[], string names[], int cap)
이며 while 루프는 while ((board1[i] != 0 || board2[i] != 0))
이라고 말하면서 문제는 while 루프가 끝나기 전에 끝까지 실행해야한다는 것입니다. 중간에 끊기를 원합니다. IF board1이 모두 0을 얻습니다.
bool isGameOver(int board1[], int board2[], int cap)
{
bool lost1 = true;
bool lost2 = true;
for (int i = 0; i < cap && lost1 != false; ++i)
if (board1[i] != 0)
lost1 = false;
if (lost1)
return true;
for (int i = 0; i < cap && lost2 != false; ++i)
if (board2[i] != 0)
lost2 = false;
return lost2;
}
void ShootAtShip(int board1[], int board2[], string names[], int cap) {
const int hit = 0;
int shot = 0;
int temp;
isGameOver(board1, board2, cap);
for (int i = 0; i < cap; i++) {
while ((board1[i] != 0 || board2[i] != 0)) { //detects if any board has all their ships shot down
cout << names[1] << " set a position to shoot." << endl;
cin >> shot;
temp = shot;
while ((shot >= cap) || (shot < 0)) { //detects if the number is allowed
cout << "That number is not allowed, " << names[1] << " set a position to shoot." << endl;
cin >> shot;
}
if (board1[shot] != 0) {
board1[shot] = 0;
cout << "Hit!" << endl;
}
else {
cout << "You missed." << endl;
}
shot = 0;
cout << names[0] << " set a position to shoot." << endl;
cin >> shot;
while ((shot >= cap) || (shot < 0)) { //detects if the number is allowed
cout << "That number is not allowed, " << names[0] << " set a position to shoot." << endl;
cin >> shot;
}
if (board2[shot] != 0) {
board2[shot] = 0;
cout << "Hit!" << endl;
}
else {
cout << "You missed." << endl;
}
}
}
cout << "Testing is while loop stops";
}
전체 코드를 게시해야합니까? 우리가이 모든 일을 겪어야 만한다면 정말 당신을 도우려는 것이 훨씬 어렵습니다. 가능한 한 문제를 단순화하려고 항상 노력하십시오. – Jendas
정확히 무엇이 잘못 되었습니까? 깨진거야? 아니면 최적화가 필요합니까? – rsethc
코드를 좀 더 작은 코드로 변경 한 경우, 문제는 while 루프가 하나의 보드가 모두 0이 될 때만 깨지게된다는 것입니다. –