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;
20 import java.util.HashMap;
23 import org.hedgecode.chess.img.AbstractImageLoader;
24 import org.hedgecode.chess.img.FilenameUtils;
25 import org.hedgecode.chess.img.ImageConstants;
26 import org.hedgecode.chess.img.ImageException;
27 import org.hedgecode.chess.img.ImageFilter;
32 * @author Dmitry Samoshin aka gotty
34 public class BoardLoader extends AbstractImageLoader {
36 private static final String SQUARES_DIR = ImageConstants.RESOURCE_SQUARES_DIR;
38 private static final String SQUARE_DARK = ImageConstants.DARK_SQUARE_FILENAME;
39 private static final String SQUARE_LIGHT = ImageConstants.LIGHT_SQUARE_FILENAME;
41 private static final String[] SQUARE_NAMES = {SQUARE_DARK, SQUARE_LIGHT};
43 private Map<String, Board> squareSetMap = new HashMap<>();
46 public Board load(String name) throws ImageException {
48 if (Type.STATELESS.equals(loadType()) || !squareSetMap.containsKey(name)) {
49 String boardPath = FilenameUtils.getFullPath(SQUARES_DIR, name);
50 SquarePair<BufferedImage> squarePair = loadSquares(boardPath);
51 if (squarePair != null) {
52 board = Board.create(squarePair);
53 if (Type.STATEFUL.equals(loadType())) {
54 squareSetMap.put(name, board);
58 board = squareSetMap.get(name);
64 public void unload(String name) {
65 if (Type.STATEFUL.equals(loadType()) && squareSetMap.containsKey(name)) {
66 squareSetMap.remove(name);
71 protected void clear() {
75 private SquarePair<BufferedImage> loadSquares(String boardPath) throws ImageException {
76 Map<String, BufferedImage> images =
79 new ImageFilter(SQUARE_NAMES)
81 BufferedImage dark = images.get(SQUARE_DARK);
82 BufferedImage light = images.get(SQUARE_LIGHT);
83 return (dark != null && light != null)
84 ? SquarePair.create(dark, light)
85 : null; // todo: ImageException