[英]How to test if a position on a 2D grid contains an object in an array?
I was making a game where there is a 2d grid with walls, players, and enemies.我正在制作一个游戏,其中有一个带有墙壁、玩家和敌人的 2d 网格。 I have a file with the 2d grid with each as a different character.
我有一个带有 2d 网格的文件,每个网格都是不同的字符。 While reading the file, I assigned a 2d array to contain the values of the walls as they will not move, but I created a new enemy and new player when the character for either was read.
在读取文件时,我分配了一个 2d 数组来包含墙壁的值,因为它们不会移动,但是当读取其中任何一个的角色时,我创建了一个新的敌人和新的玩家。 Now I'm trying to display the players and enemies and I cannot figure out how to.
现在我正在尝试显示玩家和敌人,但我不知道该怎么做。 Here's my code:
这是我的代码:
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 + "& ");
}
}
}
}
You haven't shared the definition of your Lion and Player classes...你还没有分享你的 Lion 和 Player 类的定义......
I'm assuming that they will each have getRow() and getCol() methods, and that your cells array only contains the walls and no player or lion characters.我假设他们每个人都有 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)
}
adding a boolean isAt(int col, int row)
method to your Lion and Player classes would make this code tidier.将
boolean isAt(int col, int row)
方法添加到您的 Lion 和 Player 类将使此代码更整洁。
you may also need to print cells[i][j]
every time nothing is matched, and a new line after each row.您可能还需要在每次没有匹配时打印
cells[i][j]
,并在每行后打印一个新行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.