diff --git a/README.md b/README.md index 5d686e9f..060d4578 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,21 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Prokofev Ilia* -| Number | Solution | Short description -| --- | --- | --- | -| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/master/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| Index | Solution | Short description| +| :---: | --- | --- | +|**Course Project**|[Sea Battle](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/course_project)|Console version of the classic Sea Battle game with graphical representation| +| HW1 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_1)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_1/char_count) | The app that reads input arguments and prints them, until "error" argument | +|-----| [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/traffic_light)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/traffic_light) | The app that reads console and calculate current traffic light's color | +| HW2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/pyramid_printer)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/pyramid_printer) | The app that reads console and prints a pyramid based on this | +|-----| [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_2/random_chars_table)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_2/random_chars_table) | The app that reads console for length, width and strategy and prints table based on this| +| HW3 | [Immutable Class](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_3) | The class that give opportunity for create Immutable object| +|-----| [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_annotation)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_annotation) | A form of syntactic metadata that can be added to Java source code| +| HW4 | [Custom File Reader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/custom_file_reader)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/custom_file_reader) | The app that provides 3 ways to read and edit a file| +|-----| [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_4/singleton)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_4/singleton) | Creational design pattern, which ensures that only one object of its kind exists | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/power_of_number)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/power_of_number) | The app that raises a number to a power | +|-----| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_5/custom_regex_matcher)
[Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/test/java/homework_5/custom_regex_matcher) | The app that check input string by hardcoded regex and return boolean answer | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_6/map_problems_generator)|Two classes that allow you to check the work of the collision and create a situation where it is impossible to get the object just put| +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/IliaProkofev/src/main/java/homework_7)|Functional interface that allows you to transform a Kitten into a Cat| -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[CodingBat link](https://codingbat.com/done?user=slowly@live.ru&tag=8165639202) diff --git a/build.gradle b/build.gradle index b91dc843..67b7f675 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,12 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + + compileOnly 'org.projectlombok:lombok:1.18.20' + annotationProcessor 'org.projectlombok:lombok:1.18.20' + + testCompileOnly 'org.projectlombok:lombok:1.18.20' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' } test { diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..2c694d4b --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,8 @@ +package course_project; + +public class Main { + + public static void main(String[] args) { + SeaBattle.initializeGame(); + } +} diff --git a/src/main/java/course_project/SeaBattle.java b/src/main/java/course_project/SeaBattle.java new file mode 100644 index 00000000..c0680377 --- /dev/null +++ b/src/main/java/course_project/SeaBattle.java @@ -0,0 +1,12 @@ +package course_project; + +import course_project.dialogue.Menu; + +final class SeaBattle { + + public static void initializeGame() { + Menu.showLogo(); + Menu.showGreetings(); + Menu.showMainMenu(); + } +} diff --git a/src/main/java/course_project/board/Battlefield.java b/src/main/java/course_project/board/Battlefield.java new file mode 100644 index 00000000..9be5778a --- /dev/null +++ b/src/main/java/course_project/board/Battlefield.java @@ -0,0 +1,207 @@ +package course_project.board; + +import course_project.player.Player; +import course_project.ships.*; + +import java.util.*; + +import static course_project.dialogue.Menu.*; +import static course_project.utils.RandomPositionGenerator.generateRandomForCell; +import static course_project.utils.RandomDirectionGenerator.generateRandomDirection; + +public class Battlefield extends Board { + + private final List availableShips = new ArrayList<>(); + + public Battlefield() { + super.cells = new Cell[FIELD_SIZE][FIELD_SIZE]; + fillCells(); + addShipsToList(); + } + + public List getAvailableShips() { + return this.availableShips; + } + + public void addShipsToList() { + availableShips.add(new Battleship()); + availableShips.add(new Destroyer()); + availableShips.add(new Destroyer()); + availableShips.add(new Cruiser()); + availableShips.add(new Cruiser()); + availableShips.add(new Cruiser()); + availableShips.add(new PatrolBoat()); + availableShips.add(new PatrolBoat()); + availableShips.add(new PatrolBoat()); + availableShips.add(new PatrolBoat()); + } + + public boolean addShipOnBattlefield(Ship ship, Cell cell, boolean isHorizontal) { + if (checkSpaceForPlaceShip(cell, ship.getSize(), isHorizontal)) { + if (isHorizontal) { + return !addRowOfCells(cell, ship); + } else { + return !addColumnOfCells(cell, ship); + } + } + return true; + } + + public void availableShipsDecrease(Ship ship) { + this.availableShips.remove(ship); + } + + private boolean addColumnOfCells(Cell entryCell, Ship ship) { + if (checkPossibilityForAddColumn(entryCell, ship.getSize())) { + int y = entryCell.getY(); + for (int i = entryCell.getX(); i < entryCell.getX() + ship.getSize(); i++) { + getCellByPosition(i, y).setShipAtCell(ship); + } + return true; + } + return false; + } + + private boolean addRowOfCells(Cell entryCell, Ship ship) { + if (checkPossibilityForAddRow(entryCell, ship.getSize())) { + int x = entryCell.getX(); + for (int j = entryCell.getY(); j < entryCell.getY() + ship.getSize(); j++) { + getCellByPosition(x, j).setShipAtCell(ship); + } + return true; + } + return false; + } + + private boolean checkPossibilityForAddColumn(Cell entryCell, int shipSize) { + if (!(checkCellAbove(entryCell) && + checkCellAboveLeftDiagonal(entryCell) && + checkCellAboveRightDiagonal(entryCell))) { + return false; + } + int y = entryCell.getY(); + for (int i = entryCell.getX(); i < entryCell.getX() + shipSize; i++) { + Cell currentCell = cells[i][y]; + if (!(isCellEmpty(currentCell) && + checkCellBelow(currentCell) && + checkCellOnTheLeft(currentCell) && + checkCellOnTheRight(currentCell))) { + return false; + } + if (i == entryCell.getX() + shipSize - 1 && + !(checkCellBelowLeftDiagonal(currentCell) && + checkCellBelowRightDiagonal(currentCell)) + ) { + return false; + } + } + return true; + } + + private boolean checkPossibilityForAddRow(Cell entryCell, int shipSize) { + if (!(checkCellOnTheLeft(entryCell) && + checkCellAboveLeftDiagonal(entryCell) && + checkCellBelowLeftDiagonal(entryCell) && + checkCellAboveRightDiagonal(entryCell)) + ) { + return false; + } + int x = entryCell.getX(); + for (int j = entryCell.getY(); j < entryCell.getY() + shipSize; j++) { + Cell currentCell = cells[x][j]; + if (!(isCellEmpty(currentCell) && + checkCellOnTheRight(currentCell) && + checkCellAbove(currentCell) && + checkCellBelow(currentCell)) + ) { + System.out.println("Cannot set the ship to coordinates " + Character.toUpperCase((char) (entryCell.getY() + 97)) + "" + (entryCell.getX() + 1) + ", check if the ship is in contact with another.\n"); + return false; + } + if (j == entryCell.getY() + shipSize - 1 && + !(checkCellAboveRightDiagonal(currentCell) && + checkCellBelowRightDiagonal(currentCell)) + ) { + return false; + } + } + return true; + } + + private boolean checkSpaceForPlaceShip(Cell fromCell, int shipSize, boolean isHorizontal) { + return isHorizontal ? + fromCell.getY() >= 0 && fromCell.getY() + shipSize <= FIELD_SIZE : + fromCell.getX() >= 0 && fromCell.getX() + shipSize <= FIELD_SIZE; + } + + private boolean checkCellAbove(Cell currentCell) { + return currentCell.getX() == 0 || isCellEmpty(cells[currentCell.getX() - 1][currentCell.getY()]); + } + + private boolean checkCellBelow(Cell currentCell) { + return currentCell.getX() == 9 || isCellEmpty(cells[currentCell.getX() + 1][currentCell.getY()]); + } + + private boolean checkCellOnTheRight(Cell currentCell) { + return currentCell.getY() == 9 || isCellEmpty(cells[currentCell.getX()][currentCell.getY() + 1]); + } + + private boolean checkCellOnTheLeft(Cell currentCell) { + return currentCell.getY() == 0 || isCellEmpty(cells[currentCell.getX()][currentCell.getY() - 1]); + } + + private boolean checkCellAboveLeftDiagonal(Cell currentCell) { + return currentCell.getX() == 0 || currentCell.getY() == 0 || + isCellEmpty(cells[currentCell.getX() - 1][currentCell.getY() - 1]); + } + + private boolean checkCellBelowLeftDiagonal(Cell currentCell) { + return currentCell.getX() == 9 || currentCell.getY() == 0 || + isCellEmpty(cells[currentCell.getX() + 1][currentCell.getY() - 1]); + } + + private boolean checkCellAboveRightDiagonal(Cell currentCell) { + return currentCell.getX() == 0 || currentCell.getY() == 9 || + isCellEmpty(cells[currentCell.getX() - 1][currentCell.getY() + 1]); + } + + private boolean checkCellBelowRightDiagonal(Cell currentCell) { + return currentCell.getX() == 9 || currentCell.getY() == 9 || + isCellEmpty(cells[currentCell.getX() + 1][currentCell.getY() + 1]); + } + + + public boolean hasAvailableShips() { + return !this.availableShips.isEmpty(); + } + + public static void addShipsOneByOne(Player currentPlayer) { + showHelp(); + for (Ship ship : currentPlayer.getField().getAvailableShips()) { + currentPlayer.getField().printField(); + Cell position; + boolean isHorizontal = true; + do { + System.out.print("Ship's type: " + ship.getName() + ". Size: " + ship.getSize() + ". Specify coordinates: "); + String[] cellPossition = getInputPosition().split(" "); + int x = Integer.parseInt(cellPossition[0].substring(1)) - 1; + int y = Integer.parseInt(String.valueOf(cellPossition[0].charAt(0) - 97)); + position = currentPlayer.getField().getCellByPosition(x, y); + if (cellPossition.length == 2) { + isHorizontal = !"v".equals(cellPossition[1]); + } + } while (currentPlayer.getField().addShipOnBattlefield(ship, position, isHorizontal)); + } + } + + public static void generateRandomPlacesForShips(Player currentPlayer) { + for (Ship ship : currentPlayer.getField().getAvailableShips()) { + Cell toPos; + boolean isHorizontal; + do { + toPos = currentPlayer.getField().getCellByPosition(generateRandomForCell(), + generateRandomForCell()); + isHorizontal = generateRandomDirection(); + } while (currentPlayer.getField().addShipOnBattlefield(ship, toPos, isHorizontal)); + } + } +} diff --git a/src/main/java/course_project/board/Board.java b/src/main/java/course_project/board/Board.java new file mode 100644 index 00000000..1a81d24b --- /dev/null +++ b/src/main/java/course_project/board/Board.java @@ -0,0 +1,113 @@ +package course_project.board; + +import course_project.player.Player; + +import static course_project.utils.Colors.*; + +public class Board { + + public static final int FIELD_SIZE = 10; + private static final String SHIP = ANSI_GREEN + "■" + ANSI_RESET; + private static final String WATER = "~"; + private static final String MISS = ANSI_MAGENTA + "▓" + ANSI_RESET; + private static final String HIT = ANSI_YELLOW + "×" + ANSI_RESET; + private static final String DESTROY = ANSI_RED + "*" + ANSI_RESET; + + Cell[][] cells; + + protected Board() { + this.cells = new Cell[FIELD_SIZE][FIELD_SIZE]; + fillCells(); + } + + public void fillCells() { + for (int i = 0; i < FIELD_SIZE; i++) { + for (int j = 0; j < FIELD_SIZE; j++) { + cells[i][j] = new Cell(i, j); + } + } + } + + public void printField() { + StringBuilder field = new StringBuilder(); + field.append("\t" + "A B C D E F G H I J").append("\n"); + + for (int i = 0; i < FIELD_SIZE; i++) { + field.append(String.format("|%-2d|", i + 1)); + for (int j = 0; j < FIELD_SIZE; j++) { + Cell currentCell = getCellByPosition(i, j); + String symbol = WATER; + if (!isCellEmpty(currentCell)) { + symbol = SHIP; + } + field.append(String.format("%s ", symbol)); + } + field.append("\n"); + } + System.out.println(field); + } + + public void showTwoFields(Player currentPlayer, Player enemy) { + + StringBuilder twoFields = new StringBuilder(); + + twoFields.append("\t" + "A B C D E F G H I J").append("\t\t\t " + "A B C D E F G H I J").append("\n"); + + for (int i = 0; i < FIELD_SIZE; i++) { + twoFields.append(String.format("|%-2d|", i + 1)); + for (int j = 0; j < FIELD_SIZE; j++) { + if (currentPlayer.getField().getCellByPosition(i, j).isHit()) { + checkCellStateAndMarkIt(currentPlayer, twoFields, i, j); + } else { + if (currentPlayer.getField().isCellEmpty(currentPlayer.getField().getCellByPosition(i, j))) { + twoFields.append(String.format("%s ", WATER)); + } else { + twoFields.append(String.format("%s ", SHIP)); + } + } + } + twoFields.append("\t\t").append(String.format("|%-2d|", i + 1)); + for (int j = 0; j < FIELD_SIZE; j++) { + if (enemy.getField().getCellByPosition(i, j).isHit()) { + checkCellStateAndMarkIt(enemy, twoFields, i, j); + } else { + twoFields.append(String.format("%s ", WATER)); + } + } + twoFields.append("\n"); + } + System.out.println(twoFields); + } + + private void checkCellStateAndMarkIt(Player currentPlayer, StringBuilder bothFields, int i, int j) { + if (currentPlayer.getField().isHit(currentPlayer.getField().getCellByPosition(i, j))) { + if (currentPlayer.getField().getCellByPosition(i, j).getReference().isDestroyed()) { + bothFields.append(String.format("%s ", DESTROY)); + } else { + bothFields.append(String.format("%s ", HIT)); + } + } else { + bothFields.append(String.format("%s ", MISS)); + } + } + + public Cell getCellByPosition(int x, int y) { + for (Cell[] cellRow : this.cells) { + for (Cell cellColumn : cellRow) { + if (cellColumn.getX() == x && cellColumn.getY() == y) { + return cellColumn; + } + } + } + return null; + } + + public boolean isCellEmpty(Cell currentCell) { + return currentCell.getShipReference() == null; + } + + public boolean isHit(Cell toCell) { + return !isCellEmpty(cells[toCell.getX()][toCell.getY()]); + } + +} diff --git a/src/main/java/course_project/board/Cell.java b/src/main/java/course_project/board/Cell.java new file mode 100644 index 00000000..75eb2c89 --- /dev/null +++ b/src/main/java/course_project/board/Cell.java @@ -0,0 +1,48 @@ +package course_project.board; +//done +import course_project.ships.Ship; + +public class Cell { + + private final int x; + private final int y; + private boolean hit; + private Ship reference; + + public Cell(int x, int y) { + this.x = x; + this.y = y; + this.reference = null; + this.hit = false; + } + + public boolean isHit() { + return this.hit; + } + + public void setHit(boolean hit) { + this.hit = hit; + } + + public Ship getShipReference() { + if (this.reference == null) return null; + else return reference; + } + + public void setShipAtCell(Ship ship) { + this.reference = ship; + } + + public int getX() { + return this.x; + } + + public int getY() { + return this.y; + } + + public Ship getReference() { + return this.reference; + } + +} diff --git a/src/main/java/course_project/dialogue/Menu.java b/src/main/java/course_project/dialogue/Menu.java new file mode 100644 index 00000000..c37f97e2 --- /dev/null +++ b/src/main/java/course_project/dialogue/Menu.java @@ -0,0 +1,208 @@ +package course_project.dialogue; + +import course_project.logic.GameLogic; +import course_project.player.Player; +import course_project.ships.Ship; + +import java.util.Scanner; + +import static course_project.board.Battlefield.generateRandomPlacesForShips; +import static course_project.board.Battlefield.addShipsOneByOne; + +@SuppressWarnings("java:S1118") +public class Menu { + + private static final String START_MESSAGE = "\n\t\t\t\t\tWelcome to Sea Battle mini-game. \n\t\t\t\tFirst of all, you should select game mode:"; + private static final String WRONG_INPUT = "Please, enter a valid coordinates."; + private static final Scanner scanner = new Scanner(System.in); + + private static Player player; + private static Player enemy; + + public static void showGreetings() { + System.out.println(START_MESSAGE); + } + + public static void showMainMenu() { + System.out.println("\t\t\t\t- 1. Human vs Computer" + + "\t\t- 2. Human vs Human" + + "\n\t\t\t\t- 3. Computer vs Computer" + + "\t- 4. Exit"); + String mode = getInput(); + switch (mode) { + case "1": + startHumanVSComputer(); + break; + case "2": + startHumanVSHuman(); + break; + case "3": + startComputerVSComputer(); + break; + case "4": + exit(); + break; + default: + System.out.println(WRONG_INPUT); + showMainMenu(); + } + } + + private static void startHumanVSComputer() { + player = new Player(getInputName(), false); + enemy = new Player("Artem Nikolaev", true); + showPlayerMenu(player); + generateRandomPlacesForShips(enemy); + GameLogic game = new GameLogic(player, enemy); + game.run(); + } + + private static void startHumanVSHuman() { + player = new Player(getInputName(), false); + enemy = new Player(getInputName(), false); + showPlayerMenu(player); + showPlayerMenu(enemy); + GameLogic game = new GameLogic(player, enemy); + game.run(); + } + + private static void startComputerVSComputer() { + player = new Player("Computer 1", true); + enemy = new Player("Computer 2", true); + generateRandomPlacesForShips(player); + generateRandomPlacesForShips(enemy); + GameLogic game = new GameLogic(player, enemy); + game.run(); + } + + private static String getInputName() { + System.out.println("\t\tPlease, provide your name, it can contain only English letters in any case:"); + String name; + while (true) { + name = getInputNameS(); + if (name.matches("^[a-zA-Z ]{2,}$")) { + return name; + } else { + System.out.println("The name is incorrect, it can contain only English letters in any case"); + } + } + } + + private static void showPlayerMenu(Player currentPlayer) { + System.out.println("\tThe next step is to choose the type of ship placement. " + currentPlayer.getName() + ", please, select your choice:" + + "\n\t\t\t\t\t- 1 Add ships on the field manually" + + "\n\t\t\t\t\t- 2 Auto adding ships"); + String input = getInput(); + switch (input) { + case "1": + addShipsOneByOne(currentPlayer); + currentPlayer.getField().printField(); + System.out.println("Battlefield was successfully filled. \n"); + break; + case "2": + generateRandomPlacesForShips(currentPlayer); + currentPlayer.getField().printField(); + System.out.println("Battlefield was successfully filled. \n"); + break; + default: + System.out.println(WRONG_INPUT); + showPlayerMenu(currentPlayer); + } + } + + public static void showHelp() { + System.out.println("\tIn order to manually place the ship on the field, you need specify the correct coordinates, for example, g4 or B3 v. " + + "\n\t\t\t\t\t\tBy default, the direction is set to horizontal." + + "\n\t\t\t\t\tIf you want to rotate ship, add 'v' letter after coordinates." + + "\n\t\t\t\t\tIf you want to leave the game at any time, enter 'exit'"); + } + + public static void showCoordinatesHelp(){ + System.out.println("In order to select which cell you want to hit, you need specify the correct coordinates, for example, a5 or H6\n"); + } + + public static String getPlayerMotionInput() { + while (true) { + String input = getInput(); + if ("exit".equals(input)) { + exit(); + } else if (input.matches("^[a-j]([1-9]|10)$")) { + return input; + } else { + System.out.println(WRONG_INPUT); + } + + } + } + + public static String getInputPosition() { + while (true) { + String input = getInput(); + if ("exit".equals(input)) { + exit(); + } else if (input.matches("^[a-j]([1-9]|10)$") || input.matches("^[a-j]([1-9]|10)\\s[v]$")) { + return input; + } else { + System.out.println(WRONG_INPUT); + } + } + } + + private static String getInput() { + return scanner.nextLine().trim().toLowerCase(); + } + + private static String getInputNameS() { + return scanner.nextLine().trim(); + } + + + public static void destroyTrigger(String enemy, String currentPlayer, Ship ship, int x, int y) { + System.out.println(currentPlayer + " hit " + enemy + "'s ship at coordinates " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " and destroy " + ship.getName() + "."); + } + + public static void showWinScreen(Player currentPlayer, Player opponent) { + System.out.println("\n" + currentPlayer.getName() + ", congratulations, you won the game."); + showCongratulationsPicture(); + System.out.println("\n" + opponent.getName() + ", better luck next time.\n"); + + currentPlayer.getField().showTwoFields(currentPlayer, opponent); + System.out.println("This is the end of the game. Thank you for participating and see you soon."); + exit(); + } + + private static void exit() { + scanner.close(); + Runtime.getRuntime().exit(0); + } + + private static void showCongratulationsPicture() { + System.out.println(" .''. \n" + + " .''. . *''* :_\\/_: . \n" + + " :_\\/_: _\\(/_ .:.*_\\/_* : /\\ : .'.:.'.\n" + + " .''.: /\\ : ./)\\ ':'* /\\ * : '..'. -=:o:=-\n" + + " :_\\/_:'.:::. ' *''* * '.\\'/.' _\\(/_'.':'.'\n" + + " : /\\ : ::::: *_\\/_* -= o =- /)\\ ' *\n" + + " '..' ':::' * /\\ * .'/.\\'. '\n" + + " * *..* :\n" + + " *\n" + + " *"); + } + + public static void showLogo(){ + System.out.println(" |__\n" + + " |\\/\n" + + " ---\n" + + " / | [\n" + + " ! | |||\n" + + " _/| _/|-++'\n" + + " + +--| |--|--|_ |-\n" + + " { /|__| |/\\__| |--- |||__/\n" + + " +---------------___[}-_===_.'____ ||\n" + + " ____`-' ||___-{]_| _[}- | |_[___\\==-- \\/ _\n" + + " __..._____--==/___]_|__|_____________________________[___\\==--___,-----' |\n" + + "| Ilia.Prokofev./\n" + + " \\_______________________________________________________________________|"); + } + +} diff --git a/src/main/java/course_project/logic/GameLogic.java b/src/main/java/course_project/logic/GameLogic.java new file mode 100644 index 00000000..229bd1ea --- /dev/null +++ b/src/main/java/course_project/logic/GameLogic.java @@ -0,0 +1,120 @@ +package course_project.logic; + +import course_project.player.Player; +import course_project.ships.Ship; + +import static course_project.dialogue.Menu.*; +import static course_project.utils.RandomPositionGenerator.generateRandomForCell; + +public class GameLogic { + + private final Player player1; + private final Player player2; + private Player currentPlayer; + + public GameLogic(Player firstPlayer, Player secondPlayer) { + this.player1 = firstPlayer; + this.player2 = secondPlayer; + currentPlayer = firstPlayer; + } + + private void changeCurrentPlayer() { + if (currentPlayer == player1) { + currentPlayer = player2; + } else { + currentPlayer = player1; + } + } + + private Player getEnemy() { + return currentPlayer == player1 ? player2 : player1; + } + + public void run() { + showCoordinatesHelp(); + while (currentPlayer.getField().hasAvailableShips() && getEnemy().getField().hasAvailableShips()) { + if (currentPlayer.isComputer() && getEnemy().isComputer()) { + CPUTurn(currentPlayer); + } else if (!currentPlayer.isComputer() && getEnemy().isComputer()) { + playerTurn(currentPlayer); + } else if (currentPlayer.isComputer() && !getEnemy().isComputer()) { + CPUTurn(currentPlayer); + } + } + } + + private void endGame() { + if (currentPlayer.getField().hasAvailableShips()) { + showWinScreen(currentPlayer, getEnemy()); + } else { + showWinScreen(getEnemy(), currentPlayer); + } + } + + private void CPUTurn(Player currentPlayer) { + int x = generateRandomForCell(); + int y = generateRandomForCell(); + + if (!getEnemy().getField().getCellByPosition(x, y).isHit()) { + getEnemy().getField().getCellByPosition(x, y).setHit(true); + if (!getEnemy().getField().isCellEmpty(getEnemy().getField().getCellByPosition(x, y))) { + Ship enemyShip = getEnemy().getField().getCellByPosition(x, y).getReference(); + enemyShip.hitCountIncrease(); + if (enemyShip.isDestroyed()) { + destroyTrigger(getEnemy().getName(), currentPlayer.getName(), enemyShip, x, y); + getEnemy().getField().availableShipsDecrease(enemyShip); + if (!getEnemy().getField().hasAvailableShips()) { + endGame(); + } + } else { + System.out.println(currentPlayer.getName() + " hit " + getEnemy().getName() + "'s ship at coordinates " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + "."); + System.out.println(currentPlayer.getName() + " makes a move one more time."); + } + CPUTurn(currentPlayer); + } else { + System.out.println(currentPlayer.getName() + " select " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " and miss.\n"); + changeCurrentPlayer(); + } + } else { + CPUTurn(currentPlayer); + } + } + + private void playerTurn(Player currentPlayer) { + currentPlayer.getField().showTwoFields(currentPlayer, getEnemy()); + System.out.println(currentPlayer.getName() + ", it's your turn. Enter coordinates: "); + try { + String pos = getPlayerMotionInput(); + int x = Integer.parseInt(pos.substring(1)) - 1; + int y = Integer.parseInt(String.valueOf(pos.charAt(0) - 97)); + + if (getEnemy().getField().getCellByPosition(x, y).isHit()) { + System.out.println(currentPlayer.getName() + ", you have already chosen " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " coordinate, please re-enter: "); + playerTurn(currentPlayer); + } else { + getEnemy().getField().getCellByPosition(x, y).setHit(true); + if (!getEnemy().getField().isCellEmpty(getEnemy().getField().getCellByPosition(x, y))) { + Ship enemyShip = getEnemy().getField().getCellByPosition(x, y).getReference(); + enemyShip.hitCountIncrease(); + if (enemyShip.isDestroyed()) { + destroyTrigger(getEnemy().getName(), currentPlayer.getName(), enemyShip, x, y); + getEnemy().getField().availableShipsDecrease(enemyShip); + + if (!getEnemy().getField().hasAvailableShips()) { + endGame(); + } + } else { + System.out.println(currentPlayer.getName() + " hit " + getEnemy().getName() + "'s ship at coordinates " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1)); + System.out.println(currentPlayer.getName() + " makes a move one more time."); + } + playerTurn(currentPlayer); + } else { + System.out.println(currentPlayer.getName() + " select " + Character.toUpperCase((char) (y + 97)) + "" + (x + 1) + " and miss."); + changeCurrentPlayer(); + } + } + } catch (NumberFormatException e) { + playerTurn(currentPlayer); + } + } +} \ No newline at end of file diff --git a/src/main/java/course_project/player/Player.java b/src/main/java/course_project/player/Player.java new file mode 100644 index 00000000..129ce9ed --- /dev/null +++ b/src/main/java/course_project/player/Player.java @@ -0,0 +1,28 @@ +package course_project.player; + +import course_project.board.Battlefield; + +public class Player { + + private final boolean isComputer; + private final String name; + private final Battlefield battlefield; + + public Player(String name, boolean isComputer) { + this.isComputer = isComputer; + this.name = name; + this.battlefield = new Battlefield(); + } + + public boolean isComputer() { + return this.isComputer; + } + + public String getName() { + return this.name; + } + + public Battlefield getField() { + return this.battlefield; + } +} diff --git a/src/main/java/course_project/ships/Battleship.java b/src/main/java/course_project/ships/Battleship.java new file mode 100644 index 00000000..45bc6f90 --- /dev/null +++ b/src/main/java/course_project/ships/Battleship.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class Battleship extends Ship { + + private static final int SIZE = 4; + private static final String SHIP_NAME = "Battleship"; + + public Battleship() { + super(SIZE, SHIP_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Cruiser.java b/src/main/java/course_project/ships/Cruiser.java new file mode 100644 index 00000000..9d50b433 --- /dev/null +++ b/src/main/java/course_project/ships/Cruiser.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class Cruiser extends Ship { + + private static final int SIZE = 2; + private static final String SHIP_NAME = "Cruiser"; + + public Cruiser() { + super(SIZE, SHIP_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Destroyer.java b/src/main/java/course_project/ships/Destroyer.java new file mode 100644 index 00000000..26d7cb37 --- /dev/null +++ b/src/main/java/course_project/ships/Destroyer.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class Destroyer extends Ship { + + private static final int SIZE = 3; + private static final String SHIP_NAME = "Destroyer"; + + public Destroyer() { + super(SIZE, SHIP_NAME); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/PatrolBoat.java b/src/main/java/course_project/ships/PatrolBoat.java new file mode 100644 index 00000000..8cbd5641 --- /dev/null +++ b/src/main/java/course_project/ships/PatrolBoat.java @@ -0,0 +1,11 @@ +package course_project.ships; + +public final class PatrolBoat extends Ship { + + private static final int SIZE = 1; + private static final String SHIP_NAME = "Patrol Boat"; + + public PatrolBoat() { + super(SIZE, SHIP_NAME); + } +} diff --git a/src/main/java/course_project/ships/Ship.java b/src/main/java/course_project/ships/Ship.java new file mode 100644 index 00000000..c4c95a50 --- /dev/null +++ b/src/main/java/course_project/ships/Ship.java @@ -0,0 +1,30 @@ +package course_project.ships; + +public abstract class Ship { + + private final int size; + private final String name; + private int hitCount; + + protected Ship(int size, String shipName) { + this.size = size; + this.name = shipName; + this.hitCount = 0; + } + + public int getSize() { + return this.size; + } + + public String getName() { + return this.name; + } + + public boolean isDestroyed() { + return this.hitCount == this.size; + } + + public void hitCountIncrease() { + this.hitCount++; + } +} diff --git a/src/main/java/course_project/utils/Colors.java b/src/main/java/course_project/utils/Colors.java new file mode 100644 index 00000000..fc1963c6 --- /dev/null +++ b/src/main/java/course_project/utils/Colors.java @@ -0,0 +1,10 @@ +package course_project.utils; + +public final class Colors { + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_RED = "\033[1;91m"; + public static final String BACKGROUND_CYAN = "\u001B[46m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_MAGENTA = "\u001B[35m"; + public static final String ANSI_YELLOW = "\u001B[33m"; +} diff --git a/src/main/java/course_project/utils/RandomDirectionGenerator.java b/src/main/java/course_project/utils/RandomDirectionGenerator.java new file mode 100644 index 00000000..0b9396b3 --- /dev/null +++ b/src/main/java/course_project/utils/RandomDirectionGenerator.java @@ -0,0 +1,9 @@ +package course_project.utils; + +public class RandomDirectionGenerator { + + public static boolean generateRandomDirection() { + return Math.random() <= 0.5; + } + +} diff --git a/src/main/java/course_project/utils/RandomPositionGenerator.java b/src/main/java/course_project/utils/RandomPositionGenerator.java new file mode 100644 index 00000000..395f4b3b --- /dev/null +++ b/src/main/java/course_project/utils/RandomPositionGenerator.java @@ -0,0 +1,11 @@ +package course_project.utils; + +import java.util.Random; + +public class RandomPositionGenerator { + + public static int generateRandomForCell() { + Random random = new Random(); + return random.nextInt(10); + } +} diff --git a/src/main/java/homework_1/CharCount.java b/src/main/java/homework_1/CharCount.java new file mode 100644 index 00000000..6d4d0b1c --- /dev/null +++ b/src/main/java/homework_1/CharCount.java @@ -0,0 +1,18 @@ +package homework_1; + +public class CharCount { + + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; + + public static void run(String[] args) { + for (String arg : args) { + if (arg.equals("error")) { + System.out.println(ANSI_RED + "Alarm!" + ANSI_RESET); + break; + } else { + System.out.println(arg + ": " + arg.length() + " letters"); + } + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..d22a36b1 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,8 +2,7 @@ public class Main { - public static void main(String[] args) { - System.out.println("Hello homework!"); - } - + public static void main(String[] args) { + CharCount.run(args); + } } diff --git a/src/main/java/homework_2/pyramid_printer/Constants.java b/src/main/java/homework_2/pyramid_printer/Constants.java new file mode 100644 index 00000000..a6108434 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Constants.java @@ -0,0 +1,6 @@ +package homework_2.pyramid_printer; + +final class Constants { + static final String INPUT_MISMATCH = "Only 1 non-negative integer is allowed."; + static final String INPUT = "Enter a valid INT value for create a pyramid:"; +} diff --git a/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java new file mode 100644 index 00000000..674ea910 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/ExtraPyramidPrinter.java @@ -0,0 +1,29 @@ +package homework_2.pyramid_printer; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.pyramid_printer.Constants.INPUT; +import static homework_2.pyramid_printer.Constants.INPUT_MISMATCH; + +public class ExtraPyramidPrinter { + + public void run() { + System.out.println(INPUT); + try (Scanner scanner = new Scanner(System.in)) { + int x = scanner.nextInt(); + if (x >= 0) { + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print(x); + } + System.out.println(); + } + } else { + System.out.println(INPUT_MISMATCH); + } + } catch (InputMismatchException e) { + System.out.println(INPUT_MISMATCH); + } + } +} diff --git a/src/main/java/homework_2/pyramid_printer/Main.java b/src/main/java/homework_2/pyramid_printer/Main.java new file mode 100644 index 00000000..df73a866 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,14 @@ +package homework_2.pyramid_printer; + +public class Main { + + public static void main(String[] args) { + if (args.length > 1) { + System.out.println("Only 1 parameter is allowed"); + } else if (args.length == 0) { + new PyramidPrinter().run(); + } else if (args[0].equals("dRepresentation")) { + new ExtraPyramidPrinter().run(); + } + } +} diff --git a/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java new file mode 100644 index 00000000..fd249c8f --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,30 @@ +package homework_2.pyramid_printer; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.pyramid_printer.Constants.INPUT; +import static homework_2.pyramid_printer.Constants.INPUT_MISMATCH; + +public class PyramidPrinter { + + public void run() { + System.out.println(INPUT); + try (Scanner scanner = new Scanner(System.in)) { + int x = scanner.nextInt(); + if (x >= 0) { + for (int i = 1; i <= x; ++i) { + for (int j = 1; j <= i; ++j) { + System.out.print("x"); + } + System.out.println(); + } + } else { + System.out.println(INPUT_MISMATCH); + } + } catch (InputMismatchException e) { + System.out.println(INPUT_MISMATCH); + } + } +} + diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..be586c4b --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,8 @@ +package homework_2.random_chars_table; + +public class Main { + + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..74d6f9a4 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,90 @@ +package homework_2.random_chars_table; + +import java.util.InputMismatchException; +import java.util.Random; +import java.util.Scanner; + +public class RandomCharsTable { + + private int length; + private int width; + private String strategy; + + public void run() { + createTableWithRandomCharacters(); + } + + private void createTableWithRandomCharacters() { + System.out.println("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\" "); + inputData(); + checkLengthAndWidth(length, width); + checkStrategyValid(strategy); + fillAndPrintTable(strategy, getTable()); + } + + private char[][] getTable() { + return new char[length][width]; + } + + private void inputData() { + try (Scanner scanner = new Scanner(System.in)) { + String[] input = scanner.nextLine().split(" "); + length = Integer.parseInt(input[0]); + width = Integer.parseInt(input[1]); + strategy = input[2]; + } catch (NegativeArraySizeException | InputMismatchException | NumberFormatException e) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + } + } + + private void checkLengthAndWidth(int length, int width) { + if (length == 0 || width == 0) { + throw new InputMismatchException(); + } + } + + private void fillAndPrintTable(String strategy, char[][] table) { + Random random = new Random(); + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + table[i][j] = (char) (random.nextInt(((90 - 65) + 1)) + 65); + System.out.print("|" + table[i][j]); + } + System.out.print("|"); + System.out.println(); + } + checkStrategyAndExecute(strategy, table); + } + + private void checkStrategyValid(String strategy) { + if (!strategy.equals("even") && !strategy.equals("odd")) { + throw new InputMismatchException(); + } + } + + private void checkStrategyAndExecute(String strategy, char[][] table) { + StringBuilder str = new StringBuilder(); + if (strategy.equals("even")) { + System.out.print("Even letters - "); + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + if (table[i][j] % 2 == 0) { + str.append(table[i][j]).append(", "); + } + } + } + } else { + System.out.print("Odd letters - "); + for (int i = 0; i < length; i++) { + for (int j = 0; j < width; j++) { + if (table[i][j] % 2 != 0) { + str.append(table[i][j]).append(", "); + } + } + } + } + if (str.length() > 2) { + System.out.print(str.substring(0, str.length() - 2)); + } + } +} diff --git a/src/main/java/homework_2/traffic_light/ColorSelector.java b/src/main/java/homework_2/traffic_light/ColorSelector.java new file mode 100644 index 00000000..5664723d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ColorSelector.java @@ -0,0 +1,18 @@ +package homework_2.traffic_light; + +class ColorSelector { + protected static final String ANSI_RESET = "\u001B[0m"; + protected static final String ANSI_RED = "\u001B[31m"; + protected static final String ANSI_GREEN = "\u001B[32m"; + protected static final String ANSI_YELLOW = "\u001B[33m"; + protected static final String MESSAGE = "The traffic light is"; + + protected static String pickColor(String color) { + if (color.equals("green")) { + return MESSAGE + ANSI_GREEN + " Green" + ANSI_RESET + " now"; + } else if (color.equals("yellow")) { + return MESSAGE + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now"; + } else + return MESSAGE + ANSI_RED + " Red" + ANSI_RESET + " now"; + } +} diff --git a/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java new file mode 100644 index 00000000..ea8dd49a --- /dev/null +++ b/src/main/java/homework_2/traffic_light/ExtraTrafficLight.java @@ -0,0 +1,56 @@ +package homework_2.traffic_light; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.traffic_light.ColorSelector.pickColor; + + +public class ExtraTrafficLight { + + public void run() { + System.out.println("Provide time in \"hh:mm:ss\" format: "); + try (Scanner scan = new Scanner(System.in)) { + String nextLine = scan.next(); + String[] input = nextLine.split(":"); + int hours = Integer.parseInt(input[0]); + int minutes = Integer.parseInt(input[1]); + int seconds = Integer.parseInt(input[2]); + validateSecondMode(hours, minutes, seconds, input.length); + int globalseconds = seconds + minutes * 60 + hours * 3600; + getSeconds(globalseconds); + } catch (InputMismatchException e) { + System.out.println("You entered an invalid date."); + } catch (NumberFormatException e) { + System.out.println("Only numbers is allow."); + } catch (ArrayIndexOutOfBoundsException e) { + System.out.println("Incorrect input."); + } + } + + private static void validateSecondMode(int hours, int minutes, int seconds, int length) { + if ((hours < 0 || hours >= 24)) { + throw new InputMismatchException(); + } + if (minutes < 0 || minutes >= 60) { + throw new InputMismatchException(); + } + if (seconds < 0 || seconds >= 60) { + throw new InputMismatchException(); + } + if (length > 3) { + throw new InputMismatchException(); + } + } + + private static void getSeconds(int seconds) { + int sec = seconds % 60; + if (sec >= 0 && sec < 35) { + System.out.println(pickColor("green")); + } else if ((sec >= 35 && sec < 40) || sec >= 55) { + System.out.println(pickColor("yellow")); + } else { + System.out.println(pickColor("red")); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/Main.java b/src/main/java/homework_2/traffic_light/Main.java new file mode 100644 index 00000000..6d66c93c --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,14 @@ +package homework_2.traffic_light; + +public class Main { + + public static void main(String[] args) { + if (args.length > 1) { + System.out.println("Only 1 parameter is allowed"); + } else if (args.length == 0) { + new TrafficLight().run(); + } else if (args[0].equals("ExtraMode")) { + new ExtraTrafficLight().run(); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/TrafficLight.java b/src/main/java/homework_2/traffic_light/TrafficLight.java new file mode 100644 index 00000000..4fb569d1 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,36 @@ +package homework_2.traffic_light; + +import java.util.InputMismatchException; +import java.util.Scanner; + +import static homework_2.traffic_light.ColorSelector.pickColor; + +public class TrafficLight { + + public void run() { + System.out.println("Provide time in seconds:"); + try (Scanner scan = new Scanner(System.in)) { + int seconds = Integer.parseInt(scan.nextLine()); + if (seconds < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } else if (seconds >= 86400) { + System.out.println("Day is over."); + } else { + getSeconds(seconds); + } + } catch (InputMismatchException | NumberFormatException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } + + private static void getSeconds(int seconds) { + int sec = seconds % 60; + if (sec >= 0 && sec < 35) { + System.out.println(pickColor("green")); + } else if ((sec >= 35 && sec < 40) || sec >= 55) { + System.out.println(pickColor("yellow")); + } else { + System.out.println(pickColor("red")); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_3/ImmutableClassMan.java b/src/main/java/homework_3/ImmutableClassMan.java new file mode 100644 index 00000000..f87ab8f9 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClassMan.java @@ -0,0 +1,66 @@ +package homework_3; +/* + Rules for Creating an Immutable Class in Java +1. The class must be declared as final (So that child classes can’t be created). +2. Don't provide "setter" methods — methods that modify fields or objects referred to by fields. +3. Make all fields final and private. +4. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. +5. If the instance fields include references to mutable objects, don't allow those objects to be changed: + * Don't provide methods that modify the mutable objects. + * Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor, + !if necessary, create copies, and store references to the copies. + !Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods. +6. A parameterized constructor should initialize all the fields performing a deep copy (So that data members can’t be modified with object reference). + */ + +import java.util.ArrayList; +import java.util.List; + +public final class ImmutableClassMan { + + private final int age; + private final String name; + private final ArrayList job; + + public int getAge() { + return age; + } + + public String getName() { + return name; + } + + public List getJob() { + if (job != null){ + return new ArrayList<>(job); + } + return new ArrayList<>(); + } + + public ImmutableClassMan(int age, String name, List job) { + this.age = age; + this.name = name; + this.job = new ArrayList<>(job); + } + + public ImmutableClassMan(int age, String name) { + this.age = age; + this.name = name; + this.job = null; + } + + public ImmutableClassMan addNewJob (String job){ + List newList = getJob(); + newList.add(job); + return new ImmutableClassMan(age, name, newList); + } + + @Override + public String toString() { + return "ImmutableClassMan{" + + "age=" + age + + ", name='" + name + '\'' + + ", job=" + job + + '}'; + } +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotation.java b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java new file mode 100644 index 00000000..4ff3fcac --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotation.java @@ -0,0 +1,9 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Target({ElementType.LOCAL_VARIABLE, ElementType.FIELD, ElementType.CONSTRUCTOR}) +@Retention(RetentionPolicy.RUNTIME) +public @interface CustomAnnotation { + String name() default "Egor"; +} diff --git a/src/main/java/homework_4/custom_annotation/HelloGenerator.java b/src/main/java/homework_4/custom_annotation/HelloGenerator.java new file mode 100644 index 00000000..12ac97af --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/HelloGenerator.java @@ -0,0 +1,60 @@ +package homework_4.custom_annotation; + +import java.util.Arrays; + +public class HelloGenerator { + private String name; + private int age; + + public static void main(String args[]) { + HelloGenerator helloGenerator = new HelloGenerator(); + HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); + System.out.println(helloGenerator); + System.out.println(helloGenerator1); + } + + @CustomAnnotation + public HelloGenerator() { + String temp; + try { + CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getConstructor().getDeclaredAnnotations()[0]; + temp = customAnnotation.name(); + } catch (NoSuchMethodException e) { + temp = "Aristarch"; + this.age = 50; + } + this.name = temp; + this.age = 15; + } + + @CustomAnnotation + public HelloGenerator(String name, int age) { + try { + CustomAnnotation customAnnotation = (CustomAnnotation) this.getClass().getConstructor().getDeclaredAnnotations()[0]; + if (name == null) { + this.name = customAnnotation.name(); + } else { + this.name = name; + } + //this.name = name; + this.age = age; + } catch (NoSuchMethodException e) { + name = "Aristarch"; + this.age = 5090; + } + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Hello " + name + "!" + " You are " + age + " year old!"; + } + +} diff --git a/src/main/java/homework_4/custom_file_reader/CustomFileReader.java b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java new file mode 100644 index 00000000..34adc794 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,54 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Scanner; + +public class CustomFileReader { + + static final String GLOBAL_PATH = "src/main/resources/custom_file_reader/custom.file.reader.txt"; + + public void run1() { + try (Scanner input = new Scanner(new File(GLOBAL_PATH))) { + String output = ""; + while (input.hasNext()) { + output = output.concat(input.nextLine().replace(",", "") + "\n"); + } + output = output.replace(".", "").trim(); + System.out.println(output); + } catch (FileNotFoundException e) { + System.out.println("File not found."); + } + } + + public void run2() { + StringBuilder contents = new StringBuilder(); + try (BufferedReader reader = new BufferedReader(new FileReader(GLOBAL_PATH))) { + String check; + String space = ""; + while ((check = reader.readLine()) != null) { + contents.append(space); + contents.append(check.replaceAll("[,.]", "")); + space = "\n"; + } + System.out.println(contents); + } catch (IOException e) { + System.out.println("File not found."); + } + } + + public void run3() { + Path path = Paths.get(GLOBAL_PATH); + try { + List text = Files.readAllLines(path); + for (String line : text) { + System.out.println(line.replaceAll("[,.]", "")); + } + } catch (IOException e) { + System.out.println("File not found"); + } + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Main.java b/src/main/java/homework_4/custom_file_reader/Main.java new file mode 100644 index 00000000..fba1bc7d --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,8 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + new CustomFileReader().run2(); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..ca7c33d1 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,20 @@ +package homework_4.singleton; + +public class Singleton { + + private static Singleton instance; + + private Singleton() { + } + + public static Singleton getInstance() { + if (instance == null) { + synchronized (Singleton.class) { + if (instance == null) { + instance = new Singleton(); + } + } + } + return instance; + } +} diff --git a/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java new file mode 100644 index 00000000..fb799585 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,29 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CustomRegexMatcher { + + private static final String CHECK_USERNAME = "^[a-z0-9.-]{5,10}$"; + + public void run() { + System.out.println(checkRegex()); + } + + private static boolean checkRegex() { + return getInput().matches(CHECK_USERNAME); + } + + private static String getInput() { + String input = ""; + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + input = reader.readLine(); + } catch (IOException e) { + e.printStackTrace(); + } + return input; + } +} \ No newline at end of file diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..f8b52c06 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..64c1ff9c --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..025768b4 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,49 @@ +package homework_5.power_of_number; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public class PowerOfNumber { + + public void run() { + int[] input = getInput(); + if (input.length != 2) { + System.out.println("Only 2 non-negative integers are allowed"); + } else { + System.out.println(power(input[0], input[1])); + } + } + + private static int[] getInput() { + try { + Scanner scanner = new Scanner(System.in); + int[] input = new int[2]; + String[] string = scanner.nextLine().split(" "); + input[0] = Integer.parseInt(string[0]); + input[1] = Integer.parseInt(string[1]); + + if (string.length != 2) { + throw new InputMismatchException(); + } + + if (isValid(input[0]) && isValid(input[1])) { + return input; + } else { + throw new InputMismatchException(); + } + } catch (NumberFormatException | InputMismatchException | ArrayIndexOutOfBoundsException e) { + return new int[0]; + } + } + + private static int power(int number, int divide) { + if (divide != 0) { + return number * power(number, divide - 1); + } + return 1; + } + + private static boolean isValid(int number) { + return number >= 0; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java new file mode 100644 index 00000000..1b033b13 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,15 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; + +public class Main { + public static void main(String[] args) { + + HashMap map = new HashMap(); + MapProblemsMutableGenerator mapProblemsMutableGenerator = new MapProblemsMutableGenerator(50); + map.put(mapProblemsMutableGenerator, 1); + System.out.println(map.get(mapProblemsMutableGenerator)); + mapProblemsMutableGenerator.setWeight(25); + System.out.println(map.get(mapProblemsMutableGenerator)); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..a5b8c8f9 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,26 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +class MapProblemsCollisionGenerator { + + private final int age; + + MapProblemsCollisionGenerator(int age) { + this.age = age; + } + + @Override + public int hashCode() { + return Objects.hashCode(0); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null || getClass() != obj.getClass()) return false; + MapProblemsCollisionGenerator newObj = (MapProblemsCollisionGenerator) obj; + return age == newObj.age; + } + +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java new file mode 100644 index 00000000..5d81da6b --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,34 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; + +public class MapProblemsGenerator { + + public void makeCollision() { + + HashMap mapForCollisions = new HashMap<>(); + + MapProblemsCollisionGenerator obj1 = new MapProblemsCollisionGenerator(10); + MapProblemsCollisionGenerator obj2 = new MapProblemsCollisionGenerator(15); + + mapForCollisions.put(obj1, "field"); + mapForCollisions.put(obj2, "anotherField"); + System.out.println("mapForCollisions = " + mapForCollisions); + System.out.println(obj1.hashCode() == obj2.hashCode()); + } + + public void makeUnreachedObject() { + + HashMap mapForUnreachableObjects = new HashMap<>(); + + MapProblemsMutableGenerator obj1 = new MapProblemsMutableGenerator(125); + MapProblemsMutableGenerator obj2 = new MapProblemsMutableGenerator(126); + + mapForUnreachableObjects.put(obj1, "field"); + mapForUnreachableObjects.put(obj2, "anotherField"); + System.out.println("mapForUnreachableObjects = " + mapForUnreachableObjects); + System.out.println("mapForUnreachableObjects.get(obj1) = " + mapForUnreachableObjects.get(obj1)); + + } +} + diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..0471a07f --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,29 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +public class MapProblemsMutableGenerator { + + private int weight; + + public MapProblemsMutableGenerator(int weight) { + this.weight = weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return weight == that.weight; + } + + @Override + public int hashCode() { + return Objects.hash(weight); + } +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..cbe096dd --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,19 @@ +package homework_7; + +import homework_7.kitten_to_cat_function.Cat; +import homework_7.kitten_to_cat_function.Kitten; +import homework_7.kitten_to_cat_function.KittenToCatFunction; + +public class Main { + public static void main(String[] args) { + Kitten rudolf = new Kitten("Rudolf", 3, "Gottalot"); + Cat buchi = new Cat("Buchi", 12); + + KittenToCatFunction kittenToCat = kitten -> new Cat( kitten.getName(), kitten.getAge() + 10); + Cat grewRudolf = kittenToCat.grow(rudolf); + + System.out.println(buchi); + System.out.println(rudolf); + System.out.println(grewRudolf); + } +} \ No newline at end of file diff --git a/src/main/java/homework_7/kitten_to_cat_function/Cat.java b/src/main/java/homework_7/kitten_to_cat_function/Cat.java new file mode 100644 index 00000000..dc0bfdf6 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Cat.java @@ -0,0 +1,25 @@ +package homework_7.kitten_to_cat_function; + +public class Cat { + private final String name; + private final int age; + + public Cat(String name, int age) { + this.name = name; + this.age = age; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Cat's name: " + this.getName() + + ", Cat's age: " + this.getAge(); + } +} \ No newline at end of file diff --git a/src/main/java/homework_7/kitten_to_cat_function/Kitten.java b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java new file mode 100644 index 00000000..a6ba36d1 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/Kitten.java @@ -0,0 +1,32 @@ +package homework_7.kitten_to_cat_function; + +public class Kitten { + private final String nameOfEnemy; + private final String name; + private final int age; + + public Kitten(String name, int age, String enemyName) { + this.name = name; + this.age = age; + this.nameOfEnemy = enemyName; + } + + public String getNameOfEnemy() { + return nameOfEnemy; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + @Override + public String toString() { + return "Kitten's name: " + this.getName() + + ", Kitten's age: " + this.getAge() + + ", Kitten's enemy name: " + this.getNameOfEnemy() ; + } +} diff --git a/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java new file mode 100644 index 00000000..5c7b09d5 --- /dev/null +++ b/src/main/java/homework_7/kitten_to_cat_function/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7.kitten_to_cat_function; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/resources/custom_file_reader/custom.file.reader.txt b/src/main/resources/custom_file_reader/custom.file.reader.txt new file mode 100644 index 00000000..39206e66 --- /dev/null +++ b/src/main/resources/custom_file_reader/custom.file.reader.txt @@ -0,0 +1,6 @@ +Мы часто повторяем, что о человеке судят по его делам, но забываем иногда, что слово тоже поступок. +Речь человека — зеркало его самого. +Всё фальшивое , лживое или вульгарное, как бы человек ни пытался скрыть это от других, вся пустота, +черствость или грубость прорываются в его речи с такой же силой и очевидностью, +с какой проявляются искренность и благородство, глубина и тонкость мыслей и чувств. +То, о чём говорит человек, отражает его внутренний мир. \ No newline at end of file diff --git a/src/test/java/homework_1/char_count/CharCountTest.java b/src/test/java/homework_1/char_count/CharCountTest.java new file mode 100644 index 00000000..4768b3a8 --- /dev/null +++ b/src/test/java/homework_1/char_count/CharCountTest.java @@ -0,0 +1,43 @@ +package homework_1.char_count; + +import base.UnitBase; +import homework_1.Main; +import org.junit.jupiter.api.Test; + +import static homework_1.CharCount.ANSI_RED; +import static homework_1.CharCount.ANSI_RESET; +import static org.junit.jupiter.api.Assertions.*; + +class CharCountTest extends UnitBase { + @Test + void givenError_whenRun_thenExpected() { + String[] args = {"some", "new", "word", "and", "error"}; + Main.main(args); + printOut(); + assertEquals("some: 4 letters", getOutputLines()[0]); + assertEquals("new: 3 letters", getOutputLines()[1]); + assertEquals("word: 4 letters", getOutputLines()[2]); + assertEquals("and: 3 letters", getOutputLines()[3]); + assertEquals(ANSI_RED + "Alarm!" + ANSI_RESET, getOutputLines()[4]); + } + + @Test + void givenNoError_whenRun_thenExpected() { + String[] args = {"some", "new", "word", "and", "no error"}; + Main.main(args); + printOut(); + assertEquals("some: 4 letters", getOutputLines()[0]); + assertEquals("new: 3 letters", getOutputLines()[1]); + assertEquals("word: 4 letters", getOutputLines()[2]); + assertEquals("and: 3 letters", getOutputLines()[3]); + assertEquals("no error: 8 letters", getOutputLines()[4]); + } + + @Test + void givenZeroArguments_whenRun_thenExpected() { + String[] args = {}; + Main.main(args); + printOut(); + assertEquals("", getOutputLines()[0]); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java new file mode 100644 index 00000000..232de1e1 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/ExtraPyramidPrinterTest.java @@ -0,0 +1,61 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtraPyramidPrinterTest extends UnitBase { + private void run() { + new ExtraPyramidPrinter().run(); + removeFromOutput("Enter a valid INT value for create a pyramid:"); + printOut(); + } + + @Test + void givenPositive1_whenRun_thenExpected() { + setInput("1"); + + run(); + + assertEquals("1", getOutput()); + } + + @Test + void givenPositive3_whenRun_thenExpected() { + setInput("3"); + + run(); + + assertEquals("3", getOutputLines()[0]); + assertEquals("33", getOutputLines()[1]); + assertEquals("333", getOutputLines()[2]); + } + + @Test + void given0_whenRun_thenExpected() { + setInput("0"); + + run(); + + assertEquals("",getOutput()); + } + + @Test + void givenNegative_whenRun_thenExpectedError() { + setInput("-5"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + } + + @Test + void givenNaN_whenRun_thenExpectedError() { + setInput("asd"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.",getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..25a4a85b --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,62 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class PyramidPrinterTest extends UnitBase { + + private void run() { + new PyramidPrinter().run(); + removeFromOutput("Enter a valid INT value for create a pyramid:"); + printOut(); + } + + @Test + void givenPositive1_whenRun_thenExpected() { + setInput("1"); + + run(); + + assertEquals("x", getOutput()); + } + + @Test + void givenPositive3_whenRun_thenExpected() { + setInput("3"); + + run(); + + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + } + + @Test + void givenZero_whenRun_thenExpected() { + setInput("0"); + + run(); + + assertEquals("", getOutput()); + } + + @Test + void givenNegative_whenRun_thenExpectedError() { + setInput("-5"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.", getOutput()); + } + + @Test + void givenNaN_whenRun_thenExpectedError() { + setInput("asd"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed.", getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..7543d541 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,43 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class RandomCharsTableTest extends UnitBase { + + private void run() { + new RandomCharsTable().run(); + removeFromOutput("Enter valid table length, width and strategy(even or odd) in format \"length width strategy\""); + printOut(); + } + + @Test + void givenNegative_whenRun_thenArraySizeError() { + setInput("-1 5 even"); + + run(); + + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutput()); + } + + @Test + void givenWrongArgument_whenRun_thenInputError() { + setInput("error 5 even"); + + run(); + + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutput()); + } + + @Test + void givenWrongStrategyName_whenRun_thenInputError() { + setInput("4 5 error"); + + run(); + + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutput()); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java new file mode 100644 index 00000000..79926029 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/ExtraTrafficLightTest.java @@ -0,0 +1,96 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_2.traffic_light.ColorSelector.*; +import static org.junit.jupiter.api.Assertions.*; + +class ExtraTrafficLightTest extends UnitBase { + private void run() { + new ExtraTrafficLight().run(); + removeFromOutput("Provide time in \"hh:mm:ss\" format: "); + printOut(); + } + + @Test + void givenValidArguments_whenRun_thenYellowOutput() { + setInput("23:59:59"); + + run(); + + assertEquals("The traffic light is" + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now", getOutput()); + } + + @Test + void givenOneWrongArgument_whenRun_thenInputError() { + setInput("25:45:45"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void givenTwoWrongArguments_whenRun_thenInputError() { + setInput("25:65:45"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void givenThreeWrongArguments_whenRun_thenInputError() { + setInput("25:65:67"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void givenAdditionalField_whenRun_thenInputError() { + setInput("25:65:67:67"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void givenNaN_whenRun_thenNumberFormatError() { + setInput("error"); + + run(); + + assertEquals("Only numbers is allow.", getOutput()); + } + + @Test + void givenZero_whenRun_thenInputError() { + setInput("0"); + + run(); + + assertEquals("Incorrect input.", getOutput()); + } + + @Test + void givenNegativeArgument_whenRun_thenInputError() { + setInput("-5:23:45"); + + run(); + + assertEquals("You entered an invalid date.", getOutput()); + } + + @Test + void givenOutOfBoundsArguments_whenRun_thenInputError() { + setInput("5 5 5 5 5"); + + run(); + + assertEquals("Incorrect input.", getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..b1d46433 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,61 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_2.traffic_light.ColorSelector.*; +import static org.junit.jupiter.api.Assertions.*; + +class TrafficLightTest extends UnitBase { + + private void run() { + new TrafficLight().run(); + removeFromOutput("Provide time in seconds:"); + printOut(); + } + + @Test + void given55_whenRun_thenYellowOutput() { + setInput("55"); + + run(); + + assertEquals("The traffic light is" + ANSI_YELLOW + " Yellow" + ANSI_RESET + " now", getOutput()); + } + + @Test + void given7506_whenRun_thenGreenOutput() { + setInput("7506"); + + run(); + + assertEquals("The traffic light is" + ANSI_GREEN + " Green" + ANSI_RESET + " now", getOutput()); + } + + @Test + void givenNegative_whenRun_thenInputError() { + setInput("-5"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } + + @Test + void givenNan_whenRun_thenInputError() { + setInput("error"); + + run(); + + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutput()); + } + + @Test + void givenMoreThanDay_whenRun_thenDayOverError() { + setInput("86401"); + + run(); + + assertEquals("Day is over.", getOutput()); + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java new file mode 100644 index 00000000..111024a9 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/CustomAnnotationTest.java @@ -0,0 +1,48 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomAnnotationTest extends UnitBase { + HelloGenerator helloGenerator = new HelloGenerator(); + HelloGenerator helloGenerator1 = new HelloGenerator(null, 5); + HelloGenerator helloGenerator2 = new HelloGenerator("Aleksei", 35); + + @Test + void givenEmptyNameField_whenCreateObject_thenTakeFromAnnotation(){ + String expected = "Egor"; + assertEquals(expected, helloGenerator.getName()); + } + + @Test + void givenEmptyAgeField_whenCreateObject_thenTakeFromAnnotation(){ + int expected = 15; + assertEquals(expected, helloGenerator.getAge()); + } + + @Test + void run3(){ + String expected = "Egor"; + assertEquals(expected, helloGenerator1.getName()); + } + + @Test + void run4(){ + int expected = 5; + assertEquals(expected, helloGenerator1.getAge()); + } + + @Test + void run5(){ + String expected = "Aleksei"; + assertEquals(expected, helloGenerator2.getName()); + } + + @Test + void run6(){ + int expected = 35; + assertEquals(expected, helloGenerator2.getAge()); + } +} diff --git a/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java new file mode 100644 index 00000000..d4896b29 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,46 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + CustomFileReader customFileReader = new CustomFileReader(); + + @Test + void testRun1() { + customFileReader.run1(); + String expected = getOutput(); + if (expected.contains(",") || expected.contains(".")) { + throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); + } + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void testRun2() { + customFileReader.run2(); + String expected = getOutput(); + if (expected.contains(",") || expected.contains(".")) { + throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); + } + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void testRun3() { + customFileReader.run3(); + String expected = getOutput(); + if (expected.contains(",") || expected.contains(".")) { + throw new IllegalArgumentException("Text contains symbol ',' or symbol '.'"); + } + assertEquals(expected, getOutput()); + printOut(); + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..a6ec4ebf --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,15 @@ +package homework_4.singleton; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class SingletonTest { + + @Test + void assertSingletons() { + Singleton expected = Singleton.getInstance(); + Singleton actual = Singleton.getInstance(); + assertSame(expected, actual); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..359e3b65 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,40 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + + @Test + void givenCorrectUserName_whenCheckRegex_thenTrue() { + String expected = "true"; + setInput("nuker228"); + new CustomRegexMatcher().run(); + removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenCorrectUserNameWithDot_whenCheckRegex_thenTrue() { + String expected = "true"; + setInput("nuker.228"); + new CustomRegexMatcher().run(); + removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenIncorrectUserName_whenCheckRegex_thenFalse() { + String expected = "false"; + setInput("nuker@228"); + new CustomRegexMatcher().run(); + removeFromOutput("Enter your username, it must only contain letters, numbers and dot, minimum length 5, maximum length 10(inclusive):"); + assertEquals(expected, getOutput()); + printOut(); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..3158c09c --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,54 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + @Test + void given5and2_whenPoW_then25() { + String expected = String.valueOf((int) Math.pow(5, 2)); + setInput("5 2"); + new PowerOfNumber().run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void given0and5_whenPoW_then25() { + String expected = String.valueOf((int) Math.pow(0, 5)); + setInput("0 5"); + new PowerOfNumber().run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void given3and0_whenPoW_then1() { + String expected = String.valueOf((int) Math.pow(3, 0)); + setInput("3 0"); + new PowerOfNumber().run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenWrongInput_whenPoW_thenPrintError() { + String expected = "Only 2 non-negative integers are allowed"; + setInput("asd fdf"); + new PowerOfNumber().run(); + assertEquals(expected, getOutput()); + printOut(); + } + + @Test + void givenOnlyOneArgument_whenPoW_thenPrintError() { + String expected = "Only 2 non-negative integers are allowed"; + setInput("5"); + new PowerOfNumber().run(); + assertEquals(expected, getOutput()); + printOut(); + } +} \ No newline at end of file