int TILE_SIZE_IN_PIXEL = 4;
int PIECE_SIZE_IN_TILE = 5;
public int tileToPixel(int positionInTiles){
return TILE_SIZE_IN_PIXEL * positionInTiles;
}
public int pixelToTile(int positionInPixel){
return positionInPixel / TILE_SIZE_IN_PIXEL;
}
, , (x y at).
ID- > . , (, ...). , , .
:
public class Piece{
private int x;
private int y;
private final Long id;
public void getX(){
return x;
}
public void getY(){
return y;
}
public void getID(){
return id;
}
}
public class Board(){
private Set<Long,Piece> pieces = new HashMap<Piece>(pieces);
public Piece getPieceOnTile(int tileX, int tileY){
for(Piece piece:pieces){
if (isPieceOnTile(piece, tileX, tileY)) return piece;
}
}
private boolean isPieceOnTile(piece, tileX, tileY){
if (piece.getX() < tileX) return false;
if (piece.getX() > tileX + PIECE_SIZE_IN_TILE) return false;
if (piece.getY() < tileY) return false;
if (piece.getY() > tileY + PIECE_SIZE_IN_TILE) return false;
return true;
}
}
, . , , , , Creative Commons.
The approach to preserving shapes in a set should work well if there aren't many. It should work better than a 2D array if most areas of the panel do not contain a piece. All of this currently assumes that there are no overlapping pieces. If you need to, then getPieceOnTile should return a collection of pieces. Set, if order does not matter, is List, if it does.
source
share