Update Resources.java

Joker Bilder sind jetzt auch in resources
This commit is contained in:
Dennis Weinberger 2019-03-25 16:36:44 +00:00
parent b2e00366f2
commit 34e634a05d

View file

@ -1,334 +1,343 @@
package gui; package gui;
import game.ScoreEntry; import game.ScoreEntry;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.swing.*; import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.awt.image.ColorModel; import java.awt.image.ColorModel;
import java.awt.image.WritableRaster; import java.awt.image.WritableRaster;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.List; import java.util.List;
/** /**
* Diese Klasse verwaltet die Resourcen des Spiels, darunter beispielsweise Bilder, Icons und Schriftarten. * Diese Klasse verwaltet die Resourcen des Spiels, darunter beispielsweise Bilder, Icons und Schriftarten.
*/ */
public class Resources { public class Resources {
private static final int NUM_CASTLES = 6; private static final int NUM_CASTLES = 6;
private static Resources instance; private static Resources instance;
private Map<Color, BufferedImage[]> castlesColored; private Map<Color, BufferedImage[]> castlesColored;
private BufferedImage dices[]; private BufferedImage jokers[];
private BufferedImage check; private BufferedImage dices[];
private BufferedImage unit; private BufferedImage check;
private BufferedImage arrow, arrowDeactivated, plus, plusDeactivated, swords; private BufferedImage unit;
private BufferedImage soldiers[]; private BufferedImage arrow, arrowDeactivated, plus, plusDeactivated, swords;
private List<String> castleNames; private BufferedImage soldiers[];
private Font celticFont; private List<String> castleNames;
private Font celticFont;
private List<ScoreEntry> scoreEntries;
private List<ScoreEntry> scoreEntries;
private boolean resourcesLoaded;
private boolean resourcesLoaded;
/**
* Privater Konstruktor, dieser wird normalerweise nur einmal aufgerufen /**
*/ * Privater Konstruktor, dieser wird normalerweise nur einmal aufgerufen
private Resources() { */
this.resourcesLoaded = false; private Resources() {
this.scoreEntries = new LinkedList<>(); this.resourcesLoaded = false;
} this.scoreEntries = new LinkedList<>();
}
/**
* Gibt die Instanz des Resourcen Managers zurück oder erzeugt eine neue /**
* @return Resourcen Manager * Gibt die Instanz des Resourcen Managers zurück oder erzeugt eine neue
*/ * @return Resourcen Manager
public static Resources getInstance() { */
if(instance == null) { public static Resources getInstance() {
instance = new Resources(); if(instance == null) {
instance.load(); instance = new Resources();
} instance.load();
}
return instance;
} return instance;
}
/**
* Lädt ein Bild aus den Resourcen /**
* @param name der Name der Datei * Lädt ein Bild aus den Resourcen
* @return das Bild als {@link BufferedImage}-Objekt * @param name der Name der Datei
* @throws IOException Eine IOException wird geworfen, falls das Bild nicht gefunden wurde oder andere Probleme beim Laden auftreten * @return das Bild als {@link BufferedImage}-Objekt
*/ * @throws IOException Eine IOException wird geworfen, falls das Bild nicht gefunden wurde oder andere Probleme beim Laden auftreten
private BufferedImage loadImage(String name) throws IOException { */
URL res = Resources.class.getClassLoader().getResource(name); private BufferedImage loadImage(String name) throws IOException {
if(res == null) URL res = Resources.class.getClassLoader().getResource(name);
throw new IOException("Resource not found: " + name); if(res == null)
throw new IOException("Resource not found: " + name);
return ImageIO.read(res);
} return ImageIO.read(res);
}
/**
* Lädt alle Resourcen /**
* @return true, wenn alle Resourcen erfolgreich geladen wurden * Lädt alle Resourcen
*/ * @return true, wenn alle Resourcen erfolgreich geladen wurden
public boolean load() { */
if(resourcesLoaded) public boolean load() {
return true; if(resourcesLoaded)
return true;
try {
// Load Castle try {
castlesColored = new HashMap<>(); // Load Castle
BufferedImage castles[] = new BufferedImage[NUM_CASTLES]; castlesColored = new HashMap<>();
for(int i = 0; i < NUM_CASTLES; i++) BufferedImage castles[] = new BufferedImage[NUM_CASTLES];
castles[i] = loadImage("castle" + (i + 1) + ".png"); for(int i = 0; i < NUM_CASTLES; i++)
castlesColored.put(Color.WHITE, castles); castles[i] = loadImage("castle" + (i + 1) + ".png");
castlesColored.put(Color.WHITE, castles);
// Load Dices
dices = loadDices(); // Load Dices
dices = loadDices();
// Load Icons
soldiers = new BufferedImage[] { loadImage("soldier1.png"), loadImage("soldier2.png") }; // Load Jokers
check = loadImage("check.png"); jokers = new BufferedImage[] { loadImage("add_troops_joker.png"), loadImage("add_troops_joker_disabled.png"), loadImage("scare_troops.png"), loadImage("scare_troops_disabled.png") };
unit = loadImage("unit.png");
arrow = loadImage("arrow.png"); // Load Icons
swords = loadImage("swords.png"); soldiers = new BufferedImage[] { loadImage("soldier1.png"), loadImage("soldier2.png") };
plus = loadImage("plus.png"); check = loadImage("check.png");
plusDeactivated = loadImage("plus_deactivated.png"); unit = loadImage("unit.png");
arrowDeactivated = loadImage("arrow_deactivated.png"); arrow = loadImage("arrow.png");
swords = loadImage("swords.png");
// Load Castle names plus = loadImage("plus.png");
castleNames = loadRegionNames(); plusDeactivated = loadImage("plus_deactivated.png");
arrowDeactivated = loadImage("arrow_deactivated.png");
// Load font
celticFont = loadFont("celtic.ttf"); // Load Castle names
castleNames = loadRegionNames();
// Load score entries
loadScoreEntries(); // Load font
celticFont = loadFont("celtic.ttf");
resourcesLoaded = true;
return true; // Load score entries
} catch(Exception ex) { loadScoreEntries();
JOptionPane.showMessageDialog(null, "Konnte Resourcen nicht laden: " + ex.getMessage(), "Fehler beim Laden der Resourcen", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace(); resourcesLoaded = true;
return false; return true;
} } catch(Exception ex) {
} JOptionPane.showMessageDialog(null, "Konnte Resourcen nicht laden: " + ex.getMessage(), "Fehler beim Laden der Resourcen", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
/** return false;
* Speichert bestimmte Resourcen, zurzeit nur den Highscore-Table }
* @return gibt true zurück, wenn erfolgreich gespeichert wurde }
*/
public boolean save() { /**
try { * Speichert bestimmte Resourcen, zurzeit nur den Highscore-Table
saveScoreEntries(); * @return gibt true zurück, wenn erfolgreich gespeichert wurde
return true; */
} catch(IOException ex) { public boolean save() {
ex.printStackTrace(); try {
return false; saveScoreEntries();
} return true;
} } catch(IOException ex) {
ex.printStackTrace();
/** return false;
* Diese Methode speichert alle Objekte des Typs {@link ScoreEntry} in der Textdatei "highscores.txt" }
* Jede Zeile stellt dabei einen ScoreEntry dar. Sollten Probleme auftreten, muss eine {@link IOException} geworfen werden. }
* Die Einträge sind in der Liste {@link #scoreEntries} zu finden.
* @see ScoreEntry#write(PrintWriter) /**
* @throws IOException Eine IOException wird geworfen, wenn Probleme beim Schreiben auftreten. * Diese Methode speichert alle Objekte des Typs {@link ScoreEntry} in der Textdatei "highscores.txt"
*/ * Jede Zeile stellt dabei einen ScoreEntry dar. Sollten Probleme auftreten, muss eine {@link IOException} geworfen werden.
private void saveScoreEntries() throws IOException { * Die Einträge sind in der Liste {@link #scoreEntries} zu finden.
// TODO: Resources#saveScoreEntries() * @see ScoreEntry#write(PrintWriter)
} * @throws IOException Eine IOException wird geworfen, wenn Probleme beim Schreiben auftreten.
*/
/** private void saveScoreEntries() throws IOException {
* Lädt den Highscore-Table aus der Datei "highscores.txt". // TODO: Resources#saveScoreEntries()
* Dabei wird die Liste {@link #scoreEntries} neu erzeugt und befüllt. }
* Beachte dabei, dass die Liste nach dem Einlen absteigend nach den Punktzahlen sortiert sein muss.
* Sollte eine Exception auftreten, kann diese ausgegeben werden, sie sollte aber nicht weitergegeben werden, /**
* da sonst das Laden der restlichen Resourcen abgebrochen wird ({@link #load()}). * Lädt den Highscore-Table aus der Datei "highscores.txt".
* @see ScoreEntry#read(String) * Dabei wird die Liste {@link #scoreEntries} neu erzeugt und befüllt.
* @see #addScoreEntry(ScoreEntry) * Beachte dabei, dass die Liste nach dem Einlen absteigend nach den Punktzahlen sortiert sein muss.
*/ * Sollte eine Exception auftreten, kann diese ausgegeben werden, sie sollte aber nicht weitergegeben werden,
private void loadScoreEntries() { * da sonst das Laden der restlichen Resourcen abgebrochen wird ({@link #load()}).
* @see ScoreEntry#read(String)
List<ScoreEntry> regionNames = new LinkedList<>(); * @see #addScoreEntry(ScoreEntry)
InputStream is = Resources.class.getClassLoader().getResourceAsStream("highscores.txt"); */
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); private void loadScoreEntries() {
BufferedReader br = new BufferedReader(isr);
scoreEntries = new LinkedList<>(); List<ScoreEntry> regionNames = new LinkedList<>();
String line; InputStream is = Resources.class.getClassLoader().getResourceAsStream("highscores.txt");
try { InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
while((line = br.readLine()) != null) { BufferedReader br = new BufferedReader(isr);
line = line.trim(); scoreEntries = new LinkedList<>();
if(line.length() > 0 && !line.startsWith("#")) { String line;
addScoreEntry(ScoreEntry.read(line)); try {
} while((line = br.readLine()) != null) {
} line = line.trim();
if(line.length() > 0 && !line.startsWith("#")) {
br.close(); addScoreEntry(ScoreEntry.read(line));
} catch (IOException e) { }
// TODO Auto-generated catch block }
e.printStackTrace();
} br.close();
} } catch (IOException e) {
// TODO Auto-generated catch block
/** e.printStackTrace();
* Fügt ein {@link ScoreEntry}-Objekt der Liste von Einträgen hinzu. }
* Beachte: Nach dem Einfügen muss die Liste nach den Punktzahlen absteigend sortiert bleiben. }
* @param scoreEntry Der einzufügende Eintrag
* @see ScoreEntry#compareTo(ScoreEntry) /**
*/ * Fügt ein {@link ScoreEntry}-Objekt der Liste von Einträgen hinzu.
public void addScoreEntry(ScoreEntry scoreEntry) { * Beachte: Nach dem Einfügen muss die Liste nach den Punktzahlen absteigend sortiert bleiben.
int i = scoreEntries.size() - 1; * @param scoreEntry Der einzufügende Eintrag
for(; i >= 0; i--) { * @see ScoreEntry#compareTo(ScoreEntry)
if(scoreEntry.compareTo(scoreEntries.get(i)) < 0) { */
break; public void addScoreEntry(ScoreEntry scoreEntry) {
} int i = scoreEntries.size() - 1;
} for(; i >= 0; i--) {
if(scoreEntry.compareTo(scoreEntries.get(i)) < 0) {
scoreEntries.add(i + 1, scoreEntry); break;
} }
}
public List<ScoreEntry> getScoreEntries() {
return scoreEntries; scoreEntries.add(i + 1, scoreEntry);
} }
private Font loadFont(String name) throws IOException, FontFormatException { public List<ScoreEntry> getScoreEntries() {
InputStream is = Resources.class.getClassLoader().getResourceAsStream(name); return scoreEntries;
Font f = Font.createFont(Font.TRUETYPE_FONT, is); }
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(f); private Font loadFont(String name) throws IOException, FontFormatException {
return f.deriveFont(20f); InputStream is = Resources.class.getClassLoader().getResourceAsStream(name);
} Font f = Font.createFont(Font.TRUETYPE_FONT, is);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private BufferedImage[] loadDices() throws IOException { ge.registerFont(f);
BufferedImage[] dices = new BufferedImage[6]; return f.deriveFont(20f);
BufferedImage diceImage = loadImage("dices.png"); }
int diceSizeW = diceImage.getWidth() / 3;
int diceSizeH = diceImage.getHeight() / 2; private BufferedImage[] loadDices() throws IOException {
if(diceSizeW != diceSizeH) BufferedImage[] dices = new BufferedImage[6];
System.out.println("Invalid dice dimensions for resource: dice.png. Expected 3x2 dices, got dimensions: " + diceImage.getWidth() + "x" + diceImage.getHeight()); BufferedImage diceImage = loadImage("dices.png");
int diceSizeW = diceImage.getWidth() / 3;
int diceSize = diceSizeH; int diceSizeH = diceImage.getHeight() / 2;
int num = 0; if(diceSizeW != diceSizeH)
System.out.println("Invalid dice dimensions for resource: dice.png. Expected 3x2 dices, got dimensions: " + diceImage.getWidth() + "x" + diceImage.getHeight());
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) { int diceSize = diceSizeH;
//Initialize the image array with image chunks int num = 0;
dices[num] = new BufferedImage(diceSize, diceSize, diceImage.getType());
for (int x = 0; x < 2; x++) {
// draws the image chunk for (int y = 0; y < 3; y++) {
Graphics2D gr = dices[num++].createGraphics(); //Initialize the image array with image chunks
gr.drawImage(diceImage, 0, 0, diceSize, diceSize, diceSize * y, diceSize * x, diceSize * y + diceSize, diceSize * x + diceSize, null); dices[num] = new BufferedImage(diceSize, diceSize, diceImage.getType());
gr.dispose();
} // draws the image chunk
} Graphics2D gr = dices[num++].createGraphics();
gr.drawImage(diceImage, 0, 0, diceSize, diceSize, diceSize * y, diceSize * x, diceSize * y + diceSize, diceSize * x + diceSize, null);
return dices; gr.dispose();
} }
}
private List<String> loadRegionNames() throws IOException {
return dices;
List<String> regionNames = new LinkedList<>(); }
InputStream is = Resources.class.getClassLoader().getResourceAsStream("castles.txt");
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); private List<String> loadRegionNames() throws IOException {
BufferedReader br = new BufferedReader(isr);
List<String> regionNames = new LinkedList<>();
String line; InputStream is = Resources.class.getClassLoader().getResourceAsStream("castles.txt");
while((line = br.readLine()) != null) { InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
line = line.trim(); BufferedReader br = new BufferedReader(isr);
if(line.length() > 0 && !line.startsWith("#")) {
regionNames.add(line); String line;
} while((line = br.readLine()) != null) {
} line = line.trim();
if(line.length() > 0 && !line.startsWith("#")) {
br.close(); regionNames.add(line);
return regionNames; }
} }
private BufferedImage colorImage(BufferedImage original, Color color) { br.close();
ColorModel cm = original.getColorModel(); return regionNames;
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied(); }
WritableRaster raster = original.copyData(null);
BufferedImage newImage = new BufferedImage(cm, raster, isAlphaPremultiplied, null); private BufferedImage colorImage(BufferedImage original, Color color) {
ColorModel cm = original.getColorModel();
for(int x = 0; x < original.getWidth(); x++) { boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
for(int y = 0; y < original.getHeight(); y++) { WritableRaster raster = original.copyData(null);
Color oldColor = new Color(original.getRGB(x, y), true); BufferedImage newImage = new BufferedImage(cm, raster, isAlphaPremultiplied, null);
if(oldColor.getRed() == 255 && oldColor.getGreen() == 255 && oldColor.getBlue() == 255 && oldColor.getAlpha() == 255) {
newImage.setRGB(x, y, color.getRGB()); for(int x = 0; x < original.getWidth(); x++) {
} for(int y = 0; y < original.getHeight(); y++) {
} Color oldColor = new Color(original.getRGB(x, y), true);
} if(oldColor.getRed() == 255 && oldColor.getGreen() == 255 && oldColor.getBlue() == 255 && oldColor.getAlpha() == 255) {
newImage.setRGB(x, y, color.getRGB());
return newImage; }
} }
}
public BufferedImage getCastle(Color color, int index) {
if(!resourcesLoaded) return newImage;
return null; }
index = index % NUM_CASTLES; public BufferedImage getCastle(Color color, int index) {
BufferedImage images[]; if(!resourcesLoaded)
if(castlesColored.containsKey(color)) return null;
images = castlesColored.get(color);
else index = index % NUM_CASTLES;
images = new BufferedImage[NUM_CASTLES]; BufferedImage images[];
if(castlesColored.containsKey(color))
if(images[index] != null) images = castlesColored.get(color);
return images[index]; else
images = new BufferedImage[NUM_CASTLES];
BufferedImage castleGeneric = castlesColored.get(Color.WHITE)[index];
images[index] = colorImage(castleGeneric, color); if(images[index] != null)
castlesColored.put(color, images); return images[index];
return images[index];
} BufferedImage castleGeneric = castlesColored.get(Color.WHITE)[index];
images[index] = colorImage(castleGeneric, color);
public BufferedImage getDice(int value) { castlesColored.put(color, images);
if(!resourcesLoaded) return images[index];
return null; }
return dices[value % dices.length]; public BufferedImage getDice(int value) {
} if(!resourcesLoaded)
return null;
public BufferedImage getCheckIcon() {
return this.check; return dices[value % dices.length];
} }
public BufferedImage getUnitIcon() { public BufferedImage getCheckIcon() {
return this.unit; return this.check;
} }
public BufferedImage getPlusIcon() { public BufferedImage getUnitIcon() {
return this.plus; return this.unit;
} }
public BufferedImage getArrowIcon() { public BufferedImage getPlusIcon() {
return this.arrow; return this.plus;
} }
public BufferedImage getSwordsIcon() { public BufferedImage getArrowIcon() {
return this.swords; return this.arrow;
} }
public BufferedImage getArrowIconDeactivated() { public BufferedImage getSwordsIcon() {
return this.arrowDeactivated; return this.swords;
} }
public BufferedImage[] getSoldiers() { public BufferedImage getArrowIconDeactivated() {
return this.soldiers; return this.arrowDeactivated;
} }
public List<String> getCastleNames() { public BufferedImage[] getSoldiers() {
return castleNames; return this.soldiers;
} }
public BufferedImage getPlusIconDeactivated() { public List<String> getCastleNames() {
return this.plusDeactivated; return castleNames;
} }
public Font getCelticFont() { public BufferedImage[] getJokers() {
return this.celticFont; return this.jokers;
} }
}
public BufferedImage getPlusIconDeactivated() {
return this.plusDeactivated;
}
public Font getCelticFont() {
return this.celticFont;
}
}