diff --git a/README.md b/README.md index 5d686e9f..acffd2e9 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,24 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Emelianchik Svetlana* | 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 | +| HW1 | [ConsolePrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [TrafficLight](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/traffic_light) | The app that reads the input time of the day in seconds or in format hh:mm:ss and checks the traffic light to cross the road.| +| HW2 | [PyramidPrinter](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/pyramid_printer) | The app that reads the input number and prints the pyramid of symbol "x" with such a base. | +| HW2 | [RandomCharsTable](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_2/random_chars_table) | The app that reads two numbers and a string and prints a table with random chars from A to Z and also shows the even or odd chars that was in a table depending on a strategy that was chosen. | +| HW3 | [TrafficLightTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/traffic_light) | Add unit tests for Traffic Light app | +| HW3 | [PyramidPrinterTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/pyramid_printer) | Add unit tests for Print Pyramid app| +| HW3 | [RandomCharsTableTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_2/random_chars_table) | Add unit tests for Random Chars Table app | +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_3)
[ImmutableClassTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_3) | Add Immutable class | +| HW4 | [CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_file_reader) [CustomFileReaderTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_file_reader) | The app that reads data from the file and prints it to the console without dots and commas | +| HW4 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/singleton)
[SingletonTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/singleton) | The class that can have only one instance | +| HW4 | [CustomAnnotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_4/custom_annotation)
[CustomAnnotationTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_4/custom_annotation) | The annotation Author is used to get a default value when creating an instance of Book | +| HW5 | [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/math_power) [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/math_power) | PowerOfNumber App with method pow implemented via recursion | +| HW5 | [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_5/custom_regex_matcher) [CustomRegexMatcherTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/homework_5/custom_regex_matcher) | The App checks whether the arguments match the hardcoded regex | +| HW6 | [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_6/map_problems_generator) | 1)CollidingMapProblemsGeneratorKey is the class that always creates collisions in the HashMap.
2)MutableMapProblemsGeneratorKey is the class with HashCode method that returns random value. | +| HW7 | [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/homework_7) | Custom Functional Interface KittenToCatFunction with abstract method grow(). | +| Course Project | [BattleShipGame](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/main/java/course_project/battleship_game)
[UnitTests](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/SvetlanaEmelianchik/src/test/java/course_project/battleship_game)| BattleShip game with three modes (CVC, PVC, PVP). -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) +[Link to CodingBat profile](https://codingbat.com/done?user=sveta881@mail.ru&tag=8234249112) \ No newline at end of file diff --git a/build.gradle b/build.gradle index b91dc843..6bc2a810 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,8 @@ repositories { dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' + testCompile 'org.junit.jupiter:junit-jupiter-params:5.7.0' + testImplementation group: 'org.mockito', name: 'mockito-all', version: '1.10.19' } test { diff --git a/gradlew b/gradlew old mode 100644 new mode 100755 diff --git a/src/main/java/course_project/battleship_game/Main.java b/src/main/java/course_project/battleship_game/Main.java new file mode 100644 index 00000000..f00f300a --- /dev/null +++ b/src/main/java/course_project/battleship_game/Main.java @@ -0,0 +1,11 @@ +package course_project.battleship_game; + +import course_project.battleship_game.controller.GameController; + +public class Main { + + public static void main(String[] args) { + GameController controller = new GameController(); + controller.run(); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/controller/GameController.java b/src/main/java/course_project/battleship_game/controller/GameController.java new file mode 100644 index 00000000..37c87094 --- /dev/null +++ b/src/main/java/course_project/battleship_game/controller/GameController.java @@ -0,0 +1,40 @@ +package course_project.battleship_game.controller; + +import course_project.battleship_game.exception.GameException; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.GameService; + +import static course_project.battleship_game.controller.PrintController.printMessage; +import static course_project.battleship_game.utils.Constants.EXCEPTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEETS_CREATED_MESSAGE; +import static course_project.battleship_game.utils.Constants.WELCOME_MESSAGE; + +public class GameController { + private final GameService service = new GameService(); + private final InputController inputController = new InputController(); + + public void run() { + printMessage(WELCOME_MESSAGE); + GameMode gameMode = inputController.getGameMode(); + Player[] players = service.createPlayers(gameMode); + service.rollingDiceToChooseWhoStarts(players); + try { + service.createFleet(players); + } catch (GameException e) { + printMessage(EXCEPTION_MESSAGE); + } + printMessage(FLEETS_CREATED_MESSAGE); + Player player1 = players[0]; + Player player2 = players[1]; + boolean isGameOver = false; + while (!isGameOver) { + isGameOver = service.isGameOver(player1, player2, gameMode); + if (!isGameOver) { + isGameOver = service.isGameOver(player2, player1, gameMode); + } + } + service.determineWinner(players); + } + +} diff --git a/src/main/java/course_project/battleship_game/controller/InputController.java b/src/main/java/course_project/battleship_game/controller/InputController.java new file mode 100644 index 00000000..8589e8a7 --- /dev/null +++ b/src/main/java/course_project/battleship_game/controller/InputController.java @@ -0,0 +1,86 @@ +package course_project.battleship_game.controller; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.utils.CoordinateValidator; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static course_project.battleship_game.controller.PrintController.printMessage; +import static course_project.battleship_game.utils.Constants.CHOOSE_GAME_MODE_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_SHIP_DIRECTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.DEFAULT_PLAYER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.GET_CELL_COORDINATE_MESSAGE; +import static course_project.battleship_game.utils.Constants.GET_PLAYER_NAME_MESSAGE; + +public class InputController { + private final BufferedReader READER = new BufferedReader(new InputStreamReader(System.in)); + + public String getPlayerName() { + printMessage(GET_PLAYER_NAME_MESSAGE); + String line = readLine(); + return line == null || line.isEmpty() ? DEFAULT_PLAYER_NAME : line; + } + + public GameMode getGameMode() { + printMessage(CHOOSE_GAME_MODE_MESSAGE); + String mode = readLine(); + while (true) { + if (mode.equals("0")) { + return GameMode.CVC; + } else if (mode.equals("1")) { + return GameMode.PVC; + } else if (mode.equals("2")) { + return GameMode.PVP; + } else { + printMessage(ERROR_INPUT_MESSAGE); + mode = readLine(); + } + } + } + + public int getModeToCreateFleet() { + printMessage(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE); + return getZeroOrOne(); + } + + public int getDirection() { + printMessage(CHOOSE_SHIP_DIRECTION_MESSAGE); + return getZeroOrOne(); + } + + public Cell getCell() { + printMessage(GET_CELL_COORDINATE_MESSAGE); + String coordinate = readLine(); + while (!CoordinateValidator.isCoordinate(coordinate)) { + printMessage(ERROR_INPUT_MESSAGE); + coordinate = readLine(); + } + int x = Integer.parseInt(coordinate.substring(1)) - 1; + int y = ((int) coordinate.toUpperCase().charAt(0)) - 65; + return new Cell(x, y); + } + + private String readLine() { + try { + return READER.readLine(); + } catch (IOException e) { + return ""; + } + } + + private int getZeroOrOne() { + String mode = readLine(); + while (true) { + if (mode.equals("0") || mode.equals("1")) { + return Integer.parseInt(mode); + } + printMessage(ERROR_INPUT_MESSAGE); + mode = readLine(); + } + } +} diff --git a/src/main/java/course_project/battleship_game/controller/PrintController.java b/src/main/java/course_project/battleship_game/controller/PrintController.java new file mode 100644 index 00000000..3e9ea3c5 --- /dev/null +++ b/src/main/java/course_project/battleship_game/controller/PrintController.java @@ -0,0 +1,53 @@ +package course_project.battleship_game.controller; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; + +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; +import static java.lang.System.lineSeparator; + +public class PrintController { + + public static void printMessage(String message) { + System.out.print(message); + } + + public void printBoards(GameMode mode, Player player1, Player player2) { + if (mode.equals(GameMode.CVC) || !player1.getName().contains(DEFAULT_COMPUTER_NAME)) { + printBoardForPlayer(player1, false); + printBoardForPlayer(player2, true); + } + } + + public void printBoardForPlayer(Player player, boolean isEnemy) { + printMessage(String.format(PLAYER_BOARD_MESSAGE_FORMAT, player.getName())); + printHeader(); + Cell[][] boardMatrix = player.getBoard().getBoardMatrix(); + for (int y = 0; y < boardMatrix.length; y++) { + printMessage((char) (65 + y) + " "); + for (int x = 0; x < boardMatrix.length; x++) { + printCell(isEnemy, boardMatrix[y][x]); + } + printMessage(lineSeparator()); + } + } + + private void printCell(boolean isEnemy, Cell cell) { + if (isEnemy && cell.getCellStatus().equals(CellStatus.SHIP)) { + printMessage(CellStatus.EMPTY.getCharacter()); + } else { + printMessage(cell.getCellStatus().getCharacter()); + } + } + + private void printHeader() { + printMessage(" "); + for (int i = 1; i < 11; i++) { + printMessage(i + " "); + } + printMessage(lineSeparator()); + } +} diff --git a/src/main/java/course_project/battleship_game/exception/GameException.java b/src/main/java/course_project/battleship_game/exception/GameException.java new file mode 100644 index 00000000..47f20cfc --- /dev/null +++ b/src/main/java/course_project/battleship_game/exception/GameException.java @@ -0,0 +1,6 @@ +package course_project.battleship_game.exception; + +public class GameException extends RuntimeException { + public GameException() { + } +} diff --git a/src/main/java/course_project/battleship_game/model/Board.java b/src/main/java/course_project/battleship_game/model/Board.java new file mode 100644 index 00000000..6f08f3be --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Board.java @@ -0,0 +1,35 @@ +package course_project.battleship_game.model; + +import java.util.ArrayList; +import java.util.List; + +import static course_project.battleship_game.utils.Constants.BOARD_SIZE; + +public class Board { + private final Cell[][] boardMatrix; + private final List shipList; + + public Board() { + this.boardMatrix = createBoard(); + this.shipList = new ArrayList<>(); + } + + public Cell[][] getBoardMatrix() { + return boardMatrix; + } + + public List getShipList() { + return shipList; + } + + private Cell[][] createBoard() { + Cell[][] boardMatrix = new Cell[BOARD_SIZE][BOARD_SIZE]; + for (int y = 0; y < BOARD_SIZE; y++) { + for (int x = 0; x < BOARD_SIZE; x++) { + boardMatrix[y][x] = new Cell(x, y, CellStatus.EMPTY); + } + } + return boardMatrix; + } + +} diff --git a/src/main/java/course_project/battleship_game/model/Cell.java b/src/main/java/course_project/battleship_game/model/Cell.java new file mode 100644 index 00000000..7e0ab5b3 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Cell.java @@ -0,0 +1,55 @@ +package course_project.battleship_game.model; + +import java.util.Objects; + +public class Cell { + private final int x; + private final int y; + private CellStatus status; + + public Cell(int x, int y, CellStatus status) { //change in controller + this.x = x; + this.y = y; + this.status = status; + } + + public Cell(int x, int y) { + this.x = x; + this.y = y; + } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public CellStatus getCellStatus() { + return status; + } + + public void setCellStatus(CellStatus status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Cell cell = (Cell) o; + return getX() == cell.getX() && + getY() == cell.getY(); + } + + @Override + public int hashCode() { + return Objects.hash(getX(), getY()); + } + + @Override + public String toString() { + return String.valueOf((char) (y + 65)) + (x + 1); + } +} diff --git a/src/main/java/course_project/battleship_game/model/CellStatus.java b/src/main/java/course_project/battleship_game/model/CellStatus.java new file mode 100644 index 00000000..bcef00f0 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/CellStatus.java @@ -0,0 +1,19 @@ +package course_project.battleship_game.model; + +public enum CellStatus { + EMPTY("\uD83C\uDF0A"), + SHIP("\uD83D\uDEA2"), + HIT("\u274C"), + SHIP_BORDER("\uD83C\uDF0A"), + MISSED("\uD83D\uDD18"); + + private final String character; + + CellStatus(String character) { + this.character = character; + } + + public String getCharacter() { + return character; + } +} \ No newline at end of file diff --git a/src/main/java/course_project/battleship_game/model/GameMode.java b/src/main/java/course_project/battleship_game/model/GameMode.java new file mode 100644 index 00000000..c75bd971 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/GameMode.java @@ -0,0 +1,7 @@ +package course_project.battleship_game.model; + +public enum GameMode { + CVC, + PVC, + PVP +} diff --git a/src/main/java/course_project/battleship_game/model/Player.java b/src/main/java/course_project/battleship_game/model/Player.java new file mode 100644 index 00000000..a8307762 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Player.java @@ -0,0 +1,35 @@ +package course_project.battleship_game.model; + +import java.util.ArrayList; +import java.util.List; + +public class Player { + private final String name; + private final Board board; + private final int modeToCreateFleet; + private final List logOfMoves; + + public Player(String name, int modeToCreateFleet) { + this.name = name; + this.modeToCreateFleet = modeToCreateFleet; + this.board = new Board(); + this.logOfMoves = new ArrayList<>(); + } + + public Board getBoard() { + return board; + } + + public String getName() { + return name; + } + + public List getLogOfMoves() { + return logOfMoves; + } + + public int getModeToCreateFleet() { + return modeToCreateFleet; + } + +} diff --git a/src/main/java/course_project/battleship_game/model/Ship.java b/src/main/java/course_project/battleship_game/model/Ship.java new file mode 100644 index 00000000..40f15485 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/Ship.java @@ -0,0 +1,47 @@ +package course_project.battleship_game.model; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +public class Ship { + private final ShipType type; + private final List cellsList; + + public Ship(Cell start, ShipType type, int direction) { + this.type = type; + this.cellsList = generateShipCells(start, type, direction); + } + + public ShipType getType() { + return type; + } + + public List getCellsList() { + return cellsList; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Ship ship = (Ship) o; + return getType() == ship.getType() && + getCellsList().equals(ship.getCellsList()); + } + + @Override + public int hashCode() { + return Objects.hash(getType(), getCellsList()); + } + + private static List generateShipCells(Cell start, ShipType type, int direction) { + List cells = new ArrayList<>(); + for (int i = 0; i < type.getLength(); i++) { + int x = direction == 1 ? start.getX() : start.getX() + i; + int y = direction == 1 ? start.getY() + i : start.getY(); + cells.add(new Cell(x, y, CellStatus.SHIP)); + } + return cells; + } +} diff --git a/src/main/java/course_project/battleship_game/model/ShipType.java b/src/main/java/course_project/battleship_game/model/ShipType.java new file mode 100644 index 00000000..b23df332 --- /dev/null +++ b/src/main/java/course_project/battleship_game/model/ShipType.java @@ -0,0 +1,31 @@ +package course_project.battleship_game.model; + +public enum ShipType { + BATTLESHIP(4, 1), + CRUISER(3, 2), + DESTROYER(2, 3), + TORPEDO_BOAT(1, 4); + + private final int length; + private final int amount; + + ShipType(int length, int amount) { + this.length = length; + this.amount = amount; + } + + public int getLength() { + return length; + } + + public int getAmount() { + return amount; + } + + @Override + public String toString() { + return this.name() + + " with length of " + length + " cells." + + " The amount of " + this.name().replace("_", " ").toLowerCase() + "s should be " + amount + "."; + } +} diff --git a/src/main/java/course_project/battleship_game/service/BoardService.java b/src/main/java/course_project/battleship_game/service/BoardService.java new file mode 100644 index 00000000..f08d3ad6 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/BoardService.java @@ -0,0 +1,122 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Board; +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; +import course_project.battleship_game.model.ShipType; + +import java.util.List; + +import static course_project.battleship_game.utils.Constants.BOARD_SIZE; + +public class BoardService { + private final Board board; + + public BoardService(Board board) { + this.board = board; + } + + public boolean isHitCellOnBoard(Cell cell) { + Ship shipResult = board.getShipList().stream() + .filter(ship -> + ship.getCellsList().stream() + .anyMatch(cell1 -> cell1.equals(cell))).findFirst().orElse(null); + boolean hit = false; + if (shipResult != null) { + hit = new ShipService(shipResult).isHit(cell); + } + if (!hit) { + board.getBoardMatrix()[cell.getY()][cell.getX()].setCellStatus(CellStatus.MISSED); + } + return hit; + } + + public boolean isCreatingShipSuccessful(Cell start, ShipType type, int direction) { + if (isShipValidForBoard(start, type, direction)) { + Ship ship = new Ship(start, type, direction); + board.getShipList().add(ship); + addShipToBoardMatrix(ship); + markBoardCellsAroundShip(ship); + return true; + } + return false; + } + + private void addShipToBoardMatrix(Ship ship) { + for (Cell cell : ship.getCellsList()) { + int x = cell.getX(); + int y = cell.getY(); + board.getBoardMatrix()[y][x] = cell; + } + } + + private void markBoardCellsAroundShip(Ship ship) { + List cells = ship.getCellsList(); + for (Cell cell : cells) { + int x = cell.getX(); + int y = cell.getY(); + if (x + 1 < BOARD_SIZE && + board.getBoardMatrix()[y][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x + 1 < BOARD_SIZE && y - 1 >= 0 && + board.getBoardMatrix()[y - 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y - 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x + 1 < BOARD_SIZE && y + 1 < BOARD_SIZE && + board.getBoardMatrix()[y + 1][x + 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y + 1][x + 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && + board.getBoardMatrix()[y][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && y - 1 >= 0 && + board.getBoardMatrix()[y - 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y - 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (x - 1 >= 0 && y + 1 < BOARD_SIZE && + board.getBoardMatrix()[y + 1][x - 1].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y + 1][x - 1].setCellStatus(CellStatus.SHIP_BORDER); + } + if (y + 1 < BOARD_SIZE && + board.getBoardMatrix()[y + 1][x].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y + 1][x].setCellStatus(CellStatus.SHIP_BORDER); + } + if (y - 1 >= 0 && + board.getBoardMatrix()[y - 1][x].getCellStatus().equals(CellStatus.EMPTY)) { + board.getBoardMatrix()[y - 1][x].setCellStatus(CellStatus.SHIP_BORDER); + } + } + } + + private boolean isShipValidForBoard(Cell start, ShipType type, int direction) { + if (isTypeNotEnoughInBoardShipList(type) && isShipCellsFitBoard(start, type, direction)) { + Ship ship = new Ship(start, type, direction); + return !board.getShipList().contains(ship); + } + return false; + } + + private boolean isShipCellsFitBoard(Cell start, ShipType type, int direction) { + Ship ship = new Ship(start, type, direction); + List cells = ship.getCellsList(); + for (Cell cell : cells) { + if (cell.getX() < 0 || cell.getY() < 0 || cell.getX() >= board.getBoardMatrix().length || + cell.getY() >= board.getBoardMatrix().length) { + return false; + } + if (!(board.getBoardMatrix()[cell.getY()][cell.getX()]).getCellStatus().equals(CellStatus.EMPTY)) { + return false; + } + } + return true; + } + + private boolean isTypeNotEnoughInBoardShipList(ShipType type) { + int count = (int) board.getShipList().stream().filter(ship -> ship.getType().equals(type)).count(); + return count < type.getAmount(); + } + +} diff --git a/src/main/java/course_project/battleship_game/service/GameService.java b/src/main/java/course_project/battleship_game/service/GameService.java new file mode 100644 index 00000000..abefb30c --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/GameService.java @@ -0,0 +1,75 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.controller.InputController; +import course_project.battleship_game.controller.PrintController; +import course_project.battleship_game.exception.GameException; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; + +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.controller.PrintController.printMessage; +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.PLAYER_TURN_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.PLAYER_WINNER_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.ROLLING_DICE_MESSAGE; + +public class GameService { + private final InputController inputController = new InputController(); + private final PrintController printController = new PrintController(); + + public Player[] createPlayers(GameMode mode) { + Player[] players = new Player[2]; + players[0] = mode.equals(GameMode.CVC) ? new Player(DEFAULT_COMPUTER_NAME + " Mimi", 0) : + new Player(inputController.getPlayerName(), inputController.getModeToCreateFleet()); + players[1] = !mode.equals(GameMode.PVP) ? new Player(DEFAULT_COMPUTER_NAME + " Navi", 0) : + new Player(inputController.getPlayerName(), inputController.getModeToCreateFleet()); + return players; + } + + public void rollingDiceToChooseWhoStarts(Player[] players) { + printMessage(ROLLING_DICE_MESSAGE); + int dice = ThreadLocalRandom.current().nextInt(1, 3); + printMessage("Dice is " + dice + "\n"); + if (dice == 2) { + Player temp = players[0]; + players[0] = players[1]; + players[1] = temp; + } + printMessage(players[0].getName() + " will go first\n"); + } + + public void createFleet(Player[] players) { + if (players.length != 2) { + throw new GameException(); + } + new PlayerService(players[0]).createFleetForPlayer(); + new PlayerService(players[1]).createFleetForPlayer(); + } + + public boolean isGameOver(Player player1, Player player2, GameMode gameMode) { + boolean isMoveSuccessful = true; + printMessage(String.format(PLAYER_TURN_MESSAGE_FORMAT, player1.getName())); + while (isMoveSuccessful && !isNoMoreAliveShips(player1, player2)) { + isMoveSuccessful = new PlayerService(player1).isMoveSuccessful(player2); + printController.printBoards(gameMode, player1, player2); + } + return isNoMoreAliveShips(player1, player2); + } + + public void determineWinner(Player[] players) { + Player player1 = players[0]; + Player player2 = players[1]; + if (isNoMoreAliveShips(player1, player2)) { + long player1Fleet = new PlayerService(player1).countRemainedShips(); + long player2Fleet = new PlayerService(player2).countRemainedShips(); + Player winner = player1Fleet > player2Fleet ? player1 : player2; + printMessage(String.format(PLAYER_WINNER_MESSAGE_FORMAT, winner.getName())); + } + } + + private boolean isNoMoreAliveShips(Player player1, Player player2) { + return new PlayerService(player1).isNoMoreAliveShips() || new PlayerService(player2).isNoMoreAliveShips(); + } + +} diff --git a/src/main/java/course_project/battleship_game/service/PlayerService.java b/src/main/java/course_project/battleship_game/service/PlayerService.java new file mode 100644 index 00000000..e238b0c1 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/PlayerService.java @@ -0,0 +1,125 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.controller.InputController; +import course_project.battleship_game.controller.PrintController; +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.model.ShipType; +import course_project.battleship_game.utils.RandomCellGenerator; + +import java.util.concurrent.ThreadLocalRandom; + +import static course_project.battleship_game.controller.PrintController.printMessage; +import static course_project.battleship_game.utils.Constants.CREATING_FLEET_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.CREATING_SHIP_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.FLEET_CREATED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.HIT_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.MISSED_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.PLAYER_MOVE_MESSAGE_FORMAT; +import static course_project.battleship_game.utils.Constants.REMAINING_AMOUNT_OF_TYPE_TO_CREATE; +import static course_project.battleship_game.utils.Constants.SAME_COORDINATE_ERROR_MESSAGE; +import static course_project.battleship_game.utils.Constants.SHIP_CREATED_MESSAGE_FORMAT; + +public class PlayerService { + private final Player player; + private final InputController inputController = new InputController(); + private final PrintController printController = new PrintController(); + + public PlayerService(Player player) { + this.player = player; + } + + public boolean isMoveSuccessful(Player enemy) { + Cell cell = null; + while (cell == null || !player.getLogOfMoves().contains(cell)) { + if (player.getName().contains(DEFAULT_COMPUTER_NAME)) { + cell = RandomCellGenerator.generateRandomCell(); + } else { + cell = inputController.getCell(); + } + + if (!player.getLogOfMoves().contains(cell)) { + player.getLogOfMoves().add(cell); + } else { + if (!player.getName().contains(DEFAULT_COMPUTER_NAME)) { + printMessage(SAME_COORDINATE_ERROR_MESSAGE); + } + cell = null; + } + } + printMessage(String.format(PLAYER_MOVE_MESSAGE_FORMAT, player.getName(), cell.toString())); + boolean hit = new BoardService(enemy.getBoard()).isHitCellOnBoard(cell); + if (hit) { + printMessage(String.format(HIT_MESSAGE_FORMAT, player.getName(), enemy.getName(), cell.toString())); + } else { + printMessage(String.format(MISSED_MESSAGE_FORMAT, player.getName(), cell.toString())); + } + return hit; + } + + public boolean isNoMoreAliveShips() { + return player.getBoard().getShipList().stream().allMatch(ship -> new ShipService(ship).isNotAlive()); + } + + public void createFleetForPlayer() { + printMessage(String.format(CREATING_FLEET_MESSAGE_FORMAT, player.getName())); + if (player.getModeToCreateFleet() == 0) { + createRightAmountOfTypeRandomly(ShipType.BATTLESHIP); + createRightAmountOfTypeRandomly(ShipType.CRUISER); + createRightAmountOfTypeRandomly(ShipType.DESTROYER); + createRightAmountOfTypeRandomly(ShipType.TORPEDO_BOAT); + } else { + createRightAmountOfTypeManually(ShipType.BATTLESHIP); + createRightAmountOfTypeManually(ShipType.CRUISER); + createRightAmountOfTypeManually(ShipType.DESTROYER); + createRightAmountOfTypeManually(ShipType.TORPEDO_BOAT); + } + printMessage(String.format(FLEET_CREATED_MESSAGE_FORMAT, player.getName())); + } + + public long countRemainedShips() { + return player.getBoard().getShipList().stream().filter(ship -> !new ShipService(ship).isNotAlive()).count(); + } + + private void createRightAmountOfTypeManually(ShipType type) { + printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = inputController.getCell(); + int direction = inputController.getDirection(); + start.setCellStatus(CellStatus.SHIP); + boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + if (type.getAmount() - count != 0) { + printMessage(String.format(REMAINING_AMOUNT_OF_TYPE_TO_CREATE, + type.name().replace("_", " ").toLowerCase(), type.getAmount() - count)); + } + printController.printBoardForPlayer(player, false); + } else { + printMessage(ERROR_INPUT_MESSAGE); + } + } + printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + "You", type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + + private void createRightAmountOfTypeRandomly(ShipType type) { + printMessage(String.format(CREATING_SHIP_MESSAGE_FORMAT, type.toString())); + int count = 0; + while (count != type.getAmount()) { + Cell start = RandomCellGenerator.generateRandomCell(); + int direction = ThreadLocalRandom.current().nextInt(0, 2); + boolean created = new BoardService(player.getBoard()).isCreatingShipSuccessful(start, type, direction); + if (created) { + count++; + } + } + printMessage(String.format(SHIP_CREATED_MESSAGE_FORMAT, + player.getName(), type.getAmount(), type.name().replace("_", " ").toLowerCase())); + } + +} diff --git a/src/main/java/course_project/battleship_game/service/ShipService.java b/src/main/java/course_project/battleship_game/service/ShipService.java new file mode 100644 index 00000000..14557cb5 --- /dev/null +++ b/src/main/java/course_project/battleship_game/service/ShipService.java @@ -0,0 +1,26 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; + +public class ShipService { + private final Ship ship; + + public ShipService(Ship ship) { + this.ship = ship; + } + + public boolean isHit(Cell cell) { + if (ship.getCellsList().contains(cell)) { + ship.getCellsList().get(ship.getCellsList().indexOf(cell)).setCellStatus(CellStatus.HIT); + return true; + } + return false; + } + + public boolean isNotAlive() { + return ship.getCellsList().stream().allMatch(c -> c.getCellStatus().equals(CellStatus.HIT)); + } + +} diff --git a/src/main/java/course_project/battleship_game/utils/Constants.java b/src/main/java/course_project/battleship_game/utils/Constants.java new file mode 100644 index 00000000..48436ce6 --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/Constants.java @@ -0,0 +1,40 @@ +package course_project.battleship_game.utils; + +public class Constants { + public static final int BOARD_SIZE = 10; + public static final int LOWER_BOUND = 48; + public static final int UPPER_BOUND = 58; + public static final int CELL_INT_UPPER_BOUND = 11; + public static final int CHAR_LOWER_BOUND = 64; + public static final int CHAR_UPPER_BOUND = 75; + public static final String DEFAULT_PLAYER_NAME = "Player"; + public static final String DEFAULT_COMPUTER_NAME = "Computer"; + public static final String WELCOME_MESSAGE = "Welcome to the Battleship game!\n"; + public static final String CHOOSE_GAME_MODE_MESSAGE = "Choose game mode:\n" + + "0 - Computer vs Computer\n" + + "1 - Computer vs Player\n" + + "2 - Player vs Player\n"; + public static final String GET_PLAYER_NAME_MESSAGE = "Enter your name:\n"; + public static final String ROLLING_DICE_MESSAGE = "We are rolling dice to choose who will go first.\n"; + public static final String FLEETS_CREATED_MESSAGE = "\nFleets have been successfully created! Let's the battle begin!\n"; + public static final String CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE = "\nChoose mode:\n" + + "0 - place your ships randomly\n" + + "1 - place your ships by yourself.\n"; + public static final String CHOOSE_SHIP_DIRECTION_MESSAGE = "Put 0 - for horizontal placement or 1 - for vertical placement\n"; + public static final String GET_CELL_COORDINATE_MESSAGE = "Type coordinate in format (Letters from A to J, numbers from 1 to 10)\n"; + public static final String EXCEPTION_MESSAGE = "Something went wrong. Please, restart the program.\n"; + public static final String ERROR_INPUT_MESSAGE = "Wrong input.\n"; + public static final String SAME_COORDINATE_ERROR_MESSAGE = "You have already done this move. Please try again!\n"; + public static final String PLAYER_BOARD_MESSAGE_FORMAT = "\nThis is %s's board\n"; + public static final String PLAYER_TURN_MESSAGE_FORMAT = "\nNow it is %s's turn\n"; + public static final String PLAYER_MOVE_MESSAGE_FORMAT = "%s made move on %s.\n"; + public static final String HIT_MESSAGE_FORMAT = "%s has just hit the ship of %s located on %s!\n"; + public static final String PLAYER_WINNER_MESSAGE_FORMAT = "\nCongratulations %s! You won the game!\n"; + public static final String MISSED_MESSAGE_FORMAT = "%s missed on %s.\n"; + public static final String CREATING_FLEET_MESSAGE_FORMAT = "\nCreating fleet for %s\n"; + public static final String FLEET_CREATED_MESSAGE_FORMAT = "The fleet for %s has been created!\n"; + public static final String CREATING_SHIP_MESSAGE_FORMAT = "Creating %s\n"; + public static final String SHIP_CREATED_MESSAGE_FORMAT = "%s successfully created %d %s(s).\n"; + public static final String REMAINING_AMOUNT_OF_TYPE_TO_CREATE = "Remaining amount of %ss is %d\n"; + +} diff --git a/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java b/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java new file mode 100644 index 00000000..ce85da9b --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/CoordinateValidator.java @@ -0,0 +1,34 @@ +package course_project.battleship_game.utils; + +import static course_project.battleship_game.utils.Constants.CELL_INT_UPPER_BOUND; +import static course_project.battleship_game.utils.Constants.CHAR_LOWER_BOUND; +import static course_project.battleship_game.utils.Constants.CHAR_UPPER_BOUND; +import static course_project.battleship_game.utils.Constants.LOWER_BOUND; +import static course_project.battleship_game.utils.Constants.UPPER_BOUND; + +public class CoordinateValidator { + + public static boolean isCoordinate(String coordinate) { + if (coordinate.length() > 3) { + return false; + } + boolean isFirstLetter = CHAR_LOWER_BOUND < coordinate.toUpperCase().charAt(0) && + coordinate.toUpperCase().charAt(0) < CHAR_UPPER_BOUND; + boolean isNumber = coordinate.length() > 1 && isSuitableForCellCoordinate(coordinate.substring(1)); + return isFirstLetter && isNumber; + } + + private static boolean isSuitableForCellCoordinate(String str) { + int count = 0; + for (int ch : str.toCharArray()) { + if (LOWER_BOUND <= ch && ch < UPPER_BOUND) { + count++; + } + } + if (count == str.length()) { + int i = Integer.parseInt(str); + return 0 < i && i < CELL_INT_UPPER_BOUND; + } + return false; + } +} diff --git a/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java b/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java new file mode 100644 index 00000000..268d679d --- /dev/null +++ b/src/main/java/course_project/battleship_game/utils/RandomCellGenerator.java @@ -0,0 +1,14 @@ +package course_project.battleship_game.utils; + +import course_project.battleship_game.model.Cell; + +import java.util.concurrent.ThreadLocalRandom; + +public class RandomCellGenerator { + + public static Cell generateRandomCell() { + int x = ThreadLocalRandom.current().nextInt(0, 10); + int y = ThreadLocalRandom.current().nextInt(0, 10); + return new Cell(x, y); + } +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..f706148f 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,9 +1,28 @@ package homework_1; public class Main { + private static final String WARNING_MESSAGE = "Alarm!"; + private static final String NOT_FOUND_MESSAGE = "Arguments have not been found! Please enter arguments when starting the program!"; + private static final String INVALID_ARGUMENT = "error"; + private static final String OUTPUT_PATTERN = "%s: %d %s\n"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_RESET = "\u001B[0m"; - public static void main(String[] args) { - System.out.println("Hello homework!"); - } + public static void main(String[] args) { + if (args.length < 1) { + System.out.println(ANSI_RED + NOT_FOUND_MESSAGE + ANSI_RESET); + return; + } + for (String s : args) { + if (s.equals(INVALID_ARGUMENT)) { + System.out.println(ANSI_RED + WARNING_MESSAGE + ANSI_RESET); + return; + } + System.out.printf(OUTPUT_PATTERN, s, s.length(), generateNumerator(s.length())); + } + } -} + private static String generateNumerator(int wordLength) { + return wordLength == 1 ? "letter" : "letters"; + } +} \ No newline at end of file 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..e50e37eb --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer; + +public class Main { + public static void main(String[] args) { + new PyramidPrinter().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..3026e9a1 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,46 @@ +package homework_2.pyramid_printer; + +import homework_2.pyramid_printer.exception.PyramidPrinterException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static homework_2.pyramid_printer.utils.PyramidPrinterConstants.ERROR_MESSAGE; +import static homework_2.pyramid_printer.utils.PyramidPrinterConstants.INFO_MESSAGE; +import static homework_2.pyramid_printer.utils.PyramidPrinterConstants.LETTER; + +public class PyramidPrinter { + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println(INFO_MESSAGE); + String line = reader.readLine(); + int rows = getNumber(line); + generatePyramid(rows); + } catch (IOException | PyramidPrinterException e) { + System.out.println(ERROR_MESSAGE); + } + } + + private int getNumber(String text) throws PyramidPrinterException { + try { + int number = Integer.parseInt(text); + if (number < 0) { + throw new PyramidPrinterException(ERROR_MESSAGE); + } + return number; + } catch (NumberFormatException e) { + throw new PyramidPrinterException(ERROR_MESSAGE); + } + } + + private void generatePyramid(int rows) { + for (int i = 0; i < rows; i++) { + for (int j = 0; j <= i; j++) { + System.out.print(LETTER); + } + System.out.println(); + } + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java b/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java new file mode 100644 index 00000000..a0c7fc65 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/exception/PyramidPrinterException.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer.exception; + +public class PyramidPrinterException extends Throwable { + public PyramidPrinterException(String detailMessage) { + super(detailMessage); + } +} diff --git a/src/main/java/homework_2/pyramid_printer/utils/PyramidPrinterConstants.java b/src/main/java/homework_2/pyramid_printer/utils/PyramidPrinterConstants.java new file mode 100644 index 00000000..0ac0db19 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/utils/PyramidPrinterConstants.java @@ -0,0 +1,7 @@ +package homework_2.pyramid_printer.utils; + +public final class PyramidPrinterConstants { + public static final String INFO_MESSAGE = "Please enter a positive integer for rows"; + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String LETTER = "x"; +} 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..682fe366 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,7 @@ +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..aac2cd8c --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,88 @@ +package homework_2.random_chars_table; + +import homework_2.random_chars_table.exception.RandomCharsTableException; + +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.ERROR_MESSAGE; +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.MAX_CHAR; +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.MIN_CHAR; +import static homework_2.random_chars_table.utils.RandomCharsTableUtils.getData; +import static homework_2.random_chars_table.utils.RandomCharsTableUtils.printMessage; +import static java.lang.System.lineSeparator; + +public class RandomCharsTable { + + public void run() { + try { + String[] data = getData().split(" "); + if (isValidData(data)) { + showCharsTable(getNumber(data[0]), getNumber(data[1]), getStrategy(data[2])); + } else { + printMessage(ERROR_MESSAGE); + } + } catch (RandomCharsTableException e) { + printMessage(ERROR_MESSAGE); + } + } + + private boolean isValidData(String[] data) { + return data.length == 3; + } + + private void showCharsTable(int rows, int columns, String strategy) { + Set charsByStrategySet = new HashSet<>(); + for (int i = 0; i < rows; i++) { + printMessage("|"); + for (int j = 0; j < columns; j++) { + char ch = getRandomChar(); + if (isCharFitsStrategy(ch, strategy)) { + charsByStrategySet.add(ch); + } + printMessage(ch + "|"); + } + printMessage(lineSeparator()); + } + printMessage(getFormattedStringForPrinting(strategy, charsByStrategySet)); + } + + private char getRandomChar() { + return (char) ThreadLocalRandom.current().nextInt(MIN_CHAR, MAX_CHAR + 1); + } + + private int getNumber(String text) throws RandomCharsTableException { + int number; + try { + number = Integer.parseInt(text); + if (number < 1) { + throw new RandomCharsTableException(); + } + } catch (NumberFormatException e) { + throw new RandomCharsTableException(); + } + return number; + } + + private String getStrategy(String line) throws RandomCharsTableException { + if (line.toLowerCase().equals("odd") || line.toLowerCase().equals("even")) { + return line.toLowerCase(); + } else { + throw new RandomCharsTableException(); + } + } + + private boolean isCharFitsStrategy(char ch, String strategy) { + return strategy.equals("even") == (ch % 2 == 0); + } + + private String getFormattedStringForPrinting(String strategy, Set letters) { + String capFirst = strategy.substring(0, 1).toUpperCase() + strategy.substring(1); + StringBuilder result = new StringBuilder(capFirst + " letters - "); + for (Character ch : letters) { + result.append(ch).append(", "); + } + return result.substring(0, result.toString().trim().length() - 1); + } +} \ No newline at end of file diff --git a/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java b/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java new file mode 100644 index 00000000..cd113268 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/exception/RandomCharsTableException.java @@ -0,0 +1,6 @@ +package homework_2.random_chars_table.exception; + +public class RandomCharsTableException extends RuntimeException { + public RandomCharsTableException() { + } +} diff --git a/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableConstants.java b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableConstants.java new file mode 100644 index 00000000..cc58d02a --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableConstants.java @@ -0,0 +1,8 @@ +package homework_2.random_chars_table.utils; + +public final class RandomCharsTableConstants { + public static final String INFO_MESSAGE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; + public static final String ERROR_MESSAGE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public static final int MAX_CHAR = 90; + public static final int MIN_CHAR = 65; +} diff --git a/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableUtils.java b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableUtils.java new file mode 100644 index 00000000..843d9d2b --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/utils/RandomCharsTableUtils.java @@ -0,0 +1,25 @@ +package homework_2.random_chars_table.utils; + +import homework_2.random_chars_table.exception.RandomCharsTableException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static homework_2.random_chars_table.utils.RandomCharsTableConstants.INFO_MESSAGE; + + +public final class RandomCharsTableUtils { + public static void printMessage(String text) { + System.out.print(text); + } + + public static String getData() { + printMessage(INFO_MESSAGE); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + return reader.readLine(); + } catch (IOException e) { + throw new RandomCharsTableException(); + } + } +} 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..bee35a2c --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,10 @@ +package homework_2.traffic_light; + +import static homework_2.traffic_light.utils.TrafficLightUtils.isExtraMode; + +public class Main { + public static void main(String[] args) { + TrafficLight trafficLight = args.length > 0 && isExtraMode(args[0]) ? new TrafficLightExtraMode() : new TrafficLight(); + trafficLight.run(); + } +} 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..76b3c9de --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,53 @@ +package homework_2.traffic_light; + +import homework_2.traffic_light.exception.TrafficLightException; + +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.TrafficLightConstants.INFO_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.LIGHT_GREEN_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.LIGHT_RED_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.LIGHT_YELLOW_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_DAY; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_MINUTE; +import static homework_2.traffic_light.utils.TrafficLightUtils.getData; +import static homework_2.traffic_light.utils.TrafficLightUtils.printMessage; + +public class TrafficLight { + + public void run() { + printMessage(INFO_MESSAGE); + try { + String data = getData(); + printLight(getSeconds(data)); + } catch (TrafficLightException e) { + printMessage(e.getMessage()); + } + } + + protected int getSeconds(String time) { + try { + int seconds = Integer.parseInt(time); + if (seconds < 0) { + throw new TrafficLightException(ERROR_MESSAGE); + } else if (seconds > SECONDS_IN_DAY) { + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); + } + return seconds; + } catch (NumberFormatException e) { + throw new TrafficLightException(ERROR_MESSAGE); + } + } + + protected void printLight(int seconds) { + int remainder = seconds % SECONDS_IN_MINUTE; + if (remainder >= 0 && remainder < 35) { + printMessage(LIGHT_GREEN_MESSAGE); + } else if (remainder >= 40 && remainder < 55) { + printMessage(LIGHT_RED_MESSAGE); + } else { + printMessage(LIGHT_YELLOW_MESSAGE); + } + } +} + diff --git a/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java new file mode 100644 index 00000000..438f1202 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLightExtraMode.java @@ -0,0 +1,40 @@ +package homework_2.traffic_light; + +import homework_2.traffic_light.exception.TrafficLightException; + +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE; +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE_EXCEED_LIMIT; +import static homework_2.traffic_light.utils.TrafficLightConstants.INFO_MESSAGE_TO_EXTRA_MODE; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_HOUR; +import static homework_2.traffic_light.utils.TrafficLightConstants.SECONDS_IN_MINUTE; +import static homework_2.traffic_light.utils.TrafficLightUtils.getData; +import static homework_2.traffic_light.utils.TrafficLightUtils.printMessage; + +public class TrafficLightExtraMode extends TrafficLight { + + @Override + public void run() { + printMessage(INFO_MESSAGE_TO_EXTRA_MODE); + try { + String data = getData(); + printLight(getSeconds(data)); + } catch (TrafficLightException e) { + printMessage(e.getMessage()); + } + } + + @Override + protected int getSeconds(String time) { + String[] timeArray = time.trim().split(":"); + if (timeArray.length != 3 || time.contains("-")) { + throw new TrafficLightException(ERROR_MESSAGE); + } + int hours = Integer.parseInt(timeArray[0]); + int minutes = Integer.parseInt(timeArray[1]); + int seconds = Integer.parseInt(timeArray[2]); + if (hours > 23 || minutes > 59 || seconds > 59) { + throw new TrafficLightException(ERROR_MESSAGE_EXCEED_LIMIT); + } + return hours * SECONDS_IN_HOUR + minutes * SECONDS_IN_MINUTE + seconds; + } +} diff --git a/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java b/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java new file mode 100644 index 00000000..e570b76c --- /dev/null +++ b/src/main/java/homework_2/traffic_light/exception/TrafficLightException.java @@ -0,0 +1,7 @@ +package homework_2.traffic_light.exception; + +public class TrafficLightException extends RuntimeException { + public TrafficLightException(String message) { + super(message); + } +} diff --git a/src/main/java/homework_2/traffic_light/utils/TrafficLightConstants.java b/src/main/java/homework_2/traffic_light/utils/TrafficLightConstants.java new file mode 100644 index 00000000..8c490f51 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/utils/TrafficLightConstants.java @@ -0,0 +1,18 @@ +package homework_2.traffic_light.utils; + +public final class TrafficLightConstants { + public static final String ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String INFO_MESSAGE = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + + "Please enter time in seconds. From 0 to 86399: "; + public static final String INFO_MESSAGE_TO_EXTRA_MODE = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the extra mode. To enter the default mode you should restart the program with no arguments.\n" + + "Please enter time in format hh:mm:ss: "; + public static final String ERROR_MESSAGE_EXCEED_LIMIT = "The day is over"; + public static final String LIGHT_RED_MESSAGE = "RED"; + public static final String LIGHT_GREEN_MESSAGE = "GREEN"; + public static final String LIGHT_YELLOW_MESSAGE = "YELLOW"; + public static final int SECONDS_IN_DAY = 86399; + public static final int SECONDS_IN_HOUR = 3600; + public static final int SECONDS_IN_MINUTE = 60; +} \ No newline at end of file diff --git a/src/main/java/homework_2/traffic_light/utils/TrafficLightUtils.java b/src/main/java/homework_2/traffic_light/utils/TrafficLightUtils.java new file mode 100644 index 00000000..22435021 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/utils/TrafficLightUtils.java @@ -0,0 +1,28 @@ +package homework_2.traffic_light.utils; + +import homework_2.traffic_light.exception.TrafficLightException; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import static homework_2.traffic_light.utils.TrafficLightConstants.ERROR_MESSAGE; + +public final class TrafficLightUtils { + + public static void printMessage(String text) { + System.out.print(text); + } + + public static boolean isExtraMode(String mode) { + return mode.equals("1"); + } + + public static String getData() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + return reader.readLine(); + } catch (IOException e) { + throw new TrafficLightException(ERROR_MESSAGE); + } + } +} diff --git a/src/main/java/homework_3/Age.java b/src/main/java/homework_3/Age.java new file mode 100644 index 00000000..2bb3411b --- /dev/null +++ b/src/main/java/homework_3/Age.java @@ -0,0 +1,22 @@ +package homework_3; + +public class Age { + private final int day; + private final int month; + private final int year; + + public Age(int day, int month, int year) { + this.day = day; + this.month = month; + this.year = year; + } + + public Age(Age age) { + this(age.day, age.month, age.year); + } + + @Override + public String toString() { + return day + "." + month + "." + year; + } +} diff --git a/src/main/java/homework_3/ImmutableWorker.java b/src/main/java/homework_3/ImmutableWorker.java new file mode 100644 index 00000000..3224013b --- /dev/null +++ b/src/main/java/homework_3/ImmutableWorker.java @@ -0,0 +1,94 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * In general immutable class means that once an object is created, we cannot change its content, so: + * Immutable class should be final. + * Its fields should be private final. + * There should be getters but no setters. + * For link objects there should be a deep copy in the constructor. + * Constructor always creates a new object. + */ + +public final class ImmutableWorker { + private final String name; + private final String department; + private final int id; + private final List tasks; + private final Age age; + + public ImmutableWorker(String name, String department, int id, List tasks, Age age) { + this.name = name; + this.department = department; + this.id = id; + this.tasks = new ArrayList<>(tasks); + this.age = new Age(age); + } + + public ImmutableWorker(String name, String department, int id, Age age) { + this.name = name; + this.department = department; + this.id = id; + this.tasks = new ArrayList<>(); + this.age = new Age(age); + } + + public ImmutableWorker(String name, int id, Age age) { + this.name = name; + this.department = "No department"; + this.id = id; + this.tasks = new ArrayList<>(); + this.age = new Age(age); + } + + public ImmutableWorker updateWorker(String name, String department, int id, List tasks, Age age) { + if (name == null) { + name = this.name; + } + if (department == null) { + department = this.department; + } + if (id == 0) { + id = this.id; + } + if (tasks == null) { + tasks = new ArrayList<>(); + tasks.addAll(this.tasks); + } + if (age == null) { + age = new Age(this.age); + } + return new ImmutableWorker(name, department, id, tasks, age); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ImmutableWorker that = (ImmutableWorker) o; + return id == that.id && + Objects.equals(name, that.name) && + Objects.equals(department, that.department) && + Objects.equals(tasks, that.tasks) && + Objects.equals(age, that.age); + } + + @Override + public int hashCode() { + return Objects.hash(name, department, id, tasks, age); + } + + @Override + public String toString() { + return "ImmutableWorker{" + + "name='" + name + '\'' + + ", department='" + department + '\'' + + ", id=" + id + + ", tasks_size=" + tasks.size() + + ", age=" + age.toString() + + '}'; + } +} diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java new file mode 100644 index 00000000..fe2a7467 --- /dev/null +++ b/src/main/java/homework_3/Main.java @@ -0,0 +1,25 @@ +package homework_3; + +import java.util.ArrayList; +import java.util.List; + +public class Main { + public static void main(String[] args) { + List testList = new ArrayList<>(); + testList.add("task1"); + Age age = new Age(13, 5, 1980); + ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); + testList.add("task2"); + System.out.println("testList size: " + testList.size()); + System.out.println(worker); + System.out.println(worker.hashCode()); + ImmutableWorker worker1 = worker.updateWorker("Jackson", "Sales", 897, testList, age); + System.out.println(worker1); + System.out.println(worker1.hashCode()); + ImmutableWorker worker2 = worker.updateWorker(null, "Account", 0, null, null); + System.out.println(worker2); + System.out.println(worker2.hashCode()); + System.out.println(worker == worker1); + System.out.println(worker1 == worker2); + } +} diff --git a/src/main/java/homework_4/custom_annotation/Author.java b/src/main/java/homework_4/custom_annotation/Author.java new file mode 100644 index 00000000..5a84163c --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Author.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface Author { + String value() default "Unknown author"; +} diff --git a/src/main/java/homework_4/custom_annotation/Book.java b/src/main/java/homework_4/custom_annotation/Book.java new file mode 100644 index 00000000..31ea572f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Book.java @@ -0,0 +1,33 @@ +package homework_4.custom_annotation; + +@Author +public class Book { + private String name; + private String author; + + public Book(String name, String author) { + if (author == null || author.isEmpty()) { + Author defaultAuthor = (Author) this.getClass().getDeclaredAnnotations()[0]; + this.author = defaultAuthor.value(); + } else { + this.author = author; + } + this.name = name; + } + + public String getName() { + return name; + } + + public String getAuthor() { + return author; + } + + @Override + public String toString() { + return "Book{" + + "name='" + name + '\'' + + ", author='" + author + '\'' + + '}'; + } +} 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..03a78ce8 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,56 @@ +package homework_4.custom_file_reader; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Scanner; + +import static java.lang.System.lineSeparator; + +public class CustomFileReader { + private static final String FILE_NAME = "src/main/resources/custom_file_reader/Shakespeare.txt"; + private static final String ERROR_MESSAGE = "Can not read file."; + private static final File FILE = new File(FILE_NAME); + + public void run1() { + try (BufferedReader reader = new BufferedReader(new FileReader(FILE))) { + String line; + while ((line = reader.readLine()) != null) { + printMessage(trimDotsAndCommas(line) + lineSeparator()); + } + } catch (IOException e) { + printMessage(ERROR_MESSAGE); + } + } + + public void run2() { + try (Scanner scanner = new Scanner(FILE)){ + while (scanner.hasNextLine()) { + printMessage(trimDotsAndCommas(scanner.nextLine()) + lineSeparator()); + } + } catch (FileNotFoundException e) { + printMessage(ERROR_MESSAGE); + } + } + + public void run3() { + try { + String data = new String(Files.readAllBytes(Paths.get(FILE_NAME))); + printMessage(trimDotsAndCommas(data)); + } catch (IOException e) { + printMessage(ERROR_MESSAGE); + } + } + + private void printMessage(String message) { + System.out.print(message); + } + + private String trimDotsAndCommas(String line){ + return line.replaceAll("[,.]", ""); + } +} 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..fdf40d57 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,14 @@ +package homework_4.custom_file_reader; + +public class Main { + public static void main(String[] args) { + CustomFileReader reader = new CustomFileReader(); + reader.run1(); + System.out.println(); + reader.run2(); + System.out.println(); + reader.run3(); + } +} + + 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..107c5f74 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,12 @@ +package homework_4.singleton; + +public class Singleton { + + private static class SingletonHolder { + public static final Singleton HOLDER_INSTANCE = new Singleton(); + } + + public static Singleton getInstance() { + return SingletonHolder.HOLDER_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..4cbd5879 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,26 @@ +package homework_5.custom_regex_matcher; + +import java.util.regex.Pattern; + +import static java.lang.System.lineSeparator; + +public class CustomRegexMatcher { + private static final String CUSTOM_REGEX = "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}:\\d+?[zZ]\\s*–\\s*\\[.*]\\s*-\\s*.*"; + + public void run(String[] args) { + if (args.length < 1) { + printMessage("false"); + } + for (String s : args) { + printMessage(isMatching(s) + lineSeparator()); + } + } + + private boolean isMatching(String str) { + return Pattern.matches(CUSTOM_REGEX, str); + } + + private void printMessage(String text) { + System.out.print(text); + } +} \ 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..5462ced7 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,9 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + //The example of an argument matching hardcoded regex: "2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l" + new CustomRegexMatcher().run(args); + } +} diff --git a/src/main/java/homework_5/math_power/Main.java b/src/main/java/homework_5/math_power/Main.java new file mode 100644 index 00000000..01b02e57 --- /dev/null +++ b/src/main/java/homework_5/math_power/Main.java @@ -0,0 +1,8 @@ +package homework_5.math_power; + +public class Main { + + public static void main(String[] args) { + new PowerOfNumber().run(args); + } +} diff --git a/src/main/java/homework_5/math_power/PowerOfNumber.java b/src/main/java/homework_5/math_power/PowerOfNumber.java new file mode 100644 index 00000000..803dadcf --- /dev/null +++ b/src/main/java/homework_5/math_power/PowerOfNumber.java @@ -0,0 +1,26 @@ +package homework_5.math_power; + +import static homework_5.math_power.utils.PowerOfNumberConstants.ERROR_MESSAGE; +import static homework_5.math_power.utils.PowerOfNumberValidator.isValid; + +public class PowerOfNumber { + + public void run(String[] args) { + if (isValid(args)) { + printMessage(String.valueOf(pow(Integer.parseInt(args[0]), Integer.parseInt(args[1])))); + } else { + printMessage(ERROR_MESSAGE); + } + } + + private long pow(int value, int powValue) { + if (powValue == 0) { + return 1; + } + return powValue == 1 ? value : value * pow(value, powValue - 1); + } + + private static void printMessage(String text) { + System.out.print(text); + } +} diff --git a/src/main/java/homework_5/math_power/utils/PowerOfNumberConstants.java b/src/main/java/homework_5/math_power/utils/PowerOfNumberConstants.java new file mode 100644 index 00000000..4e9e570c --- /dev/null +++ b/src/main/java/homework_5/math_power/utils/PowerOfNumberConstants.java @@ -0,0 +1,5 @@ +package homework_5.math_power.utils; + +public final class PowerOfNumberConstants { + public static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; +} diff --git a/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java b/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java new file mode 100644 index 00000000..b4716091 --- /dev/null +++ b/src/main/java/homework_5/math_power/utils/PowerOfNumberValidator.java @@ -0,0 +1,12 @@ +package homework_5.math_power.utils; + +public final class PowerOfNumberValidator { + + public static boolean isValid(String[] args) { + try { + return args.length == 2 && Integer.parseInt(args[0]) >= 0 && Integer.parseInt(args[1]) >= 0; + } catch (NumberFormatException e) { + return false; + } + } +} 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..086a8ea1 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,35 @@ +package homework_6.map_problems_generator; + +import homework_6.map_problems_generator.impl.CollidingMapProblemsGeneratorKey; +import homework_6.map_problems_generator.impl.MutableMapProblemsGeneratorKey; + +import java.util.HashMap; +import java.util.Map; + +public class Main { + + public static void main(String[] args) { + System.out.println("Testing CollidingMapProblemsGeneratorKey:"); + Map, Integer> mapWithCollidingKeys = new HashMap<>(); + MapProblemsGenerator myObject1 = new CollidingMapProblemsGeneratorKey<>(); + MapProblemsGenerator myObject2 = new CollidingMapProblemsGeneratorKey<>("2"); + System.out.println("myObject1.hashCode() == myObject2.hashCode() = " + (myObject1.hashCode() == myObject2.hashCode())); + System.out.println("myObject1.equals(myObject2) = " + myObject1.equals(myObject2)); + mapWithCollidingKeys.put(myObject1, 1); + mapWithCollidingKeys.put(myObject2, 1); + System.out.println("mapWithCollidingKeys.size() = " + mapWithCollidingKeys.size()); + + System.out.println("\n----\n"); + + System.out.println("Testing MutableMapProblemsGeneratorKey:"); + Map, Integer> map = new HashMap<>(); + MutableMapProblemsGeneratorKey myObject = new MutableMapProblemsGeneratorKey<>(1); + System.out.println("myObject = " + myObject); + map.put(myObject, 1); + myObject.setId(2); + System.out.println("map.containsKey(myObject) = " + map.containsKey(myObject)); + System.out.println("map.size() = " + map.size()); + System.out.println("Map keys:"); + map.keySet().forEach(System.out::println); + } +} 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..465170fa --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,5 @@ +package homework_6.map_problems_generator; + +public interface MapProblemsGenerator { + +} diff --git a/src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java b/src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java new file mode 100644 index 00000000..90274fb8 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/impl/AbstractMapProblemsGenerator.java @@ -0,0 +1,30 @@ +package homework_6.map_problems_generator.impl; + +import homework_6.map_problems_generator.MapProblemsGenerator; + +import java.util.Objects; + +public abstract class AbstractMapProblemsGenerator implements MapProblemsGenerator { + private final T value; + + public AbstractMapProblemsGenerator(T value) { + this.value = value; + } + + public T getValue() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + AbstractMapProblemsGenerator that = (AbstractMapProblemsGenerator) o; + return Objects.equals(getValue(), that.getValue()); + } + + @Override + public int hashCode() { + return Objects.hash(getValue()); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java b/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java new file mode 100644 index 00000000..a78d7d65 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/impl/CollidingMapProblemsGeneratorKey.java @@ -0,0 +1,22 @@ +package homework_6.map_problems_generator.impl; + +public class CollidingMapProblemsGeneratorKey extends AbstractMapProblemsGenerator { + + public CollidingMapProblemsGeneratorKey() { + super(null); + } + + public CollidingMapProblemsGeneratorKey(T value) { + super(value); + } + + @Override + public int hashCode() { + return 31; + } + + @Override + public boolean equals(Object o) { + return super.equals(o); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java b/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java new file mode 100644 index 00000000..27ada9f6 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/impl/MutableMapProblemsGeneratorKey.java @@ -0,0 +1,28 @@ +package homework_6.map_problems_generator.impl; + +public class MutableMapProblemsGeneratorKey extends AbstractMapProblemsGenerator { + private int id; + + public MutableMapProblemsGeneratorKey(int id) { + super(null); + this.id = id; + } + + public void setId(int id) { + this.id = id; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + if (!super.equals(o)) return false; + MutableMapProblemsGeneratorKey that = (MutableMapProblemsGeneratorKey) o; + return id == that.id; + } + + @Override + public int hashCode() { + return Integer.hashCode(id); + } +} \ No newline at end of file diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..951f6092 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,9 @@ +package homework_7; + +import homework_7.entity.Cat; +import homework_7.entity.Kitten; + +@FunctionalInterface +public interface KittenToCatFunction { + C grow(K kitten); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..dc6ba0ce --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,13 @@ +package homework_7; + +import homework_7.entity.Cat; +import homework_7.entity.Kitten; + +public class Main { + + public static void main(String[] args) { + Kitten kitten = new Kitten("Kitty Tom", 1, 2); + Cat grownUpCat = kitten.grow(k -> new Cat(k.getName().replace("Kitty", "Big"), k.getAge() + 1, k.getWeight() * 2)); + System.out.println(grownUpCat); + } +} diff --git a/src/main/java/homework_7/entity/Cat.java b/src/main/java/homework_7/entity/Cat.java new file mode 100644 index 00000000..c8ae3eed --- /dev/null +++ b/src/main/java/homework_7/entity/Cat.java @@ -0,0 +1,34 @@ +package homework_7.entity; + +public class Cat { + private final String name; + private final int age; + private final int weight; + + public Cat(String name, int age, int weight) { + this.name = name; + this.age = age; + this.weight = weight; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public int getWeight() { + return weight; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + ", weight=" + weight + + '}'; + } +} diff --git a/src/main/java/homework_7/entity/Kitten.java b/src/main/java/homework_7/entity/Kitten.java new file mode 100644 index 00000000..303416bd --- /dev/null +++ b/src/main/java/homework_7/entity/Kitten.java @@ -0,0 +1,40 @@ +package homework_7.entity; + +import homework_7.KittenToCatFunction; + +public class Kitten { + private final String name; + private final int age; + private final int weight; + + public Kitten(String name, int age, int weight) { + this.name = name; + this.age = age; + this.weight = weight; + } + + public Cat grow(KittenToCatFunction function) { + return function.grow(this); + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public int getWeight() { + return weight; + } + + @Override + public String toString() { + return "Kitten{" + + "name='" + name + '\'' + + ", age=" + age + + ", weight=" + weight + + '}'; + } +} diff --git a/src/main/resources/custom_file_reader/Shakespeare.txt b/src/main/resources/custom_file_reader/Shakespeare.txt new file mode 100644 index 00000000..07b4889d --- /dev/null +++ b/src/main/resources/custom_file_reader/Shakespeare.txt @@ -0,0 +1,28 @@ +All the world's a stage, +And all the men and women merely players; +They have their exits and their entrances, +And one man in his time plays many parts, +His acts being seven ages. At first, the infant, +Mewling and puking in the nurse's arms. +Then the whining schoolboy, with his satchel +And shining morning face, creeping like snail +Unwillingly to school. And then the lover, +Sighing like furnace, with a woeful ballad +Made to his mistress' eyebrow. Then a soldier, +Full of strange oaths and bearded like the pard, +Jealous in honor, sudden and quick in quarrel, +Seeking the bubble reputation +Even in the cannon's mouth. And then the justice, +In fair round belly with good capon lined, +With eyes severe and beard of formal cut, +Full of wise saws and modern instances; +And so he plays his part. The sixth age shifts +Into the lean and slippered pantaloon, +With spectacles on nose and pouch on side; +His youthful hose, well saved, a world too wide +For his shrunk shank, and his big manly voice, +Turning again toward childish treble, pipes +And whistles in his sound. Last scene of all, +That ends this strange eventful history, +Is second childishness and mere oblivion, +Sans teeth, sans eyes, sans taste, sans everything. \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/controller/GameControllerTest.java b/src/test/java/course_project/battleship_game/controller/GameControllerTest.java new file mode 100644 index 00000000..5ddf28fe --- /dev/null +++ b/src/test/java/course_project/battleship_game/controller/GameControllerTest.java @@ -0,0 +1,17 @@ +package course_project.battleship_game.controller; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GameControllerTest extends UnitBase { + + @Test + void testRunCVC() { + setInput("0"); + new GameController().run(); + printOut(); + assertTrue(getOutput().contains("won the game")); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/controller/InputControllerTest.java b/src/test/java/course_project/battleship_game/controller/InputControllerTest.java new file mode 100644 index 00000000..0b0eb31b --- /dev/null +++ b/src/test/java/course_project/battleship_game/controller/InputControllerTest.java @@ -0,0 +1,100 @@ +package course_project.battleship_game.controller; + +import base.UnitBase; +import course_project.battleship_game.model.GameMode; +import org.junit.jupiter.api.Test; + +import static course_project.battleship_game.utils.Constants.CHOOSE_GAME_MODE_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE; +import static course_project.battleship_game.utils.Constants.CHOOSE_SHIP_DIRECTION_MESSAGE; +import static course_project.battleship_game.utils.Constants.DEFAULT_PLAYER_NAME; +import static course_project.battleship_game.utils.Constants.ERROR_INPUT_MESSAGE; +import static course_project.battleship_game.utils.Constants.GET_PLAYER_NAME_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class InputControllerTest extends UnitBase { + private InputController controller; + + @Override + protected void setInput(String input) { + super.setInput(input); + controller = new InputController(); + } + + @Test + void testGetNameString() { + setInput("Hero"); + String playerName = controller.getPlayerName(); + assertEquals("Hero", playerName); + assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); + } + + @Test + void testGetNameStringNumber() { + setInput("11"); + String playerName = controller.getPlayerName(); + assertEquals("11", playerName); + assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); + } + + @Test + void testGetNameEmptyString() { + setInput(""); + String playerName = controller.getPlayerName(); + assertEquals(DEFAULT_PLAYER_NAME, playerName); + assertTrue(getOutput().contains(GET_PLAYER_NAME_MESSAGE.trim())); + } + + @Test + void testGetDirectionZero() { + setInput("2\nString\n0"); + assertEquals(0, controller.getDirection()); + assertTrue(getOutput().contains(ERROR_INPUT_MESSAGE)); + assertTrue(getOutput().contains(CHOOSE_SHIP_DIRECTION_MESSAGE.trim())); + } + + @Test + void testGetDirectionOne() { + setInput("1"); + assertEquals(1, controller.getDirection()); + assertTrue(getOutput().contains(CHOOSE_SHIP_DIRECTION_MESSAGE.trim())); + } + + @Test + void testGetModeToCreateFleetZero() { + setInput("2\nString\n0"); + assertEquals(0, controller.getModeToCreateFleet()); + assertTrue(getOutput().contains(ERROR_INPUT_MESSAGE.trim())); + assertTrue(getOutput().contains(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE.trim())); + } + + @Test + void testGetModeToCreateFleetOne() { + setInput("1"); + assertEquals(1, controller.getModeToCreateFleet()); + assertTrue(getOutput().contains(CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE.trim())); + } + + @Test + void testGetGameModeCVC() { + setInput("0"); + assertEquals(GameMode.CVC, controller.getGameMode()); + assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); + } + + @Test + void testGetGameModePVC() { + setInput("1"); + assertEquals(GameMode.PVC, controller.getGameMode()); + assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); + } + + @Test + void testGetGameModePVP() { + setInput("s\n5\n2"); + assertEquals(GameMode.PVP, controller.getGameMode()); + assertTrue(getOutput().contains(CHOOSE_GAME_MODE_MESSAGE.trim())); + } + +} diff --git a/src/test/java/course_project/battleship_game/controller/PrintControllerTest.java b/src/test/java/course_project/battleship_game/controller/PrintControllerTest.java new file mode 100644 index 00000000..33d85eef --- /dev/null +++ b/src/test/java/course_project/battleship_game/controller/PrintControllerTest.java @@ -0,0 +1,51 @@ +package course_project.battleship_game.controller; + +import base.UnitBase; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import course_project.battleship_game.service.PlayerService; +import org.junit.jupiter.api.Test; + +import static course_project.battleship_game.utils.Constants.PLAYER_BOARD_MESSAGE_FORMAT; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PrintControllerTest extends UnitBase { + + @Test + void testPrintBoards() { + GameMode mode = GameMode.CVC; + Player hero = new Player("Hero", 0); + Player villain = new Player("Villain", 0); + PlayerService serviceHero = new PlayerService(hero); + PlayerService serviceVillain = new PlayerService(villain); + serviceHero.createFleetForPlayer(); + serviceVillain.createFleetForPlayer(); + new PrintController().printBoards(mode, hero, villain); + printOut(); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT, hero.getName()))); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT, villain.getName()))); + } + + @Test + void printBoardForPlayerHero() { + Player hero = new Player("Hero", 0); + PlayerService service = new PlayerService(hero); + service.createFleetForPlayer(); + new PrintController().printBoardForPlayer(hero, false); + printOut(); + assertEquals(10, hero.getBoard().getShipList().size()); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT.trim(), hero.getName()))); + } + + @Test + void printBoardForPlayerEnemy() { + Player enemy = new Player("Villain", 0); + PlayerService service = new PlayerService(enemy); + service.createFleetForPlayer(); + new PrintController().printBoardForPlayer(enemy, true); + printOut(); + assertEquals(10, enemy.getBoard().getShipList().size()); + assertTrue(getOutput().contains(String.format(PLAYER_BOARD_MESSAGE_FORMAT.trim(), enemy.getName()))); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/service/BoardServiceTest.java b/src/test/java/course_project/battleship_game/service/BoardServiceTest.java new file mode 100644 index 00000000..f5e9621e --- /dev/null +++ b/src/test/java/course_project/battleship_game/service/BoardServiceTest.java @@ -0,0 +1,73 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Board; +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; +import course_project.battleship_game.model.ShipType; +import course_project.battleship_game.utils.RandomGenerator; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +public class BoardServiceTest { + + @ParameterizedTest + @MethodSource("testCasesIsHitCellOnBoard") + void isHitCellOnBoardTrue(final Ship ship) { + Board board = Mockito.mock(Board.class); + BoardService boardService = new BoardService(board); + when(board.getShipList()).thenReturn(new ArrayList<>(Arrays.asList(ship))); + assertTrue(boardService.isHitCellOnBoard(ship.getCellsList().get(0))); + } + + @Test + void isHitCellOnBoardFalse() { + Board board = new Board(); + BoardService boardService = new BoardService(board); + Cell cell = new Cell(1, 1); + assertFalse(boardService.isHitCellOnBoard(cell)); + } + + @Test + void testIsCreatingShipSuccessfulTrue() { + Board board = new Board(); + BoardService boardService = new BoardService(board); + assertTrue(boardService.isCreatingShipSuccessful(new Cell(0, 0, CellStatus.SHIP), ShipType.TORPEDO_BOAT, 0)); + } + + @Test + void testIsCreatingShipSuccessfulFalse() { + Board board = Mockito.mock(Board.class); + BoardService boardService = new BoardService(board); + Cell start = new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()); + Ship ship = new Ship(start, ShipType.BATTLESHIP, 0); + when(board.getShipList()).thenReturn(new ArrayList<>(Arrays.asList(ship))); + assertFalse(boardService.isCreatingShipSuccessful(start, ShipType.BATTLESHIP, 0)); + } + + static Stream testCasesIsHitCellOnBoard() { + return Stream.of( + Arguments.of( + new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.BATTLESHIP, 0)), + Arguments.of(new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.TORPEDO_BOAT, 0)), + Arguments.of(new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.CRUISER, 1)), + Arguments.of(new Ship(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9()), + ShipType.DESTROYER, 1)) + ); + } + +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/service/GameServiceTest.java b/src/test/java/course_project/battleship_game/service/GameServiceTest.java new file mode 100644 index 00000000..967d6011 --- /dev/null +++ b/src/test/java/course_project/battleship_game/service/GameServiceTest.java @@ -0,0 +1,87 @@ +package course_project.battleship_game.service; + +import base.UnitBase; +import course_project.battleship_game.model.GameMode; +import course_project.battleship_game.model.Player; +import org.junit.jupiter.api.Test; + +import static course_project.battleship_game.utils.Constants.DEFAULT_COMPUTER_NAME; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class GameServiceTest extends UnitBase { + private final GameService service = new GameService(); + + @Test + void testCreateUsersCVC() { + Player[] players = service.createPlayers(GameMode.CVC); + assertEquals(2, players.length); + assertTrue(players[0].getName().contains("Computer")); + assertTrue(players[1].getName().contains("Computer")); + } + + @Test + void testCreateUsersPVC() { + setInput("test\n0"); + Player[] players = service.createPlayers(GameMode.PVC); + assertEquals(2, players.length); + assertFalse(players[0].getName().contains("Computer")); + assertTrue(players[1].getName().contains("Computer")); + } + + @Test + void testCreateUsersPVP() { + setInput("test\n0\ntest1\n0"); + Player[] players = service.createPlayers(GameMode.PVP); + assertEquals(2, players.length); + assertFalse(players[0].getName().contains(DEFAULT_COMPUTER_NAME)); + assertFalse(players[1].getName().contains(DEFAULT_COMPUTER_NAME)); + } + + @Test + void testRollingDiceShufflePlayers() { + Player[] players = service.createPlayers(GameMode.CVC); + Player one = players[0]; + service.rollingDiceToChooseWhoStarts(players); + if (getOutput().contains("1")) { + assertEquals(one, players[0]); + } else { + assertNotEquals(one, players[0]); + } + } + + @Test + void testCreateFleet() { + Player[] players = service.createPlayers(GameMode.CVC); + service.createFleet(players); + assertEquals(10, players[0].getBoard().getShipList().size()); + assertEquals(10, players[1].getBoard().getShipList().size()); + } + + @Test + void testIsGameOverOnStart() { + Player[] players = service.createPlayers(GameMode.CVC); + service.createFleet(players); + assertFalse(service.isGameOver(players[0], players[1], GameMode.CVC)); + } + + @Test + void testIsGameOverTrue() { + Player[] players = service.createPlayers(GameMode.CVC); + PlayerService playerService = new PlayerService(players[0]); + playerService.createFleetForPlayer(); + assertTrue(service.isGameOver(players[0], players[1], GameMode.CVC)); + } + + @Test + void testDetermineWinner() { + Player[] players = service.createPlayers(GameMode.CVC); + PlayerService playerService = new PlayerService(players[0]); + playerService.createFleetForPlayer(); + service.determineWinner(players); + assertTrue(getOutput().contains(players[0].getName())); + } + +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/service/PlayerServiceTest.java b/src/test/java/course_project/battleship_game/service/PlayerServiceTest.java new file mode 100644 index 00000000..0b44f914 --- /dev/null +++ b/src/test/java/course_project/battleship_game/service/PlayerServiceTest.java @@ -0,0 +1,40 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Player; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class PlayerServiceTest { + + @Test + void testCreateRandomFleetForPlayer() { + Player hero = new Player("Hero", 0); + PlayerService serviceHero = new PlayerService(hero); + serviceHero.createFleetForPlayer(); + assertEquals(10, hero.getBoard().getShipList().size()); + } + + @Test + void testIsNoMoreAliveShipsTrue() { + Player hero = new Player("Hero", 0); + PlayerService serviceHero = new PlayerService(hero); + serviceHero.createFleetForPlayer(); + hero.getBoard().getShipList().forEach(ship -> ship.getCellsList().forEach(cell -> cell.setCellStatus(CellStatus.HIT))); + assertTrue(serviceHero.isNoMoreAliveShips()); + assertEquals(0, serviceHero.countRemainedShips()); + } + + @Test + void testIsNoMoreAliveShipsFalse() { + Player hero = new Player("Hero", 0); + PlayerService serviceHero = new PlayerService(hero); + serviceHero.createFleetForPlayer(); + assertFalse(serviceHero.isNoMoreAliveShips()); + assertEquals(10, serviceHero.countRemainedShips()); + } + +} diff --git a/src/test/java/course_project/battleship_game/service/ShipServiceTest.java b/src/test/java/course_project/battleship_game/service/ShipServiceTest.java new file mode 100644 index 00000000..7e661a6a --- /dev/null +++ b/src/test/java/course_project/battleship_game/service/ShipServiceTest.java @@ -0,0 +1,57 @@ +package course_project.battleship_game.service; + +import course_project.battleship_game.model.Cell; +import course_project.battleship_game.model.CellStatus; +import course_project.battleship_game.model.Ship; +import course_project.battleship_game.utils.RandomGenerator; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mockito; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +public class ShipServiceTest { + + @ParameterizedTest + @MethodSource("testCasesIsHit") + void testIsHit(final Cell cell) { + Ship shipTrue = Mockito.mock(Ship.class); + Ship shipFalse = Mockito.mock(Ship.class); + ShipService shipServiceTrue = new ShipService(shipTrue); + ShipService shipServiceFalse = new ShipService(shipFalse); + when(shipTrue.getCellsList()).thenReturn(new ArrayList<>(Arrays.asList(cell))); + assertTrue(shipServiceTrue.isHit(cell)); + when(shipFalse.getCellsList()).thenReturn(new ArrayList<>()); + assertFalse(shipServiceFalse.isHit(cell)); + } + + @Test + void testIsNotAlive() { + Ship ship = Mockito.mock(Ship.class); + ShipService shipService = new ShipService(ship); + when(ship.getCellsList()) + .thenReturn(new ArrayList<>(Collections.singletonList( + new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9(), CellStatus.HIT)))); + assertTrue(shipService.isNotAlive()); + } + + static Stream testCasesIsHit() { + return Stream.of( + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())), + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())), + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())), + Arguments.of(new Cell(RandomGenerator.generateNumFrom0to9(), RandomGenerator.generateNumFrom0to9())) + ); + } + + +} \ No newline at end of file diff --git a/src/test/java/course_project/battleship_game/utils/Constants.java b/src/test/java/course_project/battleship_game/utils/Constants.java new file mode 100644 index 00000000..fbba0f54 --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/Constants.java @@ -0,0 +1,17 @@ +package course_project.battleship_game.utils; + +public class Constants { + public static final String DEFAULT_PLAYER_NAME = "Player"; + public static final String ERROR_INPUT_MESSAGE = "Wrong input."; + public static final String CHOOSE_SHIP_DIRECTION_MESSAGE = "Put 0 - for horizontal placement or 1 - for vertical placement"; + public static final String CHOOSE_MODE_TO_CREATE_FLEET_MESSAGE = "\nChoose mode:\n" + + "0 - place your ships randomly\n" + + "1 - place your ships by yourself."; + public static final String CHOOSE_GAME_MODE_MESSAGE = "Choose game mode:\n" + + "0 - Computer vs Computer\n" + + "1 - Computer vs Player\n" + + "2 - Player vs Player"; + public static final String GET_PLAYER_NAME_MESSAGE = "Enter your name:"; + public static final String DEFAULT_COMPUTER_NAME = "Computer"; + public static final String PLAYER_BOARD_MESSAGE_FORMAT = "This is %s's board"; +} diff --git a/src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java b/src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java new file mode 100644 index 00000000..b33726b3 --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/CoordinateValidatorTest.java @@ -0,0 +1,35 @@ +package course_project.battleship_game.utils; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + + +public class CoordinateValidatorTest { + + @ParameterizedTest + @MethodSource("testCasesIsCoordinate") + void test(final String coordinate, final boolean expected) { + assertEquals(expected, CoordinateValidator.isCoordinate(coordinate)); + } + + static Stream testCasesIsCoordinate() { + return Stream.of( + Arguments.of("A1", true), + Arguments.of("a10", true), + Arguments.of("j1", true), + Arguments.of("J10", true), + Arguments.of("K6", false), + Arguments.of("x10", false), + Arguments.of("I11", false), + Arguments.of("1", false), + Arguments.of("y", false), + Arguments.of("i 9", false), + Arguments.of("90", false) + ); + } +} diff --git a/src/test/java/course_project/battleship_game/utils/RandomGenerator.java b/src/test/java/course_project/battleship_game/utils/RandomGenerator.java new file mode 100644 index 00000000..377ccd5b --- /dev/null +++ b/src/test/java/course_project/battleship_game/utils/RandomGenerator.java @@ -0,0 +1,9 @@ +package course_project.battleship_game.utils; + +import java.util.concurrent.ThreadLocalRandom; + +public class RandomGenerator { + public static int generateNumFrom0to9() { + return ThreadLocalRandom.current().nextInt(0, 10); + } +} 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..4b25c514 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,49 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_PYRAMID_PRINTER; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_PYRAMID_PRINTER; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PyramidPrinterTest extends UnitBase { + + void run() { + new PyramidPrinter().run(); + removeFromOutput(INFO_MESSAGE_PYRAMID_PRINTER); + printOut(); + } + + @Test + void given1_whenRun_thenPrintPyramid() { + setInput("1"); + run(); + assertEquals("x", getOutput()); + } + + @Test + void given5_whenRun_thenPrintPyramid() { + setInput("5"); + run(); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + assertEquals("xxxxx", getOutputLines()[4]); + } + + @Test + void givenNaN_whenRun_getWrongFormatMessage() { + setInput("word"); + run(); + assertEquals(ERROR_MESSAGE_PYRAMID_PRINTER, getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_getWrongFormatMessage() { + setInput("-5"); + run(); + assertEquals(ERROR_MESSAGE_PYRAMID_PRINTER, getOutput()); + } +} 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..c13ec7c6 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,94 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_RANDOM_CHARS_TABLE; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_RANDOM_CHARS_TABLE; +import static homework_2.utils.Homework2Constants.MAX_CHAR; +import static homework_2.utils.Homework2Constants.MIN_CHAR; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class RandomCharsTableTest extends UnitBase { + + void run() { + new RandomCharsTable().run(); + removeFromOutput(INFO_MESSAGE_RANDOM_CHARS_TABLE); + printOut(); + } + + @Test + void testPrintAlphabetChars() { + setInput("1 2 odd"); + run(); + removeFromOutput("Odd letters - "); + removeFromOutput("|"); + removeFromOutput("\n"); + removeFromOutput(", "); + char[] chars = getOutput().toCharArray(); + assertTrue(chars[0] >= MIN_CHAR && chars[0] <= MAX_CHAR); + assertTrue(chars[1] >= MIN_CHAR && chars[1] <= MAX_CHAR); + assertTrue(chars[2] >= MIN_CHAR && chars[2] <= MAX_CHAR); + } + + @Test + void givenOddStrategy_whenRun_thenPrintOddChars() { + setInput("2 8 odd"); + run(); + removeFromOutput("Odd letters - "); + List letters = new ArrayList<>(); + if (getOutputLines()[getOutputLines().length - 1].contains(",")) { + letters = Arrays.asList(getOutputLines()[getOutputLines().length - 1].split(", ")); + } else { + letters.add(getOutputLines()[2]); + } + for (String s : letters) { + char ch = s.charAt(0); + assertNotEquals(ch % 2, 0); + } + } + + @Test + void givenEvenStrategy_whenRun_thenPrintEvenChars() { + setInput("7 5 even"); + run(); + removeFromOutput("Even letters - "); + List letters = new ArrayList<>(); + if (getOutputLines()[getOutputLines().length - 1].contains(",")) { + letters = Arrays.asList(getOutputLines()[getOutputLines().length - 1].split(", ")); + } else { + letters.add(getOutputLines()[getOutputLines().length - 1]); + } + for (String s : letters) { + char ch = s.charAt(0); + assertEquals(ch % 2, 0); + } + } + + @Test + void given1stNaN_whenRun_thenPrintNotIntegerMessage() { + setInput("word 1 even"); + run(); + assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); + } + + @Test + void given2ndNaN_whenRun_thenPrintNotIntegerMessage() { + setInput("1 word odd"); + run(); + assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); + } + + @Test + void givenWrongStrategy_whenRun_thenPrintNotIntegerMessage() { + setInput("1 3 5"); + run(); + assertEquals(ERROR_MESSAGE_RANDOM_CHARS_TABLE, getOutput()); + } +} 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..6665f714 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,112 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.ERROR_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.GREEN_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.INFO_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.RED_MESSAGE_TRAFFIC_LIGHT; +import static homework_2.utils.Homework2Constants.YELLOW_MESSAGE_TRAFFIC_LIGHT; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends UnitBase { + + void run() { + new TrafficLight().run(); + removeFromOutput(INFO_MESSAGE_TRAFFIC_LIGHT); + printOut(); + } + + void runExtraMode() { + new TrafficLightExtraMode().run(); + removeFromOutput(INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT); + printOut(); + } + + @Test + void givenSecondsRemainderFrom0To34_whenRun_thenPrintGreenLight() { + setInput("315"); + run(); + assertEquals(GREEN_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenSecondsRemainderFrom35To39Or55To59_whenRun_thenPrintYellowLight() { + setInput("37"); + run(); + assertEquals(YELLOW_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenSecondsRemainderFrom40To54_whenRun_thenPrintRedLight() { + setInput("174"); + run(); + assertEquals(RED_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenNaN_whenRun_thenPrintIncorrectFormatMessage() { + setInput("word"); + run(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenNegativeNumber_whenRun_thenPrintNegativeNumberMessage() { + setInput("-600"); + run(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenExceedLimitSeconds_whenRun_thenPrintExceedLimitMessage() { + setInput("87000"); + run(); + assertEquals(ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenExceedLimitTimeString_whenRun_thenPrintExceedLimitMessage() { + setInput("28:15:18"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenNegativeNumberTimeString_whenRun_thenPrintNegativeNumberMessage() { + setInput("-18:25:31"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenWrongFormatTimeString_whenRun_thenPrintIncorrectFormatMessage() { + setInput("29-17-16"); + runExtraMode(); + assertEquals(ERROR_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenTimeStringForGreen_whenRun_thenPrintGreenLight() { + setInput("13:24:12"); + runExtraMode(); + assertEquals(GREEN_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenTimeStringForYellow_whenRun_thenPrintYellowLight() { + setInput("18:37:39"); + runExtraMode(); + assertEquals(YELLOW_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } + + @Test + void givenTimeStringForRed_whenRun_thenPrintRedLight() { + setInput("08:13:52"); + runExtraMode(); + assertEquals(RED_MESSAGE_TRAFFIC_LIGHT, getOutput()); + } +} diff --git a/src/test/java/homework_2/utils/Homework2Constants.java b/src/test/java/homework_2/utils/Homework2Constants.java new file mode 100644 index 00000000..c77ed643 --- /dev/null +++ b/src/test/java/homework_2/utils/Homework2Constants.java @@ -0,0 +1,23 @@ +package homework_2.utils; + +public final class Homework2Constants { + public static final String ERROR_MESSAGE_TRAFFIC_LIGHT = "Only 1 non-negative integer is allowed as passed parameter"; + public static final String INFO_MESSAGE_TRAFFIC_LIGHT = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the default mode. To enter extra mode you should restart the program with argument 1.\n" + + "Please enter time in seconds. From 0 to 86399: "; + public static final String INFO_MESSAGE_TO_EXTRA_MODE_TRAFFIC_LIGHT = "Hi! This is your guide to cross the road blindly!\n" + + "You are in the extra mode. To enter the default mode you should restart the program with no arguments.\n" + + "Please enter time in format hh:mm:ss: "; + public static final String ERROR_MESSAGE_EXCEED_LIMIT_TRAFFIC_LIGHT = "The day is over"; + public static final String RED_MESSAGE_TRAFFIC_LIGHT = "RED"; + public static final String GREEN_MESSAGE_TRAFFIC_LIGHT = "GREEN"; + public static final String YELLOW_MESSAGE_TRAFFIC_LIGHT = "YELLOW"; + + public static final String INFO_MESSAGE_PYRAMID_PRINTER = "Please enter a positive integer for rows"; + public static final String ERROR_MESSAGE_PYRAMID_PRINTER = "Only 1 non-negative integer is allowed as passed parameter"; + + public static final String ERROR_MESSAGE_RANDOM_CHARS_TABLE = "Passed parameters should match the format [positive integer] [positive integer] [even|odd]"; + public static final String INFO_MESSAGE_RANDOM_CHARS_TABLE = "Enter parameters for columns, rows and strategy that match the format: [positive integer] [positive integer] [even|odd]\n"; + public static final int MAX_CHAR = 90; + public static final int MIN_CHAR = 65; +} \ No newline at end of file diff --git a/src/test/java/homework_3/ImmutableWorkerTest.java b/src/test/java/homework_3/ImmutableWorkerTest.java new file mode 100644 index 00000000..72b9aa30 --- /dev/null +++ b/src/test/java/homework_3/ImmutableWorkerTest.java @@ -0,0 +1,20 @@ +package homework_3; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertNotSame; + +public class ImmutableWorkerTest { + + @Test + void testIfImmutable() { + List testList = new ArrayList<>(); + Age age = new Age(13, 5, 1980); + ImmutableWorker worker = new ImmutableWorker("Jones", "Marketing", 874, testList, age); + ImmutableWorker anotherWorker = worker.updateWorker("null", "Sales", 0, null, null); + assertNotSame(worker, anotherWorker); + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/BookTest.java b/src/test/java/homework_4/custom_annotation/BookTest.java new file mode 100644 index 00000000..638cdd32 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/BookTest.java @@ -0,0 +1,41 @@ +package homework_4.custom_annotation; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class BookTest { + private static final String DEFAULT_AUTHOR = "Unknown author"; + + @Test + void givenNull_getDefault() { + Book book = new Book("Harry Potter", null); + assertEquals(DEFAULT_AUTHOR, book.getAuthor()); + } + + @Test + void givenEmptyString_getDefault() { + Book book = new Book("Lord Of The Rings", ""); + assertEquals(DEFAULT_AUTHOR, book.getAuthor()); + } + + @Test + void givenAuthor_getAuthor() { + Book book = new Book("Alice's Adventures In Wonderland", "Lewis Carroll"); + assertEquals("Lewis Carroll", book.getAuthor()); + } + + @Test + void givenName_getName(){ + Book book = new Book("The Adventures of Tom Sawyer", "Mark Twain"); + assertEquals("The Adventures of Tom Sawyer", book.getName()); + } + + @Test + void givenNameAndNullAuthor_getNameAndDefaultAuthor(){ + Book book = new Book("The Scarlet Letter", null); + assertEquals("The Scarlet Letter", book.getName()); + assertEquals(DEFAULT_AUTHOR, book.getAuthor()); + } + +} 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..df716ab9 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,51 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +public class CustomFileReaderTest extends UnitBase { + private static final String FILE_NAME = "src/main/resources/custom_file_reader/Shakespeare.txt"; + + @Test + void run1() { + new CustomFileReader().run1(); + assertFalse(getOutput().contains(".")); + assertFalse(getOutput().contains(",")); + try { + assertNotEquals(Files.readAllBytes(Paths.get(FILE_NAME)), getOutput().getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + void run2() { + new CustomFileReader().run2(); + assertFalse(getOutput().contains(".")); + assertFalse(getOutput().contains(",")); + try { + assertNotEquals(Files.readAllBytes(Paths.get(FILE_NAME)), getOutput().getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + void run3() { + new CustomFileReader().run3(); + assertFalse(getOutput().contains(".")); + assertFalse(getOutput().contains(",")); + try { + assertNotEquals(Files.readAllBytes(Paths.get(FILE_NAME)), getOutput().getBytes()); + } catch (IOException e) { + e.printStackTrace(); + } + } +} 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..be3de5b7 --- /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.assertSame; + +public class SingletonTest { + + @Test + void testGetInstance() { + Singleton singleton = Singleton.getInstance(); + Singleton anotherSingleton = Singleton.getInstance(); + assertSame(singleton, anotherSingleton); + } +} 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..14ccc6a1 --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,38 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CustomRegexMatcherTest extends UnitBase { + private final CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + + @ParameterizedTest + @MethodSource("testCases") + void test(final String[] input, final String expected) { + customRegexMatcher.run(input); + assertEquals(expected, getOutput()); + } + + static Stream testCases() { + return Stream.of( + Arguments.of(new String[]{}, "false"), + Arguments.of(new String[]{"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l"}, "true"), + Arguments.of(new String[]{"2021-02-09T18:18:24:424Z – [username9] - wanna scoop 182l", + "2021-02-09T18:18:23:081Z – [username10] - wanna top up 66l", + "2021-02-09T18:18:27:941Z – [username7] - wanna top up 148l"}, "true\ntrue\ntrue"), + Arguments.of(new String[]{"2021-02-09T18:18:30:557Z – [username7] - wanna top up 173l", + "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", + "2021-02-09T18:20:27:448Z – [username6] - wanna scoop 21l"}, "true\nfalse\ntrue"), + Arguments.of(new String[]{"2021-0209T18:18:30:557Z – [username7] - wanna top up 173l", + "202102-09T18:18:31:117Z – [username9] - wanna top up 96l", + "Just a string"}, "false\nfalse\nfalse") + ); + } + +} diff --git a/src/test/java/homework_5/math_power/PowerOfNumberTest.java b/src/test/java/homework_5/math_power/PowerOfNumberTest.java new file mode 100644 index 00000000..fa2b23dd --- /dev/null +++ b/src/test/java/homework_5/math_power/PowerOfNumberTest.java @@ -0,0 +1,50 @@ +package homework_5.math_power; + +import base.UnitBase; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static homework_5.math_power.utils.PowerOfNumberConstants.ERROR_MESSAGE; +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class PowerOfNumberTest extends UnitBase { + private final PowerOfNumber powerOfNumber = new PowerOfNumber(); + + @ParameterizedTest + @MethodSource("testCasesGetErrorMessage") + void testGetErrorMessage(final String[] input, final String expected) { + powerOfNumber.run(input); + assertEquals(expected, getOutput()); + } + + @ParameterizedTest + @MethodSource("testCasesGetSuccessResult") + void testGetSuccessResult(final String[] input, final String expected) { + powerOfNumber.run(input); + assertEquals(expected, getOutput()); + } + + static Stream testCasesGetErrorMessage() { + return Stream.of( + Arguments.of(new String[]{"2", "1", "4"}, ERROR_MESSAGE), + Arguments.of(new String[]{"2", "s"}, ERROR_MESSAGE), + Arguments.of(new String[]{"-2", "5"}, ERROR_MESSAGE), + Arguments.of(new String[]{"2.5", "5"}, ERROR_MESSAGE) + ); + } + + static Stream testCasesGetSuccessResult() { + return Stream.of( + Arguments.of(new String[]{"2", "2"}, "4"), + Arguments.of(new String[]{"2", "1"}, "2"), + Arguments.of(new String[]{"2", "0"}, "1"), + Arguments.of(new String[]{"0", "2"}, "0"), + Arguments.of(new String[]{"10", "18"}, String.valueOf((long) Math.pow(10, 18))), + Arguments.of(new String[]{"5", "0"}, String.valueOf((long) Math.pow(5, 0))) + ); + } + +} diff --git a/src/test/java/homework_5/math_power/utils/PowerOfNumberConstants.java b/src/test/java/homework_5/math_power/utils/PowerOfNumberConstants.java new file mode 100644 index 00000000..4e9e570c --- /dev/null +++ b/src/test/java/homework_5/math_power/utils/PowerOfNumberConstants.java @@ -0,0 +1,5 @@ +package homework_5.math_power.utils; + +public final class PowerOfNumberConstants { + public static final String ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; +}