2014-09-29 4 views
0

전함 게임을 만들고 있는데이 문제를 해결하는 방법에 대한 조언이 필요합니다.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"; 
} 
+4

전체 코드를 게시해야합니까? 우리가이 모든 일을 겪어야 만한다면 정말 당신을 도우려는 것이 훨씬 어렵습니다. 가능한 한 문제를 단순화하려고 항상 노력하십시오. – Jendas

+0

정확히 무엇이 잘못 되었습니까? 깨진거야? 아니면 최적화가 필요합니까? – rsethc

+0

코드를 좀 더 작은 코드로 변경 한 경우, 문제는 while 루프가 하나의 보드가 모두 0이 될 때만 깨지게된다는 것입니다. –

답변

4

그래서 루프가 깨지지 않는 이유는 잘못된 논리 연산자를 사용하고 있기 때문입니다.

while ((board1[i] != 0 || board2[i] != 0)) 내가 "보드 1이 비어 있거나 보드 2, 다음 휴식 비어있는 경우"당신이 생각하고 생각하지만, while (board1[i] && board2[i])

해야한다 보드 1 아무것도 남아있는 경우 당신이 밖으로 입력하면 "입니다, 또는 2 번 보드에는 왼쪽, 계속 "이라고 표시됩니다.

또한 if (n != 0)if (n)과 같이 더 효율적일 수 있습니다.

+0

Okey, 둘 중 하나가 모두 0 일 때 루프가 끊길 원합니다. ** while (board1 [i]! = 0 && board2 [i]! = 0) ** –

+0

아, 배열의 모든 항목이 0이면 깨지십니까? 그것은 다르다. – rsethc

+0

그런 경우,'bool IsBoardAlive (<...> * board) {<...>};'와 같은'bool'을 반환하는 다른 함수를 원할 수 있습니다. 내용은 다음과 같을 수 있습니다. for (int cur = 0; cur } '일 수 있습니다. 너 생각 나니? – rsethc

관련 문제