繁体   English   中英

如何测试二维网格上的位置是否包含数组中的对象?

[英]How to test if a position on a 2D grid contains an object in an array?

我正在制作一个游戏,其中有一个带有墙壁、玩家和敌人的 2d 网格。 我有一个带有 2d 网格的文件,每个网格都是不同的字符。 在读取文件时,我分配了一个 2d 数组来包含墙壁的值,因为它们不会移动,但是当读取其中任何一个的角色时,我创建了一个新的敌人和新的玩家。 现在我正在尝试显示玩家和敌人,但我不知道该怎么做。 这是我的代码:

private char[][] cells;
private Player player;
private Lion[] lions;

public boolean hasPlayer(int row, int col)
{
    return false;       // needs fixing
}

public boolean hasLion(int row, int col)
{
if(cells[row][col] == '&') return true;
    else return false;      // needs fixing
}

public void display{
for(int i = 0; i < ROWS; i++)  
{
  for(int j = 0; j < COLS; j++) 
  {
    if(hasPlayer(i,j)){
      System.out.print(Main.BLUE + "P ");
    }
            
    else if(hasLion(i,j)){
      System.out.print(Main.YELLOW + "& ");
    }
   }
  }    
 }

你还没有分享你的 Lion 和 Player 类的定义......

我假设他们每个人都有 getRow() 和 getCol() 方法,并且您的单元格数组仅包含墙壁而没有玩家或狮子角色。

public boolean hasPlayer(int row, int col)
{
    return (this.player.getRow() == row && this.player.getCol() == col);
}

public boolean hasLion(int row, int col)
{
    return this.lions.stream().anyMatch(lion -> lion.getRow() == row && lion.getCol() == col)
}

boolean isAt(int col, int row)方法添加到您的 Lion 和 Player 类将使此代码更整洁。

您可能还需要在每次没有匹配时打印cells[i][j] ,并在每行后打印一个新行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM