80 lines
1.7 KiB
Java
80 lines
1.7 KiB
Java
package chess.view.simplerender;
|
|
|
|
import java.awt.Image;
|
|
import java.io.IOException;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
import javax.swing.Icon;
|
|
import javax.swing.ImageIcon;
|
|
|
|
import chess.model.Color;
|
|
import chess.model.Piece;
|
|
import chess.model.PieceVisitor;
|
|
import chess.model.pieces.Bishop;
|
|
import chess.model.pieces.King;
|
|
import chess.model.pieces.Knight;
|
|
import chess.model.pieces.Pawn;
|
|
import chess.model.pieces.Queen;
|
|
import chess.model.pieces.Rook;
|
|
import chess.view.AssetManager;
|
|
|
|
public class PieceIcon implements PieceVisitor<String> {
|
|
|
|
private static final String basePath = "pieces2D/";
|
|
private static final Map<String, Icon> cache = new HashMap<>();
|
|
|
|
public Icon getIcon(Piece piece) throws IOException {
|
|
if (piece == null)
|
|
return null;
|
|
String path = basePath + colorToString(piece.getColor()) + "-" + visit(piece) + ".png";
|
|
return getIcon(path);
|
|
}
|
|
|
|
private Icon getIcon(String path) throws IOException {
|
|
Icon image = cache.get(path);
|
|
if (image != null)
|
|
return image;
|
|
|
|
image = new ImageIcon(new ImageIcon(AssetManager.getResource(path).readAllBytes()).getImage()
|
|
.getScaledInstance(100, 100, Image.SCALE_SMOOTH));
|
|
cache.put(path, image);
|
|
return image;
|
|
}
|
|
|
|
private String colorToString(Color color) {
|
|
return color == Color.Black ? "black" : "white";
|
|
}
|
|
|
|
@Override
|
|
public String visitPiece(Bishop bishop) {
|
|
return "bishop";
|
|
}
|
|
|
|
@Override
|
|
public String visitPiece(King king) {
|
|
return "king";
|
|
}
|
|
|
|
@Override
|
|
public String visitPiece(Knight knight) {
|
|
return "knight";
|
|
}
|
|
|
|
@Override
|
|
public String visitPiece(Pawn pawn) {
|
|
return "pawn";
|
|
}
|
|
|
|
@Override
|
|
public String visitPiece(Queen queen) {
|
|
return "queen";
|
|
}
|
|
|
|
@Override
|
|
public String visitPiece(Rook rook) {
|
|
return "rook";
|
|
}
|
|
|
|
}
|