我在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;
}
}
答案 0 :(得分:0)
你需要为随机数发生器播种。
#include <time.h>
srand(time(NULL));
是一种无关紧要的方法。
答案 1 :(得分:0)
改善它的一种方法是选择船舶将朝向V或H的方向,然后仅使用它将适合的板的部分,因此如果船长4并且Verticle仅使用行用于垂直起点的1-7(10行板)。你不需要检查它是否适合。
查看代码,我看不到
中指定点的位置points[j].x = x;
points[j].y = (y + j);
如果船舶无效,将被清除。据我所知,点阵可能会填满无效点。