开发者

Having trouble making ships appear on the command prompt!

I building a battleship game in C. I have the following code to validate that the points of the randomly placed ship don't exceed the board limit. The code doesn't work very smoothly and the application hangs while generating the random points.

Could you recommend some optimizations to what I have?

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')
      {
        开发者_如何学Python   //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;
 }   
}


You need to seed the randomizer.

#include <time.h>

srand(time(NULL));

is a trivial way to do it.


Well one way of improving it would be to choose which direction the ship is going to go V or H and then only use the section of the board that it will fit into so if the ship is 4 long and verticle only use rows 1-7 (of a 10 row board) for the verticle starting point. THen you don't need to check if it will fit at all.

Looking at the code, I don't see where the points assigned in

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

are cleared if a ship is invalid. As far as I can see teh points array may be filling up with invalid points.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜