2 * Copyright (c) 2018-2019. Developed by Hedgecode.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.hedgecode.chess.img.board;
19 import java.awt.image.BufferedImage;
21 import java.io.IOException;
22 import java.util.HashMap;
25 import javax.imageio.ImageIO;
27 import org.hedgecode.chess.img.AbstractImageLoader;
28 import org.hedgecode.chess.img.ImageConstants;
29 import org.hedgecode.chess.img.ImageException;
30 import org.hedgecode.chess.img.ImageFilter;
35 * @author Dmitry Samoshin aka gotty
37 public class BoardLoader extends AbstractImageLoader {
39 private static final File SQUARES_PATH = new File(IMAGES_PATH, ImageConstants.RESOURCE_SQUARES_DIR);
41 private static final String SQUARE_DARK = ImageConstants.DARK_SQUARE_FILENAME;
42 private static final String SQUARE_LIGHT = ImageConstants.LIGHT_SQUARE_FILENAME;
44 private static final String[] SQUARE_NAMES = {SQUARE_DARK, SQUARE_LIGHT};
46 private Map<String, Board> squareSetMap = new HashMap<>();
49 public Board load(String name) throws ImageException {
51 SquarePair<BufferedImage> squarePair = null;
52 if (Type.STATELESS.equals(loadType()) || !squareSetMap.containsKey(name)) {
53 File boardPath = new File(SQUARES_PATH, name);
54 if (boardPath.exists() && boardPath.isDirectory()) {
55 squarePair = loadSquares(name, boardPath);
57 if (squarePair != null) {
58 board = Board.create(squarePair);
59 if (Type.STATEFUL.equals(loadType())) {
60 squareSetMap.put(name, board);
64 board = squareSetMap.get(name);
70 public void unload(String name) {
71 if (Type.STATEFUL.equals(loadType()) && squareSetMap.containsKey(name)) {
72 squareSetMap.remove(name);
77 protected void clear() {
81 private SquarePair<BufferedImage> loadSquares(String name, File boardPath) throws ImageException {
82 BufferedImage dark = null, light = null;
83 File[] images = boardPath.listFiles(new ImageFilter(SQUARE_NAMES));
85 for (File image : images) {
87 String filename = image.getName();
89 switch (filename.substring(0, filename.lastIndexOf('.'))) {
91 dark = ImageIO.read(image);
94 light = ImageIO.read(image);
97 } catch (IOException e) {
98 throw new ImageException(e.getMessage()); // todo: locale
103 return (dark != null && light != null) ? SquarePair.create(dark, light) : null;