有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中,如何在多维数组中设置随机的3个单位“ships”?

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

现在我有了这个方法,在我的Player类中设置playerships,它应该在名为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;
    }

提前感谢-如果这是一个noob问题,很抱歉


共 (1) 个答案

  1. # 1 楼答案

    首先,我认为你应该回顾你的《船舶描述》,制作一个相关的类来存储它的位置

    那么,你的算法看起来不友好。我向你提出另一个建议:

    1. 选择一个点:(x, y)在你的网格上(使用Math.random() * 7
    2. 选择一个方向:top=0left=1bottom=2right=3(使用Math.random() * 4
    3. 计算发货点:例如,如果x值相同,yyy + 1y + 2。如果top,x值是xx - 1x - 2y值是y

    在3)之前,您可以根据原始位置和方向(例如(x = 3y = 1方向=顶部将不适合(y值为10-1))。如果不合适,只需选择新的点和方向

    我希望它能帮助你