2014-09-29 119 views
0

我正在建造一艘战列舰游戏,我需要一些建议如何处理这个问题。C++的建议如何打破一个while循环

欧凯所以问题是,比赛结束时,双方玩家已经击落所有船舶,这是由一个while循环控制,我希望它一样快,一个球员已经击落了对手突破。

问题是在函数void ShootAtShip(int board1[], int board2[], string names[], int cap)和while循环说while ((board1[i] != 0 || board2[i] != 0))我认为的问题是,while循环必须在它结束之前从上到下运行,我希望它在中间断开中频板1全部为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 2014-09-29 12:15:14

+0

这到底是什么问题?它坏了吗?还是需要优化? – rsethc 2014-09-29 12:15:27

+0

将代码更改为一个小问题,问题在于当两个板都获得全零时,其中一个板全部为零时while循环不会中断。 – 2014-09-29 12:16:32

回答

4

因此,循环不会中断的原因是因为您在条件中使用了错误的逻辑运算符。

while ((board1[i] != 0 || board2[i] != 0)) 应该 while (board1[i] && board2[i])

我相信你会想“如果板1为空或板2是空的,再破”,但你打出来的“,如果董事会1已经留下任何东西,或者电路板2还有什么,继续前进“。

此外,请注意if (n != 0)可能更有效率(和只是相同)if (n)

+0

Okey,我希望当任何一个都有0时循环中断,所以这样呢? ** while(board1 [i]!= 0 && board2 [i]!= 0)** – 2014-09-29 12:23:18

+0

哦,如果数组中的所有项都为0,会中断吗?这是不同的。 – rsethc 2014-09-29 20:01:39

+0

在这种情况下,您可能需要另一个函数返回'bool',例如'bool IsBoardAlive(<...> * board){<...>};'。如果(*(items_list + cur))返回true,则内容可能与'for(int cur = 0; cur rsethc 2014-09-29 20:06:47