99 lines
2.4 KiB
Java
99 lines
2.4 KiB
Java
package dev.kske.chess.io;
|
|
|
|
import java.awt.Image;
|
|
import java.awt.image.BufferedImage;
|
|
import java.io.IOException;
|
|
import java.util.Arrays;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
|
|
import javax.imageio.ImageIO;
|
|
|
|
import dev.kske.chess.board.Piece;
|
|
|
|
/**
|
|
* Project: <strong>Chess</strong><br>
|
|
* File: <strong>TextureUtil.java</strong><br>
|
|
* Created: <strong>01.07.2019</strong><br>
|
|
*
|
|
* @since Chess v0.1-alpha
|
|
* @author Kai S. K. Engelbart
|
|
*/
|
|
public class TextureUtil {
|
|
|
|
private static Map<String, Image> textures = new HashMap<>(),
|
|
scaledTextures = new HashMap<>();
|
|
|
|
static {
|
|
loadPieceTextures();
|
|
scaledTextures.putAll(textures);
|
|
}
|
|
|
|
private TextureUtil() {}
|
|
|
|
/**
|
|
* Loads a piece texture fitting to a piece object.
|
|
*
|
|
* @param piece The piece from which the texture properties are taken
|
|
* @return The fitting texture
|
|
*/
|
|
public static Image getPieceTexture(Piece piece) {
|
|
String key = piece.getClass().getSimpleName().toLowerCase() + "_"
|
|
+ piece.getColor().toString().toLowerCase();
|
|
return scaledTextures.get(key);
|
|
}
|
|
|
|
/**
|
|
* Scales all piece textures to fit the current tile size.
|
|
*
|
|
* @param tileSize the new width and height of the piece textures
|
|
*/
|
|
public static void scalePieceTextures(int tileSize) {
|
|
scaledTextures.clear();
|
|
textures.forEach(
|
|
(key, img) -> scaledTextures.put(key, img.getScaledInstance(tileSize, tileSize, Image.SCALE_SMOOTH))
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Loads an image from a file in the resource folder.
|
|
*
|
|
* @param fileName The name of the image resource
|
|
* @return The loaded image
|
|
*/
|
|
private static Image loadImage(String fileName) {
|
|
BufferedImage in = null;
|
|
try {
|
|
in = ImageIO.read(TextureUtil.class.getResourceAsStream(fileName));
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
return in;
|
|
}
|
|
|
|
/**
|
|
* Load every PNG file inside the res/pieces directory.
|
|
* The filenames without extensions are used as keys in the map textures.
|
|
*/
|
|
private static void loadPieceTextures() {
|
|
Arrays
|
|
.asList(
|
|
"king_white",
|
|
"king_black",
|
|
"queen_white",
|
|
"queen_black",
|
|
"rook_white",
|
|
"rook_black",
|
|
"knight_white",
|
|
"knight_black",
|
|
"bishop_white",
|
|
"bishop_black",
|
|
"pawn_white",
|
|
"pawn_black"
|
|
)
|
|
.forEach(
|
|
name -> textures.put(name, loadImage("/pieces/" + name + ".png"))
|
|
);
|
|
}
|
|
}
|