2011-07-13 85 views
0

我用C語言編寫了一個戰艦遊戲。我有以下代碼來驗證隨機放置的船舶的點數不會超過船上限制。代碼無法順利運行,應用程序在生成隨機點時掛起。無法在命令提示符下顯示船隻!

你能推薦一些優化我所擁有的?

while(1 == 1) 
    { 
     //Generates the x, y coordenates of the point 
     int x = rand() % 9; 
     int y = rand() % 9;  

     //Calculating the ship direction 
     char direction = ((rand() % 10) > 5) ? 'V' : 'H'; 

     if(direction == 'H') 
     { 
      //Verifies that the ship placed on the acquired x coordenate of the point does not exceed the board size 
      //if so recalculates the value of x    
      while(!(((x + ships[i].length) - 1) < 10)) x = (rand() % 5); 
     } 
     else 
     { 
      //Verifies that the ship placed on the acquired y coordenate of the point does not exceed the board size 
      //if so recalculates the value of y 
      while(!(((y + ships[i].length) - 1) < 10)) y = (rand() % 5); 
     }        

     //Calculating the coordenates for each point of the ship        
     for(j = 0; j < ships[i].length; j++) 
     { 
      if(direction == 'H') 
      {          
      points[j].x = (x + j); 
      points[j].y = y; 
      }  
      else 
      { 
      points[j].x = x; 
      points[j].y = (y + j);               
      } 

      //Validating that the coordenate asigned to a point has not been assigned to another ship    
      if(verifyPos(points[j].x, points[j].y, ships, length)) 
      {   
       invalid = 1; 
       break; 
      } 
     } 

     //if all the points of the ship are valid, move to the next ship 
     //if not recalculate the initial point and the subsequent coordenates 
     if(invalid == 0) break;  
    } 

    ships[i].points = points; 
} 
} 
+1

請不要發表兩次相同的問題。在這種情況下正確的做法是編輯舊的(已關閉的)問題並嘗試重新打開它。 – razlebe

+0

我是新來的,我不知道如何讓我的舊帖子重新打開。所以我決定再次嘗試解釋我的問題。 – Maria

+0

沒關係 - 但您可能想閱讀[關於FAQ的這個問題](http://meta.stackexchange.com/questions/10582/what-is-a-closed-question)以更好地理解該過程。 – razlebe

回答

0

您需要種子隨機數發生器。

#include <time.h> 

srand(time(NULL)); 

是一個簡單的方法來做到這一點。

+0

我已經做到了,但它不管用:s – Maria

+0

那麼告訴我,你以前怎樣稱過'srand()'?你能粘貼確切的線嗎? –

+0

srand(time(NULL)); – Maria

0

那麼改進它的一種方法是選擇船舶將沿着V或H的哪個方向,然後僅使用它將適合的船板部分,以便如果船隻長4,並且垂直僅使用用於垂直起點的第1-7行(10行板)。你不需要檢查它是否適合。

看代碼,我沒有看到在分配

points[j].x = x; 
points[j].y = (y + j); 

其中分,如果船是無效的將被清除。據我所見,點數組可能填滿了無效點。