所以,我必须在10x10板上制作一个用户对计算机战舰游戏,用于编程类。我必须让电脑随机放置五艘船,大小分别为5、4、3、3和2。
我所做的是,我生成了两个0到9之间的随机数作为我的x和y坐标,然后第三个数字来决定船将被放置在哪个方向。然后,我使用switch语句检查板上是否有足够的空间将船放在第一位,如果有,则修改板阵列(好吧,这就是它应该做的事情)。
int main(void)
{ int x,y, bato[5]={5,4,3,3,2}, NbCases=17, countShip, dir, lenShip, countCaseEmpt, countLenShip, nbCaseOk, countModCase,i, dirTest;
time_t t;
srand(time(&t));
// gestir(plato a, int * bato, int x, int y)
// plato coord={{5,3,2,2,2},{5,3},{5,3},{5,3},{5},{0},{1,1}};
// plato is a custom data type defined as "int plato[10][10]"
plato coord={0}; //plateau vide
i=0;
for (countShip=5 ; countShip>0 ; countShip--)
{
do{
i++;
printf("%d\n",i); //counter used to check if the do while loop worked at all
nbCaseOk=0;
dirTest=0;
do {x=abs(rand())%10; y=abs(rand())%10;} while (coord[y][x]!=0); //start coordinates selection
dir = rand()%4; //direction selection
switch (countShip){ //ship lenght determination
case 0: lenShip=2; break;
case 1: lenShip=3; break;
case 2: lenShip=3; break;
case 3: lenShip=4; break;
case 4: lenShip=5; break;}
switch (dir){ //empty case checker and square modifier
case 0: //right
{
if (x+lenShip-1<10)
for (countLenShip=1 ; countLenShip<lenShip ; countLenShip++)
if (coord[y][x+countLenShip]==0) nbCaseOk+=1;
if (nbCaseOk==lenShip-1) {dirTest=1;
for (countModCase=0 ; countModCase<lenShip ; countModCase++)
coord[y][x+countModCase]=countShip; break;}}
case 1: //up
{
if (y+lenShip-1<10)
for (countLenShip=1 ; countLenShip<lenShip ; countLenShip++)
if (coord[y+countLenShip][x]==0) nbCaseOk+=1;
if (nbCaseOk==lenShip-1) {dirTest=1;
for (countModCase=0 ; countModCase<lenShip ; countModCase++)
coord[y+countModCase][x]=countShip; break;}}
case 2: //left
{
if (x-lenShip+1>=0)
for (countLenShip=1 ; countLenShip<lenShip ; countLenShip++)
if (coord[y][x-countLenShip]==0) nbCaseOk+=1;
if (nbCaseOk==lenShip-1) {dirTest=1;
for (countModCase=0 ; countModCase<lenShip ; countModCase++)
coord[y][x-countModCase]=countShip; break;}}
case 3: //down
{
if (y-lenShip+1>=0)
for (countLenShip=1 ; countLenShip<lenShip ; countLenShip++)
if (coord[y-countLenShip][x]==0) nbCaseOk+=1;
if (nbCaseOk==lenShip-1) {dirTest=1;
for (countModCase=0 ; countModCase<lenShip ; countModCase++)
coord[y-countModCase][x]=countShip; break;}}
}} while (dirTest==0);
}
aff(coord);
while (NbCases>0)
{
printf("Rentrer une coordonnee x, puis une coordonnee y, comprises entre 0 et 9:"); //"enter a coordinate between 0 and 9 for x, then another one for y:
scanf("%d",&x); scanf("%d",&y);
NbCases+=gestir(coord, bato, x, y);
aff(coord);
}
printf("état bateau: %d\n nombre cases: %d",coord[0][0], NbCases); //ship state and number of empty squares
return 0;
}
我的问题是我得到了一个无限循环。我很确定这个错误在我的switch语句中的某个地方。我使用调试器查看是什么导致了问题,我注意到,在执行swotch语句时,2D数组(坐标)没有修改,即使有足够的空间放置飞船。
我将do while循环的条件设置为(dirTest==0),但即使dirTest在switch语句末尾明显等于1,循环也不会结束。
PS:如果我的代码乱七八糟的话,我真的很抱歉,我在今年之前做过的唯一编程是去年一些非常轻量级的python。