我用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;
}
}
請不要發表兩次相同的問題。在這種情況下正確的做法是編輯舊的(已關閉的)問題並嘗試重新打開它。 – razlebe
我是新來的,我不知道如何讓我的舊帖子重新打開。所以我決定再次嘗試解釋我的問題。 – Maria
沒關係 - 但您可能想閱讀[關於FAQ的這個問題](http://meta.stackexchange.com/questions/10582/what-is-a-closed-question)以更好地理解該過程。 – razlebe