0

我正在制作一个基于文本的战舰游戏来练习 Java 编程(我还是很新,所以请耐心等待:S) 该游戏有一个 7x7 网格系统,使用多维字符数组('-')。当用户点击时,它会将其中一个“-”更改为“x”。用户提供A1、B5等坐标,程序将其转换为数组可以读取的0-6的数字。

现在我有了这个方法,我的 Player 类中的 setPlayerShips 应该在名为 playerShip1、playerShip2 和 playerShip3 的数组中设置不同的 x 和 y 坐标。数组中的第一个元素是船第一个点的 x 坐标,第二个元素是 y 坐标。第三个是第二个点的 x 坐标,第四个是 y 坐标,依此类推。这些船可以是垂直的或水平的(不倾斜),并且长度为 3 个单位。当我运行程序时,我注意到这个方法根本无法正常工作(它没有设置船3个单位的长度,并且没有在适当的位置),所以请大家看看这个方法并帮助我弄清楚它有什么问题?--注意方法的结束并不是真正的结束,

//set player ships coordinates, can be numbers from 0-6
  public static void setPlayerShips(){
    //first two coordinates are completely random(from 0-6)
    playerShip1[0]=(int)(Math.random()*7);
    playerShip1[1]=(int)(Math.random()*7);
    //next coordinates have to be next to this point, but can be in any direction
    do{
      playerShip1[2]=(int)(Math.random()*7);
    }while((Math.abs(playerShip1[2]-playerShip1[0]))>1);//x coordinate has to be either 1 away from or on the same as the first
    //if x coordinates are the same, y has to be 1 more than first y (unless first y is 5 - then make it 1 less than first y or else ship wont fit)
    if(playerShip1[0]==playerShip1[2] && playerShip1[1]>=5){
      playerShip1[3]=playerShip1[1]+1;
    }else if(playerShip1[0]==playerShip1[2] && playerShip1[1]>=5){
      playerShip1[3]=playerShip1[1]-1;
    }
    //if, both x's are the same, third x must be as well
    if(playerShip1[0]==playerShip1[2]){
      playerShip1[4]=playerShip1[0];
    }else if(playerShip1[0]==0){//else, if they aren't equal and the first x is 0 - add the last to the end after the second so it fits
      playerShip1[4]=playerShip1[2]+1;
    }else{//else, add it before the first x
      playerShip1[4]=playerShip1[0]-1;
    }
    //if both y coordinates equal eachother , third must be equal as well
    if(playerShip1[1]==playerShip1[3]){
      playerShip1[5]=playerShip1[1];
    }else if(playerShip1[3]==6){//else if second y coordinate is 6 and they are not all equal, next must come before first or it wont fit
      playerShip1[5]=playerShip1[1]-1;
    }else if(playerShip1[1]==0){//else if first y coordinate is 1, next must come after second y coordinate or it wont fit
      playerShip1[5]=playerShip1[3]+1;
    }

提前谢谢 - 如果这是一个菜鸟问题,对不起!

4

1 回答 1

0

首先,我认为您应该查看您的“船舶描述”,制作一个相关的类来存储其位置。

然后,您的算法看起来并不友好。我建议你另一个:

  1. 选择一个点:(x, y)在您的网格上(使用Math.random() * 7),
  2. 选择一个方向:上 = 0左 = 1下 = 2右 = 3(使用Math.random() * 4),
  3. 计算船点:如果正确,则x值是相同的,并且是yy例如。如果顶部,值为, ,且值为。y + 1y + 2xxx - 1x - 2yy

在 3) 之前,您可以根据原始位置和方向检查船舶是否适合网格(例如(x = 3并且y = 1方向 =顶部不适合(y值是1和))。如果不适合,只需选择新的点和方向0-1

我希望它会帮助你!

于 2013-01-14T23:53:53.570 回答