added part of javadoc

This commit is contained in:
musilto9 2020-06-10 14:27:49 +02:00
parent 05477a578c
commit 3a2b14cee8
36 changed files with 736 additions and 210 deletions

View File

@ -9,8 +9,8 @@ import java.util.*;
* @version 2.1, 2017-02-23 * @version 2.1, 2017-02-23
*/ */
public class AStar { public class AStar {
private static int DEFAULT_HV_COST = 1; private static final int DEFAULT_HV_COST = 1;
private static int DEFAULT_DIAGONAL_COST = 1000000000; private static final int DEFAULT_DIAGONAL_COST = 1;
private int hvCost; private int hvCost;
private int diagonalCost; private int diagonalCost;
private Node[][] searchArea; private Node[][] searchArea;
@ -90,10 +90,10 @@ public class AStar {
int lowerRow = row + 1; int lowerRow = row + 1;
if (lowerRow < getSearchArea().length) { if (lowerRow < getSearchArea().length) {
if (col - 1 >= 0) { if (col - 1 >= 0) {
checkNode(currentNode, col - 1, lowerRow, getDiagonalCost()); // Comment this line if diagonal movements are not allowed // checkNode(currentNode, col - 1, lowerRow, getDiagonalCost()); // Comment this line if diagonal movements are not allowed
} }
if (col + 1 < getSearchArea()[0].length) { if (col + 1 < getSearchArea()[0].length) {
checkNode(currentNode, col + 1, lowerRow, getDiagonalCost()); // Comment this line if diagonal movements are not allowed // checkNode(currentNode, col + 1, lowerRow, getDiagonalCost()); // Comment this line if diagonal movements are not allowed
} }
checkNode(currentNode, col, lowerRow, getHvCost()); checkNode(currentNode, col, lowerRow, getHvCost());
} }
@ -116,10 +116,10 @@ public class AStar {
int upperRow = row - 1; int upperRow = row - 1;
if (upperRow >= 0) { if (upperRow >= 0) {
if (col - 1 >= 0) { if (col - 1 >= 0) {
checkNode(currentNode, col - 1, upperRow, getDiagonalCost()); // Comment this if diagonal movements are not allowed // checkNode(currentNode, col - 1, upperRow, getDiagonalCost()); // Comment this if diagonal movements are not allowed
} }
if (col + 1 < getSearchArea()[0].length) { if (col + 1 < getSearchArea()[0].length) {
checkNode(currentNode, col + 1, upperRow, getDiagonalCost()); // Comment this if diagonal movements are not allowed // checkNode(currentNode, col + 1, upperRow, getDiagonalCost()); // Comment this if diagonal movements are not allowed
} }
checkNode(currentNode, col, upperRow, getHvCost()); checkNode(currentNode, col, upperRow, getHvCost());
} }

View File

@ -11,19 +11,15 @@ import java.awt.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
/**
* The main class of our application that holds JFrame which displays the whole game
*/
public class Game extends JFrame { public class Game extends JFrame {
private static final int WINDOW_WIDTH = 13;
private static final int WINDOW_HEIGHT = 13;
public static final int CELL_SIZE = 60; public static final int CELL_SIZE = 60;
private WindowOfMenu menu; private final WindowOfMenu menu;
private WindowOfFreeMove freeMove; private final WindowOfFreeMove freeMove;
private WindowOfBattle battle; private final WindowOfBattle battle;
private TilesetOverview tilesetOverview;
public WindowOfMenu getMenu() {
return menu;
}
public WindowOfFreeMove getFreeMove() { public WindowOfFreeMove getFreeMove() {
return freeMove; return freeMove;
@ -42,21 +38,9 @@ public class Game extends JFrame {
menu = new WindowOfMenu(this); menu = new WindowOfMenu(this);
battle = new WindowOfBattle(this); battle = new WindowOfBattle(this);
//tohle spustí na začátku menu
add(menu); add(menu);
menu.start(); menu.start();
//tohle spustí na začátku hru
// add(freeMove);
// freeMove.start(true);
//tohle spustí na začátku bitvu
// add(battle);
// battle.start("storageroombattle");
//Tohle spustí na začátku tileset overview
//new LevelEditor();
setDefaultCloseOperation(EXIT_ON_CLOSE); setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true); setUndecorated(true);
setLocationRelativeTo(null); setLocationRelativeTo(null);

View File

@ -12,6 +12,9 @@ import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Scanner; import java.util.Scanner;
/**
* This class manages and holds tileset and all matrices of images to be pained
*/
public class ImageCell { public class ImageCell {
private static BufferedImage image; private static BufferedImage image;
private LinkedList<BufferedImage> imagesOfTiles; private LinkedList<BufferedImage> imagesOfTiles;
@ -21,11 +24,20 @@ public class ImageCell {
private int[][] mapBackground; private int[][] mapBackground;
private int[][] mapForeground; private int[][] mapForeground;
/**
* @param width is width of new map
* @param height is height of new map
* Creates new matrices based on winth and height values
*/
public void readMapFile(int width, int height) { public void readMapFile(int width, int height) {
mapBackground = new int[width][height]; mapBackground = new int[width][height];
mapForeground = new int[width][height]; mapForeground = new int[width][height];
} }
/**
* @param name is name of map file
* Reads and parses (map-name)-tileset.txt file into matrices and arrays, separates values and passes them on for further parsing
*/
public void readMapFile(String name) { public void readMapFile(String name) {
try { try {
mapBackground = new int[WindowOfFreeMove.CANVAS_WIDTH][WindowOfFreeMove.CANVAS_HEIGHT]; mapBackground = new int[WindowOfFreeMove.CANVAS_WIDTH][WindowOfFreeMove.CANVAS_HEIGHT];
@ -62,6 +74,10 @@ public class ImageCell {
} }
} }
/**
* @param tilesetInfo is name of tileset image
* Parses tileset image into a tileset (array)
*/
public void imageTileset(String[] tilesetInfo) { public void imageTileset(String[] tilesetInfo) {
try { try {
image = ImageIO.read(new File("src/main/resources/tilesets/" + tilesetInfo[1])); image = ImageIO.read(new File("src/main/resources/tilesets/" + tilesetInfo[1]));
@ -96,6 +112,10 @@ public class ImageCell {
} }
} }
/**
* @param file is name of map tp be parsed
* Parses (map-name)-objectset.txt file into a matrix
*/
public void imageObjectset(String file) { public void imageObjectset(String file) {
try { try {
File objectFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + file + "-objectset.txt"); File objectFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + file + "-objectset.txt");
@ -113,6 +133,10 @@ public class ImageCell {
} }
} }
/**
* @param cellInfo is text representation of cellMap
* Parses text into a hash map
*/
public void loadCellMap(String[] cellInfo) { public void loadCellMap(String[] cellInfo) {
if (cellMap == null) if (cellMap == null)
cellMap = new HashMap<String, Integer>(); cellMap = new HashMap<String, Integer>();
@ -133,6 +157,10 @@ public class ImageCell {
cellMap.put(cellInfo[1], Integer.parseInt(cellInfo[2])); cellMap.put(cellInfo[1], Integer.parseInt(cellInfo[2]));
} }
/**
* @param itemInfo is name of item image
* Parses item image into array
*/
public void imageItem(String itemInfo) { public void imageItem(String itemInfo) {
int imageWidth = 0; int imageWidth = 0;
int imageHeight = 0; int imageHeight = 0;

View File

@ -5,6 +5,9 @@ import java.awt.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
/**
* This class holds images to be painted in dialog
*/
public class ImageDialog { public class ImageDialog {
private String name; private String name;
private Image image; private Image image;
@ -21,6 +24,9 @@ public class ImageDialog {
parseImage(); parseImage();
} }
/**
* Parses background image for dialog
*/
public static void parseBackground() { public static void parseBackground() {
try { try {
dialogBack = ImageIO.read(new File("src/main/resources/dialogs/DialogBox.png")); dialogBack = ImageIO.read(new File("src/main/resources/dialogs/DialogBox.png"));
@ -29,6 +35,9 @@ public class ImageDialog {
} }
} }
/**
* Parses face image for dialog
*/
private void parseImage(){ private void parseImage(){
try { try {
image = ImageIO.read(new File("src/main/resources/characters/" + name.substring(0, name.indexOf("-face.png")) + "/" + name)); image = ImageIO.read(new File("src/main/resources/characters/" + name.substring(0, name.indexOf("-face.png")) + "/" + name));

View File

@ -6,11 +6,18 @@ import java.awt.image.BufferedImage;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
/**
* This class images of doors to be painted
*/
public class ImageDoor { public class ImageDoor {
private BufferedImage image; private BufferedImage image;
private BufferedImage[] imagesOfDoor; private BufferedImage[] imagesOfDoor;
private int size; private int size;
/**
* @param rectangles is array of door images
* Parses images of door into an array
*/
public void setAllImagesOfDoor(Rectangle[] rectangles){ public void setAllImagesOfDoor(Rectangle[] rectangles){
imagesOfDoor = new BufferedImage[4]; imagesOfDoor = new BufferedImage[4];

View File

@ -9,12 +9,19 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Scanner; import java.util.Scanner;
/**
* This class holds image of hero to be painted
*/
public class ImagePerson { public class ImagePerson {
private BufferedImage image; private BufferedImage image;
private BufferedImage[] imagesOfDirection; private BufferedImage[] imagesOfDirection;
private int subimageWidth; private int subimageWidth;
private int subimageHeight; private int subimageHeight;
/**
* @param rectangles is array of hero images
* Parses images of hero into an array
*/
public void setAllImagesOfDirection(Rectangle[] rectangles){ public void setAllImagesOfDirection(Rectangle[] rectangles){
imagesOfDirection = new BufferedImage[12]; imagesOfDirection = new BufferedImage[12];
@ -46,6 +53,11 @@ public class ImagePerson {
setAllImagesOfDirection(rectangles); setAllImagesOfDirection(rectangles);
} }
/**
* @param img is image to be resized
* @return resized image
* Resizes image to be properly displayed in game
*/
public BufferedImage resize(BufferedImage img) { public BufferedImage resize(BufferedImage img) {
Image tmp; Image tmp;
if (subimageWidth > WindowOfFreeMove.CELL_SIZE) { if (subimageWidth > WindowOfFreeMove.CELL_SIZE) {

View File

@ -4,10 +4,13 @@ import javax.swing.*;
import java.awt.*; import java.awt.*;
import java.util.LinkedList; import java.util.LinkedList;
/**
* This class displays cellMap configuration
*/
public class CellSetConfig { public class CellSetConfig {
private LevelEditor editor; private final LevelEditor editor;
private JLayeredPane view; private final JLayeredPane view;
private JScrollPane scrollInfo; private JScrollPane scrollInfo;
public CellSetConfig(LevelEditor editor, JScrollPane scrollInfo) { public CellSetConfig(LevelEditor editor, JScrollPane scrollInfo) {
@ -16,6 +19,9 @@ public class CellSetConfig {
this.scrollInfo = scrollInfo; this.scrollInfo = scrollInfo;
} }
/**
* Displays fields with values from cellMap
*/
public void displayCellSetConfig() { public void displayCellSetConfig() {
int offset = 0; int offset = 0;
String[] array = {"BLOCK", "INTER", "TRIGGER", "MOVETO", "DOOR/DOORTO", "CHEST"}; //EMPTY is missing on purpose, DOOR & DOORTO are combined on purpose String[] array = {"BLOCK", "INTER", "TRIGGER", "MOVETO", "DOOR/DOORTO", "CHEST"}; //EMPTY is missing on purpose, DOOR & DOORTO are combined on purpose
@ -80,18 +86,28 @@ public class CellSetConfig {
infoPanel.add(saveInfo); infoPanel.add(saveInfo);
// scrollInfo.revalidate();
// scrollInfo.requestFocus();
view.add(scrollInfo); view.add(scrollInfo);
scrollInfo.repaint(); scrollInfo.repaint();
} }
/**
* @param name is name of label
* @param offset is offset of label
* @return new JLabel
* Creates new JLabel with name of cell type
*/
private JLabel nameLabel(String name, int offset) { private JLabel nameLabel(String name, int offset) {
JLabel label = new JLabel("<html><div style='width: 250; text-align:center; font-size: 16'>" + name + "</div></html>"); JLabel label = new JLabel("<html><div style='width: 250; text-align:center; font-size: 16'>" + name + "</div></html>");
label.setBounds(0, offset, 250, 20); label.setBounds(0, offset, 250, 20);
return label; return label;
} }
/**
* @param name is name of label
* @param offset is offset of label
* @return new JLabel
* Creates new JLabel with image of the selected tile
*/
private JLabel iconLabel(String name, int offset) { private JLabel iconLabel(String name, int offset) {
JLabel label = new JLabel(); JLabel label = new JLabel();
label.setBounds(0, offset + 40, 50, 50); label.setBounds(0, offset + 40, 50, 50);
@ -101,12 +117,23 @@ public class CellSetConfig {
return label; return label;
} }
/**
* @param offset is offset of label
* @return new JLabel
* Creates label with 'Inner Value:' text
*/
private JLabel valueLabel(int offset) { private JLabel valueLabel(int offset) {
JLabel label = new JLabel("Inner Value:"); JLabel label = new JLabel("Inner Value:");
label.setBounds(80, offset + 40, 100, 30); label.setBounds(80, offset + 40, 100, 30);
return label; return label;
} }
/**
* @param name is name of field
* @param offset is offset of field
* @return new JTextField
* Creates text field for value input
*/
private JTextField numField(String name, int offset) { private JTextField numField(String name, int offset) {
JTextField field = new JTextField(String.valueOf(editor.getCellMap().get(name))); JTextField field = new JTextField(String.valueOf(editor.getCellMap().get(name)));
field.setName(name); field.setName(name);
@ -114,6 +141,13 @@ public class CellSetConfig {
return field; return field;
} }
/**
* @param iconLabel is label to be changed
* @param tileNum is text field to be changed
* @param offset is offset of button
* @return new JButton
* Creates new button for importing value from Tileset Overview
*/
private JButton importButton(JLabel iconLabel, JTextField tileNum, int offset) { private JButton importButton(JLabel iconLabel, JTextField tileNum, int offset) {
JButton button = new JButton("Import selected tile"); JButton button = new JButton("Import selected tile");
button.setVisible(false); button.setVisible(false);
@ -131,6 +165,12 @@ public class CellSetConfig {
return button; return button;
} }
/**
* @param importButton is reference for connected import button
* @param offset is offset of button
* @return new JButton
* Creates new button for selecting a tile in Tileset Overview
*/
private JButton selectButton(JButton importButton, int offset) { private JButton selectButton(JButton importButton, int offset) {
JButton button = new JButton("Select tile"); JButton button = new JButton("Select tile");
button.setBounds(0, offset + 100, 90, 30); button.setBounds(0, offset + 100, 90, 30);
@ -145,6 +185,11 @@ public class CellSetConfig {
return button; return button;
} }
/**
* @param offset is offset of label
* @return new JLabel
* Creates new label that is used as a divider between different blocks of fields
*/
private JLabel dividerLabel(int offset) { private JLabel dividerLabel(int offset) {
JLabel label = new JLabel(); JLabel label = new JLabel();
label.setBounds(0, offset + 140, 255, 1); label.setBounds(0, offset + 140, 255, 1);

View File

@ -3,6 +3,9 @@ package ruscz.game.gameOfProd.LevelEditor;
import javax.swing.*; import javax.swing.*;
import java.util.LinkedList; import java.util.LinkedList;
/**
* This class holds and displays detailed cell info for Physical layer
*/
public class DetailedCellInfo extends JPanel { public class DetailedCellInfo extends JPanel {
private LinkedList<JRadioButton> radioButtons; private LinkedList<JRadioButton> radioButtons;
@ -19,6 +22,10 @@ public class DetailedCellInfo extends JPanel {
this.j = j; this.j = j;
} }
/**
* @param type is type of cell
* Displays detailed info based on the type of cell provided
*/
public void displayDetailedCellInfo(String type) { public void displayDetailedCellInfo(String type) {
removeAll(); removeAll();
setVisible(false); setVisible(false);
@ -60,6 +67,13 @@ public class DetailedCellInfo extends JPanel {
setInfo(); setInfo();
} }
/**
* @param title is tile of this field
* @param trueLabel is true value
* @param falseLabel is false value
* @param offset is offset from top of menu
* Displays set of radio buttons for true/false selection
*/
private void trueFalseInfo(String title, String trueLabel, String falseLabel, int offset) { private void trueFalseInfo(String title, String trueLabel, String falseLabel, int offset) {
JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>Is " + title + "</div></html>"); JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>Is " + title + "</div></html>");
label.setBounds(0, offset, 260, 20); label.setBounds(0, offset, 260, 20);
@ -87,6 +101,12 @@ public class DetailedCellInfo extends JPanel {
setVisible(true); setVisible(true);
} }
/**
* @param title is tile of this field
* @param fieldName is name of text field
* @param offset is offset from top of menu
* Displays one text field with a name
*/
private void fieldInfo(String title, String fieldName, int offset) { private void fieldInfo(String title, String fieldName, int offset) {
JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>" + title + "</div></html>"); JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>" + title + "</div></html>");
label.setBounds(0, offset, 260, 20); label.setBounds(0, offset, 260, 20);
@ -104,6 +124,9 @@ public class DetailedCellInfo extends JPanel {
setVisible(true); setVisible(true);
} }
/**
* Displays set of three radio buttons for selection
*/
private void upperLowerInfo() { private void upperLowerInfo() {
JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>Half Block</div></html>"); JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>Half Block</div></html>");
label.setBounds(0, 100, 260, 20); label.setBounds(0, 100, 260, 20);
@ -138,6 +161,10 @@ public class DetailedCellInfo extends JPanel {
setVisible(true); setVisible(true);
} }
/**
* @param offset is offset from top of menu
* Displays set of four radio buttons for direction selection
*/
private void directionInfo(int offset) { private void directionInfo(int offset) {
JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>Direction Out</div></html>"); JLabel label = new JLabel("<html><div style='text-align: center; width: 260'>Direction Out</div></html>");
label.setBounds(0, offset, 260, 20); label.setBounds(0, offset, 260, 20);
@ -180,6 +207,11 @@ public class DetailedCellInfo extends JPanel {
setVisible(true); setVisible(true);
} }
/**
* @param type type of cell
* @return cell value as it would be in a text file
* Saves all attributes from menu into text
*/
public String getCellInfo(String type) { public String getCellInfo(String type) {
String info = type; String info = type;
if (type.equals("BLOCK")) { if (type.equals("BLOCK")) {
@ -229,6 +261,11 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @param type type of cell
* @return changed type of cell
* Changes type of cell based on visibility value
*/
private String getVisibleInfo(String type) { private String getVisibleInfo(String type) {
String info = ""; String info = "";
for (JRadioButton button : radioButtons) { for (JRadioButton button : radioButtons) {
@ -244,6 +281,10 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @return text to determine if block is half-block
* Checks if a block is supposed to be half-block
*/
private String getUpperLowerInfo() { private String getUpperLowerInfo() {
String info = ""; String info = "";
for (JRadioButton button : radioButtons) { for (JRadioButton button : radioButtons) {
@ -259,6 +300,12 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @param fieldName name of field to be saved
* @param isRequired is this field required to be filled in
* @return value form field
* Saves field value
*/
private String getFieldInfo(String fieldName, boolean isRequired) { private String getFieldInfo(String fieldName, boolean isRequired) {
String info = ""; String info = "";
for (JTextField field : textFields) { for (JTextField field : textFields) {
@ -276,6 +323,11 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @param fieldName name of field to be saved
* @return value form field
* Checks id field value is an integer and saves it
*/
private String getFieldIntegerInfo(String fieldName) { private String getFieldIntegerInfo(String fieldName) {
String info = ""; String info = "";
for (JTextField field : textFields) { for (JTextField field : textFields) {
@ -291,6 +343,12 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @param trueLabel is name of true button
* @param falseLabel is name of false button
* @return text representation
* Saves true/false value as text
*/
private String getTrueFalseInfo(String trueLabel, String falseLabel) { private String getTrueFalseInfo(String trueLabel, String falseLabel) {
String info = ""; String info = "";
for (JRadioButton button : radioButtons) { for (JRadioButton button : radioButtons) {
@ -306,6 +364,10 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @return text representation of direction
* Saves direction info as text
*/
private String getDirectionInfo() { private String getDirectionInfo() {
String info = ""; String info = "";
for (JRadioButton button : radioButtons) { for (JRadioButton button : radioButtons) {
@ -329,6 +391,11 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @param type type of cell
* @return changed type of cell
* Changes type of cell based on direction value
*/
private String getDoorInfo(String type) { private String getDoorInfo(String type) {
String info = ""; String info = "";
if (j == 0 || editor.getCellArray()[i][j+1].split(",")[0].equals(type)) { if (j == 0 || editor.getCellArray()[i][j+1].split(",")[0].equals(type)) {
@ -340,6 +407,10 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* @return text representation
* Saves if door is supposed to be locked
*/
private String getLockedInfo() { private String getLockedInfo() {
String info = ""; String info = "";
for (JTextField field : textFields) { for (JTextField field : textFields) {
@ -350,6 +421,9 @@ public class DetailedCellInfo extends JPanel {
return info; return info;
} }
/**
* Loads cell info into fields
*/
private void setInfo() { private void setInfo() {
String[] info = editor.getCellArray()[i][j].split(","); String[] info = editor.getCellArray()[i][j].split(",");
String type = info[0]; String type = info[0];
@ -396,6 +470,10 @@ public class DetailedCellInfo extends JPanel {
} }
} }
/**
* @param value is text true/false value
* Parses value and checks corresponding button
*/
private void setTrueFalseInfo(String value) { private void setTrueFalseInfo(String value) {
if (value.equals("false")) { if (value.equals("false")) {
for (JRadioButton btn : radioButtons) { for (JRadioButton btn : radioButtons) {
@ -423,6 +501,10 @@ public class DetailedCellInfo extends JPanel {
} }
} }
/**
* @param value is text half-block value
* Parses value and checks corresponding button
*/
private void setUpperLowerInfo(String value) { private void setUpperLowerInfo(String value) {
String name = ""; String name = "";
switch (value) { switch (value) {
@ -441,6 +523,11 @@ public class DetailedCellInfo extends JPanel {
} }
} }
/**
* @param fieldName is name of field to be filled in
* @param value is new value of field
* Fills a selected field with value
*/
private void setFieldInfo(String fieldName, String value) { private void setFieldInfo(String fieldName, String value) {
for (JTextField field : textFields) { for (JTextField field : textFields) {
if (field.getName().equals(fieldName)) { if (field.getName().equals(fieldName)) {
@ -450,6 +537,10 @@ public class DetailedCellInfo extends JPanel {
} }
} }
/**
* @param value is text direction value
* Parses value and checks corresponding button
*/
private void setDirectionInfo(String value) { private void setDirectionInfo(String value) {
String name = ""; String name = "";
switch (value) { switch (value) {

View File

@ -1,11 +0,0 @@
package ruscz.game.gameOfProd.LevelEditor;
public class EditorManager {
private TilesetOverview overview;
private LevelEditor editor;
public EditorManager() {
editor = new LevelEditor();
}
}

View File

@ -3,6 +3,9 @@ package ruscz.game.gameOfProd.LevelEditor;
import java.io.FileWriter; import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
/**
* This class manages saving map from level editor to files that can be used in game
*/
public class EditorSaveManager { public class EditorSaveManager {
private LevelEditor editor; private LevelEditor editor;
@ -11,6 +14,9 @@ public class EditorSaveManager {
this.editor = editor; this.editor = editor;
} }
/**
* Saves map into files
*/
public void saveMap() { public void saveMap() {
boolean isValid = validate(); boolean isValid = validate();
if (isValid) { if (isValid) {
@ -25,11 +31,18 @@ public class EditorSaveManager {
} }
} }
/**
* @return is tileset valid
* Checks if a tileset exists and is not empty
*/
public boolean validate() { public boolean validate() {
boolean valid = editor.getImagesOfTiles() != null && editor.getImagesOfTiles().size() > 0; boolean valid = editor.getImagesOfTiles() != null && editor.getImagesOfTiles().size() > 0;
return valid; return valid;
} }
/**
* Saves Object layer into (map-name)-objectset.txt file
*/
private void saveObjectSet() { private void saveObjectSet() {
try { try {
FileWriter writer = new FileWriter("src/main/resources/maps/custom/" + editor.getMap().getName() + "-objectset.txt"); FileWriter writer = new FileWriter("src/main/resources/maps/custom/" + editor.getMap().getName() + "-objectset.txt");
@ -49,6 +62,9 @@ public class EditorSaveManager {
} }
} }
/**
* Saves Physical layer (mapArray) into (map-name).txt file
*/
private void saveCellSet() { private void saveCellSet() {
try { try {
FileWriter writer = new FileWriter("src/main/resources/maps/custom/" + editor.getMap().getName() + ".txt"); FileWriter writer = new FileWriter("src/main/resources/maps/custom/" + editor.getMap().getName() + ".txt");
@ -69,6 +85,9 @@ public class EditorSaveManager {
} }
} }
/**
* Saves Tile layer (mapArray) into (map-name)-tileset.txt file
*/
private void saveTileSet() { private void saveTileSet() {
try { try {
FileWriter writer = new FileWriter("src/main/resources/maps/custom/" + editor.getMap().getName() + "-tileset.txt"); FileWriter writer = new FileWriter("src/main/resources/maps/custom/" + editor.getMap().getName() + "-tileset.txt");

View File

@ -6,6 +6,9 @@ import java.awt.event.MouseEvent;
import java.awt.event.MouseListener; import java.awt.event.MouseListener;
import java.util.Arrays; import java.util.Arrays;
/**
* This class displays detailed info about selected cell
*/
public class InfoManager { public class InfoManager {
private LevelEditor editor; private LevelEditor editor;
@ -19,6 +22,13 @@ public class InfoManager {
this.view = editor.getView(); this.view = editor.getView();
} }
/**
* @param label is label to be parsed and displayed
* @param layer is name of layer on which the cell is located
* @param x is X value of cell
* @param y is Y value of cell
* Decides which type of info is needed for a selected cell
*/
protected void displayInfo(JLabel label, String layer, int x, int y) { protected void displayInfo(JLabel label, String layer, int x, int y) {
if (info != null) { if (info != null) {
info.removeAll(); info.removeAll();
@ -51,6 +61,13 @@ public class InfoManager {
view.revalidate(); view.revalidate();
} }
/**
* @param label is label to be parsed and displayed
* @param x is X value of cell
* @param y is Y value of cell
* @param isObject is cell on object layer
* Displays info regarding object cells and tile cells
*/
private void displayObjectAndTileInfo(JLabel label, int x, int y, boolean isObject) { private void displayObjectAndTileInfo(JLabel label, int x, int y, boolean isObject) {
JLabel infoLabel = new JLabel(); JLabel infoLabel = new JLabel();
infoLabel.setBounds(0, 0, 50, 50); infoLabel.setBounds(0, 0, 50, 50);
@ -158,6 +175,12 @@ public class InfoManager {
info.add(saveInfo); info.add(saveInfo);
} }
/**
* @param label is label to be parsed and displayed
* @param x is X value of cell
* @param y is Y value of cell
* Displays info regarding 'physical' cells (from mapArray)
*/
private void displayCellInfo(JLabel label, int x, int y) { private void displayCellInfo(JLabel label, int x, int y) {
String[] array = {"EMPTY", "BLOCK", "INTER", "TRIGGER", "MOVETO", "DOOR", "DOORTO", "CHEST"}; String[] array = {"EMPTY", "BLOCK", "INTER", "TRIGGER", "MOVETO", "DOOR", "DOORTO", "CHEST"};
@ -209,10 +232,6 @@ public class InfoManager {
openCellMap.setBounds(30, 600, 200, 30); openCellMap.setBounds(30, 600, 200, 30);
openCellMap.addActionListener(e -> { openCellMap.addActionListener(e -> {
// info.removeAll();
// info.revalidate();
// detailedCellInfo.removeAll();
// detailedCellInfo.revalidate();
view.remove(info); view.remove(info);
view.remove(detailedCellInfo); view.remove(detailedCellInfo);
new CellSetConfig(editor, scrollInfo).displayCellSetConfig(); new CellSetConfig(editor, scrollInfo).displayCellSetConfig();
@ -244,6 +263,12 @@ public class InfoManager {
info.add(saveInfo); info.add(saveInfo);
} }
/**
* @param value is value of cell to ba parsed
* @param x is X value of cell
* @param y is Y value of cell
* Puts DOOR cell into correct places in map's cell matrix
*/
private void saveDoor(String value, int x, int y) { private void saveDoor(String value, int x, int y) {
if (value.split(",")[0].contains("DOOR") && y == 0) { if (value.split(",")[0].contains("DOOR") && y == 0) {
value = value.substring(0, value.indexOf(",")).toLowerCase() + value.substring(value.indexOf(",")); value = value.substring(0, value.indexOf(",")).toLowerCase() + value.substring(value.indexOf(","));

View File

@ -19,11 +19,15 @@ import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class hold the JFrame that displays level editor
* It also holds references to all major classes used in level editor
*/
public class LevelEditor extends JFrame { public class LevelEditor extends JFrame {
private JLayeredPane view; private final JLayeredPane view;
private TilesetOverview overview; private TilesetOverview overview;
private JPanel menu; private final JPanel menu;
private JLabel errorMessage; private JLabel errorMessage;
private InfoManager infoManager; private InfoManager infoManager;
@ -123,6 +127,12 @@ public class LevelEditor extends JFrame {
} }
} }
/**
* @param name is name of new map
* @param width is width of new map
* @param height is height of new map
* Creates new map and populates it's cell matrix and passes it on
*/
public void createNewMap(String name, int width, int height) { public void createNewMap(String name, int width, int height) {
TypeOfCell[][] mapArray = new TypeOfCell[width][height]; TypeOfCell[][] mapArray = new TypeOfCell[width][height];
for (int i = 0; i < width; i++) { for (int i = 0; i < width; i++) {
@ -143,6 +153,9 @@ public class LevelEditor extends JFrame {
startMapEditor(); startMapEditor();
} }
/**
* Displays level editor containing newly created map
*/
public void startMapEditor() { public void startMapEditor() {
JPanel menu = new JPanel(); JPanel menu = new JPanel();
@ -204,10 +217,7 @@ public class LevelEditor extends JFrame {
view.revalidate(); view.revalidate();
view.repaint(); view.repaint();
} }
if (objectSet.isVisible()) objectSet.setVisible(false); objectSet.setVisible(!objectSet.isVisible());
else {
objectSet.setVisible(true);
}
}); });
JLabel cellLabel = new JLabel("Physical (cell) Layer"); JLabel cellLabel = new JLabel("Physical (cell) Layer");
@ -223,8 +233,7 @@ public class LevelEditor extends JFrame {
view.revalidate(); view.revalidate();
view.repaint(); view.repaint();
} }
if (cellSet.isVisible()) cellSet.setVisible(false); cellSet.setVisible(!cellSet.isVisible());
else cellSet.setVisible(true);
}); });
JLabel tileLabel = new JLabel("Tile Layer"); JLabel tileLabel = new JLabel("Tile Layer");
@ -240,8 +249,7 @@ public class LevelEditor extends JFrame {
view.revalidate(); view.revalidate();
view.repaint(); view.repaint();
} }
if (tileSet.isVisible()) tileSet.setVisible(false); tileSet.setVisible(!tileSet.isVisible());
else tileSet.setVisible(true);
}); });
errorMessage = new JLabel(); errorMessage = new JLabel();
@ -295,6 +303,9 @@ public class LevelEditor extends JFrame {
view.repaint(); view.repaint();
} }
/**
* Populates cellMap with starting values
*/
private void initializeCellMap() { private void initializeCellMap() {
cellMap.put("BLOCK", 0); cellMap.put("BLOCK", 0);
cellMap.put("INTER", 0); cellMap.put("INTER", 0);
@ -304,11 +315,19 @@ public class LevelEditor extends JFrame {
cellMap.put("CHEST", 0); cellMap.put("CHEST", 0);
} }
/**
* @param message is text to be displayed
* Displays message as an error in the error field
*/
protected void displayError(String message) { protected void displayError(String message) {
errorMessage.setText("<html><span style='color: red'>" + message + "</span></html>"); errorMessage.setText("<html><span style='color: red'>" + message + "</span></html>");
errorMessage.setVisible(true); errorMessage.setVisible(true);
} }
/**
* @param message is text to be displayed
* Displays message as a normal text in the error field
*/
protected void displayMessage(String message) { protected void displayMessage(String message) {
errorMessage.setText(message); errorMessage.setText(message);
errorMessage.setVisible(true); errorMessage.setVisible(true);

View File

@ -9,20 +9,23 @@ import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.util.LinkedList; import java.util.LinkedList;
/**
* This class manages all map layers (object layer, physical layer, tile layer)
*/
public class MapLayersManager { public class MapLayersManager {
private LevelEditor editor; private final LevelEditor editor;
private JLayeredPane view; private final JLayeredPane view;
private Map map; private final Map map;
private LinkedList<BufferedImage> imagesOfTiles; private LinkedList<BufferedImage> imagesOfTiles;
private JLayeredPane mapLayers; private final JLayeredPane mapLayers;
private JPanel objectSet; private final JPanel objectSet;
private JPanel cellSet; private final JPanel cellSet;
private JPanel tileSet; private final JPanel tileSet;
private int width; private final int width;
private int height; private final int height;
public MapLayersManager(LevelEditor editor) { public MapLayersManager(LevelEditor editor) {
this.editor = editor; this.editor = editor;
@ -56,6 +59,9 @@ public class MapLayersManager {
mapLayers.add(tileSet, JLayeredPane.DEFAULT_LAYER); mapLayers.add(tileSet, JLayeredPane.DEFAULT_LAYER);
} }
/**
* Repaints all layers
*/
protected void repaintSets() { protected void repaintSets() {
imagesOfTiles = editor.getImagesOfTiles(); imagesOfTiles = editor.getImagesOfTiles();
repaintObjectset(); repaintObjectset();
@ -63,6 +69,9 @@ public class MapLayersManager {
repaintTileset(); repaintTileset();
} }
/**
* Creates new Object layer from map foreground matrix
*/
protected void repaintObjectset() { protected void repaintObjectset() {
objectSet.removeAll(); objectSet.removeAll();
@ -70,7 +79,7 @@ public class MapLayersManager {
for (int j = 0; j < height; j++) { for (int j = 0; j < height; j++) {
JLabel object = new JLabel(); JLabel object = new JLabel();
if (imagesOfTiles == null || imagesOfTiles.size() == 0) { if (imagesOfTiles == null || imagesOfTiles.size() == 0) {
object.setText("<html><div style='text-align: center; width: 50'>" + String.valueOf(map.getImageCell().getMapForeground()[i][j]) + "</div></html>"); object.setText("<html><div style='text-align: center; width: 50'>" + map.getImageCell().getMapForeground()[i][j] + "</div></html>");
object.setHorizontalTextPosition(JLabel.CENTER); object.setHorizontalTextPosition(JLabel.CENTER);
objectSet.setOpaque(true); objectSet.setOpaque(true);
objectSet.setBackground(Color.RED); objectSet.setBackground(Color.RED);
@ -100,6 +109,9 @@ public class MapLayersManager {
view.repaint(); view.repaint();
} }
/**
* Creates new Physical layer from map cell matrix (mapArray)
*/
protected void repaintCellSet() { protected void repaintCellSet() {
cellSet.removeAll(); cellSet.removeAll();
@ -132,6 +144,9 @@ public class MapLayersManager {
view.repaint(); view.repaint();
} }
/**
* Creates new Tile layer from map background matrix
*/
protected void repaintTileset() { protected void repaintTileset() {
tileSet.removeAll(); tileSet.removeAll();
@ -168,6 +183,12 @@ public class MapLayersManager {
view.repaint(); view.repaint();
} }
/**
* @param cell is cell to ba updated
* @param i is cell's Y value
* @param j is cell's X value
* Sets cell a corresponding icon from cellMap dictionary
*/
private void setCellIcon(JLabel cell, int i, int j) { private void setCellIcon(JLabel cell, int i, int j) {
String value; String value;
String[] info = editor.getCellArray()[i][j].split(","); String[] info = editor.getCellArray()[i][j].split(",");
@ -198,6 +219,11 @@ public class MapLayersManager {
} }
} }
/**
* @param img is image to be converted
* @return converted image
* Converts image to buffered image
*/
private BufferedImage toBufferedImage(Image img) { private BufferedImage toBufferedImage(Image img) {
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = bimage.createGraphics(); Graphics2D bGr = bimage.createGraphics();
@ -206,6 +232,12 @@ public class MapLayersManager {
return bimage; return bimage;
} }
/**
* @param img is image to be tilified
* @param isUp is an upper block
* @return tilified image
* Converts regulat image (50x50px) to a half block (upper or lower)
*/
private BufferedImage tilify(BufferedImage img, boolean isUp) { private BufferedImage tilify(BufferedImage img, boolean isUp) {
BufferedImage image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB); BufferedImage image = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
Graphics2D bGr = image.createGraphics(); Graphics2D bGr = image.createGraphics();
@ -215,6 +247,11 @@ public class MapLayersManager {
return image; return image;
} }
/**
* @param cell is cell to be updated
* @param info cell text value
* Sets corresponding image to a door cell (and one cell above/lower)
*/
private void setDoorImage(JLabel cell, String[] info) { private void setDoorImage(JLabel cell, String[] info) {
if (editor.getCellMap().get("DOOR/DOORTO") == 0) { if (editor.getCellMap().get("DOOR/DOORTO") == 0) {
cell.setIcon(new ImageIcon(imagesOfTiles.get(editor.getCellMap().get("DOOR/DOORTO")).getScaledInstance(50, 50, Image.SCALE_DEFAULT))); cell.setIcon(new ImageIcon(imagesOfTiles.get(editor.getCellMap().get("DOOR/DOORTO")).getScaledInstance(50, 50, Image.SCALE_DEFAULT)));

View File

@ -10,11 +10,14 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
/**
* This class handles creating tileset from selected images and displaying them with corresponding numbers
*/
public class TilesetOverview extends JFrame { public class TilesetOverview extends JFrame {
private JLayeredPane view; private final JLayeredPane view;
private JLayeredPane tilesetPanel; private final JLayeredPane tilesetPanel;
private JScrollPane scrollPane; private final JScrollPane scrollPane;
private JLabel info; private JLabel info;
private int offset = 0; private int offset = 0;
@ -30,6 +33,10 @@ public class TilesetOverview extends JFrame {
listFilesForFolder(folder); listFilesForFolder(folder);
} }
/**
* @param folder is folder with tileset images
* Displays menu all possible images to be parsed into tileset
*/
public void listFilesForFolder(File folder) { public void listFilesForFolder(File folder) {
activeTilesets = new LinkedList<>(); activeTilesets = new LinkedList<>();
for (final File fileEntry : folder.listFiles()) { for (final File fileEntry : folder.listFiles()) {
@ -71,6 +78,10 @@ public class TilesetOverview extends JFrame {
} }
} }
/**
* @param name is image name
* Displays name of file with a designated checkbox
*/
private void loadTileset(String name) { private void loadTileset(String name) {
JLabel text = new JLabel(name); JLabel text = new JLabel(name);
text.setBounds(50 , offset, 200, 50); text.setBounds(50 , offset, 200, 50);
@ -87,6 +98,9 @@ public class TilesetOverview extends JFrame {
offset += 70; offset += 70;
} }
/**
* Generates tileset from selected images and displays is as a matrix
*/
public void generateOverview() { public void generateOverview() {
tilesetOffset = 0; tilesetOffset = 0;
imagesOfTiles = new LinkedList<>(); imagesOfTiles = new LinkedList<>();
@ -133,15 +147,11 @@ public class TilesetOverview extends JFrame {
}); });
tileList.add(tile); tileList.add(tile);
} }
//
for (int i = 0; i < Ytiles; i++) { for (int i = 0; i < Ytiles; i++) {
for (int j = 0; j < Xtiles; j++) { for (int j = 0; j < Xtiles; j++) {
tileset.add(tileList.get(i + (j*Ytiles))); tileset.add(tileList.get(i + (j*Ytiles)));
} }
} }
// for (int i = 0; i < 16; i++) {
// tileset.add(tileList.get(i));
// }
tileset.setBounds(0, tilesetOffset, width + (Xtiles * 6), height + (Ytiles * 6)); tileset.setBounds(0, tilesetOffset, width + (Xtiles * 6), height + (Ytiles * 6));
tilesetOffset += height + + (Ytiles * 6); tilesetOffset += height + + (Ytiles * 6);
tilesetPanel.add(tileset); tilesetPanel.add(tileset);

View File

@ -11,21 +11,24 @@ import java.io.FileNotFoundException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Scanner; import java.util.Scanner;
/**
* This class hold all information about map that is loaded into application
*/
public class Map { public class Map {
private String name; private String name;
private TypeOfCell[][] mapArray; private final TypeOfCell[][] mapArray;
private Person person; private final Person person;
private LinkedList<EventMoveToCell> moveToCells; private final LinkedList<EventMoveToCell> moveToCells;
private LinkedList<Block> block; private final LinkedList<Block> block;
private LinkedList<InteractionCell> interactionCells; private final LinkedList<InteractionCell> interactionCells;
private LinkedList<TriggerCell> triggerCells; private final LinkedList<TriggerCell> triggerCells;
private LinkedList<DoorCell> doorCells; private final LinkedList<DoorCell> doorCells;
private LinkedList<ChestCell> chestCells; private final LinkedList<ChestCell> chestCells;
private LinkedList<Npc> npcs; private LinkedList<Npc> npcs;
private int idExit; private int idExit;
private ImageCell imageCell; private final ImageCell imageCell;
private int[] canvasSize; private int[] canvasSize;
private SoundManager soundManager; private final SoundManager soundManager;
private static Scanner scanner; private static Scanner scanner;
@ -47,6 +50,12 @@ public class Map {
soundManager = new SoundManager(); soundManager = new SoundManager();
} }
/**
* @param nameOfMap is map name that is being searched for
* @param window is reference for WindowOfFreeMove
* @return found map
* Finds map by name in a list of loaded maps
*/
public static Map findMapByName(String nameOfMap, WindowOfFreeMove window) { public static Map findMapByName(String nameOfMap, WindowOfFreeMove window) {
LinkedList<Map> mapLinkedList = window.getMapLinkedList(); LinkedList<Map> mapLinkedList = window.getMapLinkedList();
for (Map map : mapLinkedList) { for (Map map : mapLinkedList) {
@ -56,6 +65,12 @@ public class Map {
return null; return null;
} }
/**
* @param name is map file name
* @param window is reference for WindowOfFreeMove
* @return loaded map
* Creates map and prepares all fields, then passes map on loadMap
*/
public static Map loadMapFromFile(String name, WindowOfFreeMove window) { public static Map loadMapFromFile(String name, WindowOfFreeMove window) {
try { try {
File file = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + name + ".txt"); File file = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + name + ".txt");
@ -83,6 +98,14 @@ public class Map {
return null; return null;
} }
/**
* @param map is map being loaded
* @param data is line of map file to be parsed
* @param size is array of map's size in cells
* @param y is current Y value of line being parsed
* @param window is reference for WindowOfFreeMove
* Parses line of text into corresponding cells with attributes and populates corresponding lists wit them
*/
public static void loadMap(Map map, String data, String[] size, int y, WindowOfFreeMove window) { public static void loadMap(Map map, String data, String[] size, int y, WindowOfFreeMove window) {
String[] line = data.split(" "); String[] line = data.split(" ");
for (int x = 0; x < Integer.parseInt(size[0]); x++) { for (int x = 0; x < Integer.parseInt(size[0]); x++) {
@ -137,6 +160,11 @@ public class Map {
} }
/**
* @param map is map being linked
* @param window is reference on WindowOfFreeMove
* Parses MOVETO and DOORTO cells, which link different maps together
*/
public void linkMaps(Map map, WindowOfFreeMove window) { public void linkMaps(Map map, WindowOfFreeMove window) {
try { try {
File dialogFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + map.getName() + ".txt"); File dialogFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + map.getName() + ".txt");
@ -175,26 +203,46 @@ public class Map {
} }
/**
* @param moveToCell is MOVETO cell being added
* Updates map's cell matrix and adds cell to corresponding list
*/
public void addMoveToEvent(EventMoveToCell moveToCell) { public void addMoveToEvent(EventMoveToCell moveToCell) {
mapArray[moveToCell.getX()][moveToCell.getY()] = TypeOfCell.MOVETO; mapArray[moveToCell.getX()][moveToCell.getY()] = TypeOfCell.MOVETO;
moveToCells.add(moveToCell); moveToCells.add(moveToCell);
} }
/**
* @param interactionCell is INTER cell being added
* Updates map's cell matrix and adds cell to corresponding list
*/
public void addInteractionEvent(InteractionCell interactionCell) { public void addInteractionEvent(InteractionCell interactionCell) {
mapArray[interactionCell.getX()][interactionCell.getY()] = TypeOfCell.EVENT; mapArray[interactionCell.getX()][interactionCell.getY()] = TypeOfCell.EVENT;
interactionCells.add(interactionCell); interactionCells.add(interactionCell);
} }
/**
* @param triggerCell is TRIGGER cell being added
* Updates map's cell matrix and adds cell to corresponding list
*/
public void addInteractionEvent(TriggerCell triggerCell) { public void addInteractionEvent(TriggerCell triggerCell) {
mapArray[triggerCell.getX()][triggerCell.getY()] = TypeOfCell.EVENT; mapArray[triggerCell.getX()][triggerCell.getY()] = TypeOfCell.EVENT;
triggerCells.add(triggerCell); triggerCells.add(triggerCell);
} }
/**
* @param doorCell is DOOR(TO) cell being added
* Updates map's cell matrix and adds cell to corresponding list
*/
public void addInteractionEvent(DoorCell doorCell) { public void addInteractionEvent(DoorCell doorCell) {
mapArray[doorCell.getX()][doorCell.getY()] = TypeOfCell.EVENT; mapArray[doorCell.getX()][doorCell.getY()] = TypeOfCell.EVENT;
doorCells.add(doorCell); doorCells.add(doorCell);
} }
/**
* @param chestCell is CHEST cell being added
* Updates map's cell matrix and adds cell to corresponding list
*/
public void addInteractionEvent(ChestCell chestCell) { public void addInteractionEvent(ChestCell chestCell) {
mapArray[chestCell.getX()][chestCell.getY()] = TypeOfCell.EVENT; mapArray[chestCell.getX()][chestCell.getY()] = TypeOfCell.EVENT;
chestCells.add(chestCell); chestCells.add(chestCell);
@ -440,6 +488,13 @@ public class Map {
return cell; return cell;
} }
/**
* @param x is starting X value
* @param y is starting Y value
* @param directionSight is direction of hero's sight
* @return array of new X & Y coordinates
* Translates direction of sight into new coords
*/
public int[] directionSightSwitch(int x, int y, int directionSight) { public int[] directionSightSwitch(int x, int y, int directionSight) {
switch (directionSight) { switch (directionSight) {
case 1: case 1:

View File

@ -12,13 +12,16 @@ import java.util.LinkedList;
import static ruscz.game.gameOfProd.Windows.WindowOfFreeMove.*; import static ruscz.game.gameOfProd.Windows.WindowOfFreeMove.*;
/**
* This class manages all currently loaded maps and transfers hero between maps
*/
public class MapManager { public class MapManager {
private WindowOfFreeMove.Canvas canvas; private final WindowOfFreeMove.Canvas canvas;
private LinkedList<Map> maps; private final LinkedList<Map> maps;
private Map actualMap; private Map actualMap;
private SaveManager saveManager; private final SaveManager saveManager;
private WindowOfFreeMove window; private final WindowOfFreeMove window;
private LoadManager loadManager; private final LoadManager loadManager;
public MapManager(LinkedList<Map> maps, WindowOfFreeMove.Canvas canvas, WindowOfFreeMove window) { public MapManager(LinkedList<Map> maps, WindowOfFreeMove.Canvas canvas, WindowOfFreeMove window) {
this.canvas = canvas; this.canvas = canvas;
@ -28,6 +31,10 @@ public class MapManager {
this.loadManager = new LoadManager(this); this.loadManager = new LoadManager(this);
} }
/**
* @param map is map to be set
* Sets map as the one that is currently used, if that map is not present in map list, the map is added
*/
public void setMap(Map map) { public void setMap(Map map) {
if (maps.contains(map)) { if (maps.contains(map)) {
actualMap = map; actualMap = map;
@ -55,6 +62,9 @@ public class MapManager {
return saveManager; return saveManager;
} }
/**
* Sets person on a new map based on SPAWN cell
*/
public void createMap() { public void createMap() {
for (int i = 0; i < actualMap.getMapArray().length; i++) { for (int i = 0; i < actualMap.getMapArray().length; i++) {
for (int j = 0; j < actualMap.getMapArray()[0].length; j++) { for (int j = 0; j < actualMap.getMapArray()[0].length; j++) {
@ -70,6 +80,9 @@ public class MapManager {
setPersonByMoveToEvent(); setPersonByMoveToEvent();
} }
/**
* Sets person on a new map based on MOVETO or DOORTO cell
*/
private void setPersonByMoveToEvent() { private void setPersonByMoveToEvent() {
for (EventMoveToCell cell : actualMap.getMoveToCells()) { for (EventMoveToCell cell : actualMap.getMoveToCells()) {
if (this.actualMap.getIdExit() == cell.getId()) { if (this.actualMap.getIdExit() == cell.getId()) {
@ -117,6 +130,10 @@ public class MapManager {
canvas.repaint(); canvas.repaint();
} }
/**
* @param size is array of new sizes for canvas
* Sets canvas size based on current map
*/
public void resizeCanvas(int[] size) { public void resizeCanvas(int[] size) {
canvas.setPreferredSize(new Dimension( canvas.setPreferredSize(new Dimension(
CELL_SIZE * size[0], CELL_SIZE * size[0],

View File

@ -18,15 +18,22 @@ import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.Scanner; import java.util.Scanner;
/**
* This class manages loading all saved data into current game
*/
public class LoadManager { public class LoadManager {
private MapManager mapManager; private final MapManager mapManager;
private WindowOfFreeMove window; private final WindowOfFreeMove window;
public LoadManager(MapManager mapManager) { public LoadManager(MapManager mapManager) {
this.mapManager = mapManager; this.mapManager = mapManager;
this.window = mapManager.getWindow(); this.window = mapManager.getWindow();
} }
/**
* @return are save files empty
* Checks if save files are empty (if there is no saved progress)
*/
public static boolean isSaveEmpty() { public static boolean isSaveEmpty() {
File personFile = new File("src/main/resources/save/savedGame/person.txt"); File personFile = new File("src/main/resources/save/savedGame/person.txt");
File eventFile = new File("src/main/resources/save/savedGame/events.txt"); File eventFile = new File("src/main/resources/save/savedGame/events.txt");
@ -34,11 +41,17 @@ public class LoadManager {
return personFile.length() == 0 && eventFile.length() == 0 && inventoryFile.length() == 0; return personFile.length() == 0 && eventFile.length() == 0 && inventoryFile.length() == 0;
} }
/**
* Loads new game
*/
public void loadNewGame() { public void loadNewGame() {
loadMaps(); loadMaps();
loadNpcs(); loadNpcs();
} }
/**
* Loads new game and aplicates current progress
*/
public void loadSavedGame() { public void loadSavedGame() {
loadNewGame(); loadNewGame();
loadPerson(); loadPerson();
@ -46,6 +59,9 @@ public class LoadManager {
loadInventory(); loadInventory();
} }
/**
* Clears all save files
*/
public void clearSave() { public void clearSave() {
try { try {
FileWriter writer = new FileWriter("src/main/resources/save/savedGame/person.txt"); FileWriter writer = new FileWriter("src/main/resources/save/savedGame/person.txt");
@ -60,6 +76,9 @@ public class LoadManager {
} }
} }
/**
* Loads maps in current chapter
*/
private void loadMaps() { private void loadMaps() {
try { try {
Rectangle[] rec = new Rectangle[12]; Rectangle[] rec = new Rectangle[12];
@ -95,6 +114,9 @@ public class LoadManager {
} }
} }
/**
* Loads all NPCs
*/
private void loadNpcs() { private void loadNpcs() {
try { try {
File npcsFile = new File("src/main/resources/save/newGame/npcs.txt"); File npcsFile = new File("src/main/resources/save/newGame/npcs.txt");
@ -114,6 +136,9 @@ public class LoadManager {
} }
} }
/**
* Loads hero's position from file
*/
private void loadPerson() { private void loadPerson() {
try { try {
File personFile = new File("src/main/resources/save/savedGame/person.txt"); File personFile = new File("src/main/resources/save/savedGame/person.txt");
@ -136,6 +161,9 @@ public class LoadManager {
} }
} }
/**
* Loads all events(triggers, chests & doors) from file and sets them corresponding attributes
*/
private void loadEvents() { private void loadEvents() {
try { try {
File eventFile = new File("src/main/resources/save/savedGame/events.txt"); File eventFile = new File("src/main/resources/save/savedGame/events.txt");
@ -167,6 +195,9 @@ public class LoadManager {
} }
} }
/**
* Loads hero's inventory from file
*/
private void loadInventory() { private void loadInventory() {
try { try {
File inventoryFile = new File("src/main/resources/save/savedGame/inventory.txt"); File inventoryFile = new File("src/main/resources/save/savedGame/inventory.txt");

View File

@ -13,19 +13,28 @@ import java.io.FileWriter;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
/**
* This class manages saving current progress into text files
*/
public class SaveManager { public class SaveManager {
private MapManager mapManager; private final MapManager mapManager;
public SaveManager(MapManager mapManager) { public SaveManager(MapManager mapManager) {
this.mapManager = mapManager; this.mapManager = mapManager;
} }
/**
* Saves game progress
*/
public void saveGame() { public void saveGame() {
savePerson(); savePerson();
saveEvents(); saveEvents();
saveInventory(); saveInventory();
} }
/**
* Saves current hero's position and direction
*/
private void savePerson() { private void savePerson() {
try { try {
FileWriter writer = new FileWriter("src/main/resources/save/savedGame/person.txt"); FileWriter writer = new FileWriter("src/main/resources/save/savedGame/person.txt");
@ -44,6 +53,9 @@ public class SaveManager {
} }
} }
/**
* Saves all TRIGGER, CHEST and DOOR cells with their position and activeness (+ other attributes)
*/
private void saveEvents() { private void saveEvents() {
try { try {
LinkedList<Map> maps = mapManager.getMaps(); LinkedList<Map> maps = mapManager.getMaps();
@ -94,6 +106,9 @@ public class SaveManager {
} }
} }
/**
* Saves current hero's invemtory
*/
private void saveInventory() { private void saveInventory() {
try { try {
FileWriter writer = new FileWriter("src/main/resources/save/savedGame/inventory.txt"); FileWriter writer = new FileWriter("src/main/resources/save/savedGame/inventory.txt");

View File

@ -1,5 +1,8 @@
package ruscz.game.gameOfProd.Scripts; package ruscz.game.gameOfProd.Scripts;
/**
* Enumeration for different directions
*/
public enum Direction { public enum Direction {
UP, DOWN, LEFT, RIGHT UP, DOWN, LEFT, RIGHT
} }

View File

@ -7,47 +7,26 @@ import ruscz.game.gameOfProd.Map.Map;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
/**
* This class handles translation between the output of A* algorithm and our internal movement directions
*/
public class PathFinder { public class PathFinder {
private Map map; private final Map map;
private boolean foundWay;
private static final int MAX_STEPS = 200; private static final int MAX_STEPS = 200;
public PathFinder(Map map) { public PathFinder(Map map) {
this.map = map; this.map = map;
foundWay = false;
} }
public LinkedList<Direction> getWayWithoutCollision(int startX, int startY, int endX, int endY) { /**
int nowX = startX; * @param startX is starting X value
int nowY = startY; * @param startY is starting Y value
LinkedList<Direction> directions = new LinkedList<>(); * @param endX is ending X value
while (!foundWay) { * @param endY is ending Y value
if (nowX == endX && nowY == endY) { * @return list of directions for NPC
foundWay = true; * Finds path with A* algorithm and translates it to directions using Direction enumeration
} */
if (nowX != endX) {
if (endX > nowX) {
directions.add(Direction.RIGHT);
nowX++;
} else {
directions.add(Direction.LEFT);
nowX--;
}
} else {
if (endY > nowY) {
directions.add(Direction.DOWN);
nowY++;
} else {
directions.add(Direction.UP);
nowY--;
}
}
}
return directions;
}
public LinkedList<Direction> getWayWithCollision(int startX, int startY, int endX, int endY) { public LinkedList<Direction> getWayWithCollision(int startX, int startY, int endX, int endY) {
AStar aStar = new AStar(map.getMapArray().length, map.getMapArray()[0].length, new Node(startX, startY), new Node(endX, endY)); AStar aStar = new AStar(map.getMapArray().length, map.getMapArray()[0].length, new Node(startX, startY), new Node(endX, endY));
LinkedList<Direction> directions = new LinkedList<>(); LinkedList<Direction> directions = new LinkedList<>();

View File

@ -6,6 +6,10 @@ import ruscz.game.gameOfProd.Inventory.InventoryManager;
import ruscz.game.gameOfProd.Inventory.Item; import ruscz.game.gameOfProd.Inventory.Item;
import ruscz.game.gameOfProd.Inventory.ItemAction; import ruscz.game.gameOfProd.Inventory.ItemAction;
/**
* This class parses text form player into a set of commands
* This class is currently not being used in our game, though it will be implemented at a later date
*/
public class TextParser { public class TextParser {
private String textToParse; private String textToParse;
private Battle battle; private Battle battle;
@ -14,9 +18,10 @@ public class TextParser {
private Item item; private Item item;
private String action; private String action;
public TextParser() { /**
} * @param text is input from player
* Separates incoming text into parts and passes them on to be parsed further
*/
public void parseBattleText(String text) { public void parseBattleText(String text) {
textToParse = text; textToParse = text;
String person = textToParse.toLowerCase().substring(0, textToParse.indexOf(".")); String person = textToParse.toLowerCase().substring(0, textToParse.indexOf("."));
@ -27,6 +32,10 @@ public class TextParser {
parseBattleAction(action); parseBattleAction(action);
} }
/**
* @param personText is name of battle person
* Finds battle person based on text input and sets it as actor of action
*/
private void parseBattlePerson(String personText) { private void parseBattlePerson(String personText) {
switch (personText) { switch (personText) {
case "self": case "self":
@ -41,6 +50,10 @@ public class TextParser {
} }
} }
/**
* @param action is name of action
* Calls corresponding action to user input
*/
private void parseBattleAction(String action) { private void parseBattleAction(String action) {
this.action = action; this.action = action;
switch (action) { switch (action) {
@ -73,6 +86,10 @@ public class TextParser {
} }
} }
/**
* @param targetText name of battle person
* Finds battle person based on text input and sets it as target of action
*/
private void parseBattleTarget(String targetText) { private void parseBattleTarget(String targetText) {
switch (targetText) { switch (targetText) {
case "self": case "self":

View File

@ -5,6 +5,9 @@ import javax.swing.*;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
/**
* This class handles all music being played in the game
*/
public class MusicManager { public class MusicManager {
private final String musicName; private final String musicName;
private float volume; private float volume;
@ -20,6 +23,9 @@ public class MusicManager {
this.volume = -40.0f; this.volume = -40.0f;
} }
/**
* Starts playing music
*/
public void playMusic(){ public void playMusic(){
AudioInputStream audioIn; AudioInputStream audioIn;
try { try {
@ -39,6 +45,9 @@ public class MusicManager {
} }
} }
/**
* Stops playing music
*/
public void stopMusic() { public void stopMusic() {
if (timerOut != null) timerOut.stop(); if (timerOut != null) timerOut.stop();
clip.stop(); clip.stop();
@ -53,6 +62,10 @@ public class MusicManager {
gainControl.setValue(-40.0f); gainControl.setValue(-40.0f);
} }
/**
* @param delay is timer delay in milliseconds
* Fades music in (slowly raises volume to maxVolume)
*/
public void fadeIn(int delay) { public void fadeIn(int delay) {
timerIn = new Timer(delay, actionEvent -> { timerIn = new Timer(delay, actionEvent -> {
if (volume < maxVolume) { if (volume < maxVolume) {
@ -63,6 +76,10 @@ public class MusicManager {
timerIn.start(); timerIn.start();
} }
/**
* @param delay is timer delay in milliseconds
* Fades music out (slowly lowers volume to 'zero')
*/
public void fadeOut(int delay) { public void fadeOut(int delay) {
timerOut = new Timer(delay, actionEvent -> { timerOut = new Timer(delay, actionEvent -> {
if (volume > -79.0f) { if (volume > -79.0f) {

View File

@ -9,6 +9,9 @@ import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Scanner; import java.util.Scanner;
/**
* This class handles all sounds being played in the game
*/
public class SoundManager { public class SoundManager {
private FloatControl gainControl; private FloatControl gainControl;
private Clip clip; private Clip clip;
@ -19,6 +22,10 @@ public class SoundManager {
this.delay = 0; this.delay = 0;
} }
/**
* @param file is name of file
* Parses sound map for different entities (currently only for doors)
*/
public void loadSoundMap(String file) { public void loadSoundMap(String file) {
try { try {
File mapFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + file + "-tileset.txt"); File mapFile = new File("src/main/resources/maps/" + WindowOfFreeMove.getCHAPTER() + "/" + file + "-tileset.txt");
@ -42,6 +49,11 @@ public class SoundManager {
} }
} }
/**
* @param name is sound name
* @param volume is designated volume os float
* Plays sound once
*/
public void playSound(String name, float volume){ public void playSound(String name, float volume){
AudioInputStream audioIn; AudioInputStream audioIn;
try { try {
@ -60,6 +72,12 @@ public class SoundManager {
} }
} }
/**
* @param name is sound name
* @param delay is timer delay in milliseconds
* @param volume is designated volume as float
* Plays sound repeatedly after delay
*/
public void playSoundRepeatedly(String name, int delay, float volume) { public void playSoundRepeatedly(String name, int delay, float volume) {
if (this.delay == delay) { if (this.delay == delay) {
AudioInputStream audioIn; AudioInputStream audioIn;

View File

@ -1,10 +1,15 @@
package ruscz.game.gameOfProd.Windows; package ruscz.game.gameOfProd.Windows;
import ruscz.game.gameOfProd.Cells.Person;
import static ruscz.game.gameOfProd.Windows.WindowOfFreeMove.*; import static ruscz.game.gameOfProd.Windows.WindowOfFreeMove.*;
/**
* This class handles movement of camera, resp movement of canvas
*/
public class Camera { public class Camera {
private WindowOfFreeMove window; private final WindowOfFreeMove window;
private WindowOfFreeMove.Canvas canvas; private final WindowOfFreeMove.Canvas canvas;
private boolean isBound; private boolean isBound;
private int endX; private int endX;
private int endY; private int endY;
@ -22,6 +27,9 @@ public class Camera {
this.isBound = true; this.isBound = true;
} }
/**
* Decides which type of camera movement to use
*/
public void moveCamera() { public void moveCamera() {
if (isBound) { if (isBound) {
moveBoundCamera(); moveBoundCamera();
@ -32,6 +40,9 @@ public class Camera {
} }
} }
/**
* Moves camera so that hero is always in the center if possible
*/
public void moveBoundCamera() { public void moveBoundCamera() {
int cameraOffsetX = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getX() - WINDOW_WIDTH / 2); int cameraOffsetX = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getX() - WINDOW_WIDTH / 2);
int cameraOffsetY = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getY() - WINDOW_HEIGHT / 2); int cameraOffsetY = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getY() - WINDOW_HEIGHT / 2);
@ -84,6 +95,9 @@ public class Camera {
canvas.setLocation(cameraOffsetX + Xsize, cameraOffsetY + Ysize); canvas.setLocation(cameraOffsetX + Xsize, cameraOffsetY + Ysize);
} }
/**
* Moves camera from current position to a designated end point
*/
public void moveFreeCamera() { public void moveFreeCamera() {
int coordX = (int) (canvas.getLocation().getX()); int coordX = (int) (canvas.getLocation().getX());
int coordY = (int) (canvas.getLocation().getY()); int coordY = (int) (canvas.getLocation().getY());
@ -148,31 +162,25 @@ public class Camera {
if (Math.abs(coordX - endX) <= stepX && Math.abs(coordY - endY) <= stepY && isReturning) boundCamera(); if (Math.abs(coordX - endX) <= stepX && Math.abs(coordY - endY) <= stepY && isReturning) boundCamera();
} }
/**
* Returns camera to the player
*/
public void returnFreeCamera() { public void returnFreeCamera() {
setCameraStart(); setCameraStart();
endX = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getX() - (WINDOW_WIDTH / 2)); endX = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getX() - (WINDOW_WIDTH / 2));
endY = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getY() - (WINDOW_HEIGHT / 2)); endY = (-1) * CELL_SIZE * (window.getMapManager().getActualMap().getPerson().getY() - (WINDOW_HEIGHT / 2));
// if (endX > 0) {
// endX = 0;
// }
// else if (CELL_SIZE * WINDOW_WIDTH - endX > CELL_SIZE * CANVAS_WIDTH) {
// endX = (-1) * (CELL_SIZE * CANVAS_WIDTH - CELL_SIZE * WINDOW_WIDTH);
// }
// if (endY > 0) {
// endY = 0;
// }
// else if (CELL_SIZE * WINDOW_WIDTH - endY > CELL_SIZE * CANVAS_WIDTH) {
// endY = (-1) * (CELL_SIZE * CANVAS_HEIGHT - CELL_SIZE * WINDOW_HEIGHT);
// }
time = 2; time = 2;
isReturning = true; isReturning = true;
} }
/**
* Bounds camera back to player
*/
public void boundCamera() { public void boundCamera() {
isBound = true; isBound = true;
isReturning = false; isReturning = false;
window.setCanPersonMove(true); setCanPersonMove(true);
window.getMapManager().getActualMap().getPerson().setInEvent(false); Person.setInEvent(false);
} }
public void setCameraStart() { public void setCameraStart() {

View File

@ -22,6 +22,10 @@ import java.util.LinkedList;
import java.util.Scanner; import java.util.Scanner;
/**
* This class holds JPanel used for battle sequences
* It also holds references to all main classes used for battle
*/
public class WindowOfBattle extends JPanel { public class WindowOfBattle extends JPanel {
public static final int CELL_SIZE = 50; public static final int CELL_SIZE = 50;
public static int CANVAS_WIDTH = 16; public static int CANVAS_WIDTH = 16;
@ -118,6 +122,10 @@ public class WindowOfBattle extends JPanel {
setCursor(Cursor.getDefaultCursor()); setCursor(Cursor.getDefaultCursor());
} }
/**
* @param name is battle file name
* Starts battle sequence - parses actors & other assets
*/
public void start(String name) { public void start(String name) {
LinkedList<Hero> heroes = new LinkedList<>(); LinkedList<Hero> heroes = new LinkedList<>();
LinkedList<Enemy> enemies = new LinkedList<>(); LinkedList<Enemy> enemies = new LinkedList<>();
@ -187,6 +195,10 @@ public class WindowOfBattle extends JPanel {
return canvas; return canvas;
} }
/**
* @param s is text to be displayed
* Displays text in situationText field
*/
public void writeToOutput(String s) { public void writeToOutput(String s) {
Font f = new Font(Font.SERIF, Font.BOLD, 20); Font f = new Font(Font.SERIF, Font.BOLD, 20);
if (situationText.getComponents().length == 0) { if (situationText.getComponents().length == 0) {
@ -199,6 +211,11 @@ public class WindowOfBattle extends JPanel {
repaint(); repaint();
} }
/**
* @param button is button to be styled
* @return styled button
* Styles button
*/
public JButton style(JButton button) { public JButton style(JButton button) {
Font f = new Font(Font.SERIF, Font.BOLD, 16); Font f = new Font(Font.SERIF, Font.BOLD, 16);
Color c = new Color(255, 217, 112); Color c = new Color(255, 217, 112);
@ -241,11 +258,18 @@ public class WindowOfBattle extends JPanel {
return isRunAwayPossible; return isRunAwayPossible;
} }
/**
* This class handles repainting of all battle elements and entities
*/
class Canvas extends JPanel { class Canvas extends JPanel {
private LinkedList<BufferedImage> images; private LinkedList<BufferedImage> images;
private BufferedImage image; private BufferedImage image;
private Timer timer; private Timer timer;
/**
* @param name is image name
* Adds image into list of images to be displayed & sets it as the current image
*/
public void addImage(String name) { public void addImage(String name) {
try { try {
images.add(ImageIO.read(new File("src/main/resources/images/" + name + ".png"))); images.add(ImageIO.read(new File("src/main/resources/images/" + name + ".png")));
@ -263,6 +287,10 @@ public class WindowOfBattle extends JPanel {
} }
} }
/**
* @param delay is timer delay in miliseconds
* Selects random inmage from list of images to be displayed -creates flickering effect
*/
public void flicker(int delay) { public void flicker(int delay) {
timer = new Timer(delay, actionEvent -> { timer = new Timer(delay, actionEvent -> {
image = images.get((int) (Math.random() * images.size())); image = images.get((int) (Math.random() * images.size()));

View File

@ -17,6 +17,10 @@ import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.LinkedList; import java.util.LinkedList;
/**
* This class holds JLayeredPane with the main part of our game - the maps
* It also holds references to all major classes
*/
public class WindowOfFreeMove extends JLayeredPane { public class WindowOfFreeMove extends JLayeredPane {
public static final int CELL_SIZE = 70; public static final int CELL_SIZE = 70;
public static int CANVAS_WIDTH = 50; public static int CANVAS_WIDTH = 50;
@ -46,23 +50,24 @@ public class WindowOfFreeMove extends JLayeredPane {
private static String CHAPTER = "0"; private static String CHAPTER = "0";
private Game game; private final Game game;
private Canvas canvas; private final Canvas canvas;
private DialogBar dialogBar; private final DialogBar dialogBar;
private MapManager mapManager; private MapManager mapManager;
private Camera camera; private final Camera camera;
private Timer inputTimer; private final Timer inputTimer;
private MusicManager musicManager; private MusicManager musicManager;
private Foreground foreground; private final Foreground foreground;
private LinkedList<Map> mapLinkedList; private LinkedList<Map> mapLinkedList;
public WindowOfFreeMove windowOfFreeMove() { return this;}
public MapManager getMapManager() { public MapManager getMapManager() {
return mapManager; return mapManager;
} }
/**
* Forces all panels to repaint
*/
public void repaintCanvas() { public void repaintCanvas() {
mapManager.getActualMap().getPerson().move(); mapManager.getActualMap().getPerson().move();
camera.moveCamera(); camera.moveCamera();
@ -175,6 +180,10 @@ public class WindowOfFreeMove extends JLayeredPane {
}); });
} }
/**
* @param newGame is a reference to main class Game
* Starts the game itself - loads all needed maps, starts a new game or loads saved game and starts timer for repainting
*/
public void start(boolean newGame) { public void start(boolean newGame) {
centerContent(); centerContent();
@ -208,6 +217,9 @@ public class WindowOfFreeMove extends JLayeredPane {
timer.start(); timer.start();
} }
/**
* Loads next chapter of game
*/
public void loadNextChapter() { public void loadNextChapter() {
CHAPTER = String.valueOf(Integer.parseInt(CHAPTER) + 1); CHAPTER = String.valueOf(Integer.parseInt(CHAPTER) + 1);
isReadyToPaint = false; isReadyToPaint = false;
@ -220,6 +232,10 @@ public class WindowOfFreeMove extends JLayeredPane {
isReadyToPaint = true; isReadyToPaint = true;
} }
/**
* @param name is name of battle file
* Starts new battle sequence
*/
public void startBattle(String name) { public void startBattle(String name) {
setVisible(false); setVisible(false);
WindowOfBattle battle = game.getBattle(); WindowOfBattle battle = game.getBattle();
@ -227,6 +243,9 @@ public class WindowOfFreeMove extends JLayeredPane {
battle.start(name); battle.start(name);
} }
/**
* This class handles repainting of all game elements and entities
*/
public class Canvas extends JPanel { public class Canvas extends JPanel {
@Override @Override
public void paint(Graphics g) { public void paint(Graphics g) {
@ -272,12 +291,23 @@ public class WindowOfFreeMove extends JLayeredPane {
} }
} }
/**
* @param cell is cell to be validated
* @return is cell in view or near view
* Checks if a cell is being shown in window and has to be repainted
*/
private boolean isinView(Cell cell) { private boolean isinView(Cell cell) {
Boolean xValue = (CELL_SIZE * (cell.getX()+1) > -canvas.getLocation().x) && (CELL_SIZE * (cell.getX()-1) < (-canvas.getLocation().x + CELL_SIZE * WINDOW_WIDTH)); Boolean xValue = (CELL_SIZE * (cell.getX()+1) > -canvas.getLocation().x) && (CELL_SIZE * (cell.getX()-1) < (-canvas.getLocation().x + CELL_SIZE * WINDOW_WIDTH));
Boolean yValue = (CELL_SIZE * (cell.getY()+1) > -canvas.getLocation().y) && (CELL_SIZE * (cell.getY()-1) < (-canvas.getLocation().y + CELL_SIZE * WINDOW_HEIGHT)); Boolean yValue = (CELL_SIZE * (cell.getY()+1) > -canvas.getLocation().y) && (CELL_SIZE * (cell.getY()-1) < (-canvas.getLocation().y + CELL_SIZE * WINDOW_HEIGHT));
return xValue && yValue; return xValue && yValue;
} }
/**
* @param x is X value of a cell
* @param y is Y value of a cell
* @return is cell (referenced by X & Y) in view or near view
* Checks if a cell (referenced by X & Y) is being shown in window and has to be repainted
*/
private boolean isinView(int x, int y) { private boolean isinView(int x, int y) {
Boolean xValue = (CELL_SIZE * (x+1) > -canvas.getLocation().x) && (CELL_SIZE * (x-1) < (-canvas.getLocation().x + CELL_SIZE * WINDOW_WIDTH)); Boolean xValue = (CELL_SIZE * (x+1) > -canvas.getLocation().x) && (CELL_SIZE * (x-1) < (-canvas.getLocation().x + CELL_SIZE * WINDOW_WIDTH));
Boolean yValue = (CELL_SIZE * (y+1) > -canvas.getLocation().y) && (CELL_SIZE * (y-1) < (-canvas.getLocation().y + CELL_SIZE * WINDOW_HEIGHT)); Boolean yValue = (CELL_SIZE * (y+1) > -canvas.getLocation().y) && (CELL_SIZE * (y-1) < (-canvas.getLocation().y + CELL_SIZE * WINDOW_HEIGHT));
@ -285,6 +315,10 @@ public class WindowOfFreeMove extends JLayeredPane {
} }
} }
/**
* This class handles displaying images or color on top of the whole game
* It is used in cut-scenes or for atmosphere
*/
public class Foreground extends JPanel { public class Foreground extends JPanel {
private Image imageForeground; private Image imageForeground;
private int r, g, b, a; private int r, g, b, a;
@ -308,10 +342,16 @@ public class WindowOfFreeMove extends JLayeredPane {
this.a = a; this.a = a;
} }
/**
* @param startAlpha is starting alpha value
* @param endAlpha is ending alpha value
* @param delay is delay for timer
* Gradually changes alpha value of a displayed color
*/
public void fade(int startAlpha, int endAlpha, int delay) { public void fade(int startAlpha, int endAlpha, int delay) {
a = startAlpha; a = startAlpha;
fadeTimer = new Timer(delay, actionEvent -> { fadeTimer = new Timer(delay, actionEvent -> {
if (a == endAlpha) stopTimer(); if (a == endAlpha) fadeTimer.stop();
else if (startAlpha < endAlpha) { else if (startAlpha < endAlpha) {
a += 5; a += 5;
} }
@ -322,11 +362,6 @@ public class WindowOfFreeMove extends JLayeredPane {
fadeTimer.start(); fadeTimer.start();
} }
private void stopTimer() {
fadeTimer.stop();
}
@Override @Override
public void paint(Graphics gr) { public void paint(Graphics gr) {
if (imageForeground != null) if (imageForeground != null)
@ -340,6 +375,10 @@ public class WindowOfFreeMove extends JLayeredPane {
} }
} }
/**
* @param tm is time in milliseconds
* Pauses thread for a designated length of time
*/
public static void sleep(long tm) { public static void sleep(long tm) {
try { try {
Thread.sleep(tm); Thread.sleep(tm);
@ -353,6 +392,9 @@ public class WindowOfFreeMove extends JLayeredPane {
CANVAS_HEIGHT = size[1]; CANVAS_HEIGHT = size[1];
} }
/**
* Centers game window on screen
*/
public void centerContent() { public void centerContent() {
game.getComponents()[0].setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - (WINDOW_WIDTH * CELL_SIZE)) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - (WINDOW_HEIGHT * CELL_SIZE)) / 2); game.getComponents()[0].setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - (WINDOW_WIDTH * CELL_SIZE)) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - (WINDOW_HEIGHT * CELL_SIZE)) / 2);
game.getComponents()[0].setSize(WINDOW_WIDTH * CELL_SIZE, WINDOW_HEIGHT * CELL_SIZE); game.getComponents()[0].setSize(WINDOW_WIDTH * CELL_SIZE, WINDOW_HEIGHT * CELL_SIZE);

View File

@ -17,18 +17,19 @@ import java.io.IOException;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
/**
* This class holds JPanel with menu of our game
*/
public class WindowOfMenu extends JPanel { public class WindowOfMenu extends JPanel {
public static final int WINDOW_WIDTH = 13;
public static final int WINDOW_HEIGHT = 13;
public static final int CELL_SIZE = 50; public static final int CELL_SIZE = 50;
private Game game; private final Game game;
private WindowOfFreeMove freeMove; private final WindowOfFreeMove freeMove;
private JButton startNewGame; private final JButton startNewGame;
private JButton loadSavedGame; private final JButton loadSavedGame;
private JButton startLevelEditor; private final JButton startLevelEditor;
private JButton exitGame; private final JButton exitGame;
private Dimension screenSize; private final Dimension screenSize;
private boolean showMenu; private boolean showMenu;
private MusicManager musicManager; private MusicManager musicManager;
@ -167,6 +168,9 @@ public class WindowOfMenu extends JPanel {
}); });
} }
/**
* Displays menu after initial 'Powered by CellEngine' image
*/
public void start() { public void start() {
musicManager = new MusicManager("Town2.wav", -25.0f); musicManager = new MusicManager("Town2.wav", -25.0f);
musicManager.playMusic(); musicManager.playMusic();
@ -219,6 +223,9 @@ public class WindowOfMenu extends JPanel {
} }
} }
/**
* Cleans menu and empties it to pass the action listeners to WindowOfFreeMove
*/
private void cleanUp() { private void cleanUp() {
showMenu = false; showMenu = false;
musicManager.fadeOut(5); musicManager.fadeOut(5);

View File

@ -14,12 +14,12 @@
<trigger> <trigger>
<x>6</x> <x>6</x>
<y>4</y> <y>4</y>
<active>false</active> <active>true</active>
</trigger> </trigger>
<trigger> <trigger>
<x>14</x> <x>14</x>
<y>16</y> <y>16</y>
<active>true</active> <active>false</active>
</trigger> </trigger>
<chest> <chest>
<x>1</x> <x>1</x>
@ -104,13 +104,13 @@
<x>4</x> <x>4</x>
<y>1</y> <y>1</y>
<locked>false</locked> <locked>false</locked>
<open>true</open> <open>false</open>
</dooŕ> </dooŕ>
<door> <door>
<x>2</x> <x>2</x>
<y>12</y> <y>12</y>
<locked>false</locked> <locked>false</locked>
<open>true</open> <open>false</open>
</dooŕ> </dooŕ>
<door> <door>
<x>17</x> <x>17</x>
@ -126,13 +126,13 @@
<trigger> <trigger>
<x>4</x> <x>4</x>
<y>18</y> <y>18</y>
<active>false</active> <active>true</active>
</trigger> </trigger>
<door> <door>
<x>4</x> <x>4</x>
<y>19</y> <y>19</y>
<locked>false</locked> <locked>false</locked>
<open>true</open> <open>false</open>
</dooŕ> </dooŕ>
</events> </events>
</map> </map>
@ -152,13 +152,13 @@
<trigger> <trigger>
<x>6</x> <x>6</x>
<y>2</y> <y>2</y>
<active>false</active> <active>true</active>
</trigger> </trigger>
<door> <door>
<x>6</x> <x>6</x>
<y>1</y> <y>1</y>
<locked>false</locked> <locked>false</locked>
<open>true</open> <open>false</open>
</dooŕ> </dooŕ>
</events> </events>
</map> </map>

View File

@ -1,6 +1,6 @@
<location> <location>
<map>openspace</map> <map>openspace</map>
<x>8</x> <x>8</x>
<y>15</y> <y>16</y>
<direction>3</direction> <direction>3</direction>
</location> </location>

View File

@ -14,7 +14,7 @@ import static ruscz.game.gameOfProd.Windows.WindowOfFreeMove.sleep;
public class BattleTest { public class BattleTest {
/** /**
* Procesní test, který simuluje průběh celé bitvy - silný hrdina vs. slabí nepřátelé * Process test that simulates the whole cource of a battle - strong hero vs. weak enemies
*/ */
@Test @Test
public void startBattle_battleWithAMightHero_winOfHero(){ public void startBattle_battleWithAMightHero_winOfHero(){
@ -59,7 +59,7 @@ public class BattleTest {
} }
/** /**
* Procesní test, který simuluje průběh celé bitvy - slabý hrdina vs. silní nepřátelé * Process test that simulates the whole cource of a battle - weak hero vs. strong enemies
*/ */
@Test @Test
public void startBattle_battleWithAMightEnemy_winOfEnemy(){ public void startBattle_battleWithAMightEnemy_winOfEnemy(){

View File

@ -12,7 +12,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje přidání itemu do inventáře hrdiny * Unit test that simulates addition of an item into hero's inventory
*/ */
@Test @Test
public void addItem_addItemInInventory_successfulAdd(){ public void addItem_addItemInInventory_successfulAdd(){
@ -35,7 +35,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje odebrání itemu z inventáře hrdiny * Unit test that simulates removal of an item from hero's inventory
*/ */
@Test @Test
public void removeItem_removeItemFromInventory_successfulRemove(){ public void removeItem_removeItemFromInventory_successfulRemove(){
@ -60,7 +60,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje přidání itemu, který už v inventáři je, do inventáře hrdiny * Unit test that simulates addition of an item that is already present into hero's inventory
*/ */
@Test @Test
public void addItem_increaseMultiplicityOfItem_successfulIncreasing(){ public void addItem_increaseMultiplicityOfItem_successfulIncreasing(){
@ -82,7 +82,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje odebrání itemu s násobností z inventáře hrdiny * Unit test that simulates removal of an item with multiplicity from hero's inventory
*/ */
@Test @Test
public void removeItem_decreaseMultiplicityOfItem_successfulReduce(){ public void removeItem_decreaseMultiplicityOfItem_successfulReduce(){
@ -106,7 +106,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje odebrání itemu, který v inventáři není, z inventáře hrdiny * Unit test that simulates removal of an item that is not present from hero's inventory
*/ */
@Test @Test
public void removeItem_tryDecreaseNonExistedItemOrDecreaseTooMuch_unsuccessfulReduce(){ public void removeItem_tryDecreaseNonExistedItemOrDecreaseTooMuch_unsuccessfulReduce(){
@ -127,7 +127,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje hledání itemu v inventáři hrdiny * Unit test that simulates search of an item in hero's inventory
*/ */
@Test @Test
public void findItemByName_searchingExistedItem_Item(){ public void findItemByName_searchingExistedItem_Item(){
@ -144,7 +144,7 @@ public class InventoryManagerTest {
} }
/** /**
* JUnit test, který simuluje hledání itemu, který není v inventíři hrdiny * Unit test that simulates search of an item that is not present in hero's inventory
*/ */
@Test @Test
public void findItemByName_trySearchingExistedItem_null(){ public void findItemByName_trySearchingExistedItem_null(){

View File

@ -30,8 +30,8 @@ public class LevelEditorTest {
} }
/** /**
* @param tilesets je pole názvů jednotlivých obrázků s tilesety * @param tilesets is a field with tileset-image names
* JUnit test, který simuluje vygenerování tilesetu z jednoho nebo více obrázků * Unit test that simulates generating a tileset from one or more images
*/ */
@ParameterizedTest @ParameterizedTest
@MethodSource("argumentsStream") @MethodSource("argumentsStream")
@ -66,10 +66,10 @@ public class LevelEditorTest {
} }
/** /**
* @param name název mapy * @param name is map name
* @param width šířka mapy * @param width is map width
* @param height výska mapy * @param height is map height
* JUnit test, který simuluje vytvoření mapy pro editaci v level editoru * Unit test that simulates creation of a map for editing in level editor
*/ */
@ParameterizedTest @ParameterizedTest
@MethodSource("argumentsStream2") @MethodSource("argumentsStream2")
@ -99,8 +99,8 @@ public class LevelEditorTest {
} }
/** /**
* @throws IOException kvůli porovnávání obsahu souborů a Scanneru * @throws IOException because of assertions of file contents
* Procesní test, který simuluje, vytvoření mapy v level editoru a její následné uložení do souborů * Process test that simulates creation of a map in level editor and saving of that map into files
*/ */
@Test @Test
public void saveMap_saveMapToFiles_CorrectlySavedMap() throws IOException { public void saveMap_saveMapToFiles_CorrectlySavedMap() throws IOException {
@ -198,6 +198,12 @@ public class LevelEditorTest {
Assertions.assertTrue(FileUtils.contentEquals(file1Objectset, file2Objectset)); Assertions.assertTrue(FileUtils.contentEquals(file1Objectset, file2Objectset));
} }
/**
* @param imgA is a reference image
* @param imgB is an image being compared
* @return are images similar
* Helper method that compares two images pixel by pixel
*/
public static boolean compareImages(BufferedImage imgA, BufferedImage imgB) { public static boolean compareImages(BufferedImage imgA, BufferedImage imgB) {
if (imgA.getWidth() != imgB.getWidth() || imgA.getHeight() != imgB.getHeight()) { if (imgA.getWidth() != imgB.getWidth() || imgA.getHeight() != imgB.getHeight()) {
return false; return false;

View File

@ -19,7 +19,7 @@ import java.util.stream.Stream;
public class MapTest { public class MapTest {
/** /**
* JUnit test, který simuluje načtení mapy ze souboru do matice buněk * Unit test that simulates map loading from file into a cell matrix
*/ */
@Test @Test
public void loadMapFromFile_parseMapFileToMapArray_mapArrayParsedCorrectly() { public void loadMapFromFile_parseMapFileToMapArray_mapArrayParsedCorrectly() {
@ -60,9 +60,9 @@ public class MapTest {
} }
/** /**
* @param cell referenční buňka * @param cell is a reference cell
* @param cellText text k parsování * @param cellText text for parsing
* JUnit test, který simuluje naparsování textu na konkrétní buňku s vlastnostmi * Unit test that simulates parsing text into a specific cell with attributes
*/ */
@ParameterizedTest @ParameterizedTest
@MethodSource("argumentsStream") @MethodSource("argumentsStream")
@ -85,6 +85,11 @@ public class MapTest {
} }
/**
* @param mapName is name of map
* @return cell matrix
* Helper method that parses text file into cell matrix
*/
private TypeOfCell[][] parseMap(String mapName) { private TypeOfCell[][] parseMap(String mapName) {
try { try {
File file = new File("src/main/resources/maps/999/" + mapName + ".txt"); File file = new File("src/main/resources/maps/999/" + mapName + ".txt");

View File

@ -40,12 +40,12 @@ public class PathFinderTest {
/** /**
* @param startX počáteční hodnota X * @param startX is starting X value
* @param startY počáteční hodnota Y * @param startY is starting Y value
* @param endX koncová hodnota X * @param endX is ending X value
* @param endY koncová hodnota Y * @param endY is ending Y value
* @param isPossible boolean určující zda je cesta proveditelná * @param isPossible is declaring if designated path is possible to find
* Procesní test, který simuluje automatický pohyb NPC po mapě za pomoci A* aloritmu na hledání nejkratší cesty * Process test that simulates automatic movement of NPC on a map with the help of A* algorithm that finds the shortest path
*/ */
@ParameterizedTest @ParameterizedTest
@MethodSource("argumentsStream") @MethodSource("argumentsStream")

View File

@ -65,10 +65,10 @@ public class WindowOfFreeMoveTest {
} }
/** /**
* @param directions pole jednotlivých vstupů * @param directions is field of inputs
* @param xPath předpokládaná ušlá vzdálenost na ose X * @param xPath is expected distance walked on X axis
* @param yPath předpokládaná ušlá vzdálenost na ose Y * @param yPath is expected distance walked on Y axis
* Procesní test, který simuluje pohyb hrdiny po mapě, pomocí inputu od uživatele * Process test that simulates hero's movement on a map, using input from player
*/ */
@ParameterizedTest @ParameterizedTest
@MethodSource("argumentsStream") @MethodSource("argumentsStream")
@ -100,12 +100,15 @@ public class WindowOfFreeMoveTest {
Assertions.assertEquals(testMap.getSpawnPoint()[1] + yPath, person.getY()); Assertions.assertEquals(testMap.getSpawnPoint()[1] + yPath, person.getY());
} }
/**
* Helper method that stops timer
*/
private void stopTimer() { private void stopTimer() {
timer.stop(); timer.stop();
} }
/** /**
* Procesní test, který simuluje přechod hrdiny na jinou matu pomocí MOVETO buňky * Process test that simulates hero's transition to a different map using MOVETO cell
*/ */
@Test @Test
public void moveToMap_CharacterMovesToDifferentMap_CharacterIsOnCorrectMap() { public void moveToMap_CharacterMovesToDifferentMap_CharacterIsOnCorrectMap() {
@ -160,7 +163,7 @@ public class WindowOfFreeMoveTest {
} }
/** /**
* Procesní test, který simuluje interakci hrdiny s TRIGGER buňkou a průchod spuštěnou událostí * Process test that simulates hero's interaction with a TRIGGER cell and passage through the running event
*/ */
@Test @Test
public void startEvent_CharacterEntersEventThenGoesThroughEventThenExitsEvent_CorrectCharacterResponses() { public void startEvent_CharacterEntersEventThenGoesThroughEventThenExitsEvent_CorrectCharacterResponses() {
@ -243,7 +246,7 @@ public class WindowOfFreeMoveTest {
} }
/** /**
* Procesní test, který simuluje interakci s TRIGGER buňkou, přechod na jinou mapu a následné uložení postupu ve hře * Process test that simulates heros's interaction with a TRIGGER cell, transition to a different map and saving progress in game
*/ */
@Test @Test
public void saveGame_CharacterInteractsWithTriggerCellThenMovesToDifferentMapThenGameIsSaved_CorrectlySavedProgress() { public void saveGame_CharacterInteractsWithTriggerCellThenMovesToDifferentMapThenGameIsSaved_CorrectlySavedProgress() {