diff --git a/README.md b/README.md index 5d686e9f..03483c77 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,33 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Khlebnikov Evgeniy* | 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 | [Console printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 - 1 | [Traffic Light](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_2/traffic_light) | The app that reads the time from the console (seconds) and displays the traffic light color (GREEN in green, YELLOW in yellow, RED in red) on the command line | +| HW2 - 1 Test | [Traffic Light Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_2/traffic_light) | Traffic Light Test | +| HW2 - 2 | [Pyramid Printer](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_2/pyramid_printer) | The app that reads the number once from the command line, and prints the pyramid of "x" according to the positive integer entered. Quits after first printing | +| HW2 - 2 Test | [Pyramid Printer Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_2/pyramid_printer) | Pyramid Printer Test | +| HW2 - 3 | [Random Chars Table](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_2/random_chars_table) | The app that reads length, width, strategy from the console generates the table and prints even/odd letters | +| HW2 - 3 Test | [Random Chars Table Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_2/random_chars_table) | Random Chars Table Test | +| HW3 | [ImmutableClass](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_3) | The Immutable Class An immutable class is created. Requirements for an immutable class have been added to a separate * .tht file in the homework_3 package.| +| HW4 - 1 | [ CustomFileReader](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_4/custom_file_reader) | CustomFileReader Class | +| HW4 - 1 Test | [ CustomFileReader Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_4/custom_file_reader) | CustomFileReader Class Test | +| HW4 - 2 | [Singleton](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_4/singleton) | Singleton Class. The Singleton class (thread-safe version) is created. Double checked locking was used in order to check whether the variable has already been initialized, if the another thread acquired the lock first, it may have already done the initialization. | +| HW4 - 2 Test | [Singleton Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_4/singleton) | Singleton Class Test. | +| HW4 - 3 | [Custom Annotation](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_4/custom_annotation) | Custom annotation. | +| HW4 - 3 Test| [Custom Annotation Test](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_4/custom_annotation) | Custom Annotation Test. | +| HW5 - 1| [CustomRegexMatcher](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_5/custom_regex_matcher) | CustomRegexMatcher. | +| HW5 - 1 Test| [CustomRegexMatcherTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_5/custom_regex_matcher) | CustomRegexMatcherTest. | +| HW5 - 2| [PowerOfNumber](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_5/power_of_number) | PowerOfNumber. | +| HW5 - 2| [PowerOfNumberTest](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/test/java/homework_5/power_of_number) | PowerOfNumber. | +| HW6| [MapProblemsGenerator](https://github.com/NikolaevArtem/Java_Core_June_2021/blob/feature/KhlebnikovEvgeniy/src/main/java/homework_6/map_problems_generator) | MapProblemsGenerator. | +| HW7| [KittenToCatFunction](https://github.com/NikolaevArtem/Java_Core_June_2021/tree/feature/KhlebnikovEvgeniy/src/main/java/homework_7) | KittenToCatFunction. | + + +| Title | Link | Short description +| --- | --- | --- | +| CodingBat | [CodingBat Code Practice](https://codingbat.com/done?user=khebnikove@gmail.com&tag=2964520102) | CodingBat khebnikove@gmail.com Done Page | [Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/gradlew b/gradlew index 4f906e0c..744e882e 100644 --- a/gradlew +++ b/gradlew @@ -72,7 +72,7 @@ case "`uname`" in Darwin* ) darwin=true ;; - MINGW* ) + MSYS* | MINGW* ) msys=true ;; NONSTOP* ) diff --git a/src/main/java/course_project/Main.java b/src/main/java/course_project/Main.java new file mode 100644 index 00000000..1543a875 --- /dev/null +++ b/src/main/java/course_project/Main.java @@ -0,0 +1,12 @@ +package course_project; + +import course_project.engine.BattleShipGame; + +public class Main { + + public static void main(String[] args) { + + new BattleShipGame(); + + } +} \ No newline at end of file diff --git a/src/main/java/course_project/engine/BattleShipGame.java b/src/main/java/course_project/engine/BattleShipGame.java new file mode 100644 index 00000000..a0409290 --- /dev/null +++ b/src/main/java/course_project/engine/BattleShipGame.java @@ -0,0 +1,10 @@ +package course_project.engine; + +public class BattleShipGame { + + public BattleShipGame() { + + Menu menu = new Menu(); + menu.chooseGameOptions(); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/engine/GameMap.java b/src/main/java/course_project/engine/GameMap.java new file mode 100644 index 00000000..93a233b2 --- /dev/null +++ b/src/main/java/course_project/engine/GameMap.java @@ -0,0 +1,434 @@ +package course_project.engine; + +import course_project.ships.*; + +import java.util.ArrayList; +import java.util.InputMismatchException; +import java.util.Random; +import java.util.Scanner; + +public class GameMap { + + private Scanner input = new Scanner(System.in); + private ArrayList ships = new ArrayList<>(); + + // Colours for background + public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m"; + public static final String YELLOW_BACKGROUND_BRIGHT = "\033[0;103m"; + public static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m"; + public static final String GREEN_BACKGROUND_BRIGHT = "\033[0;102m"; + public static final String PURPLE_BACKGROUND_BRIGHT = "\033[0;105m"; + public static final String CYAN_BACKGROUND_BRIGHT = "\033[0;106m"; + public static final String RED_BACKGROUND_BRIGHT = "\033[0;101m"; + + //Colours for text + public static final String ANSI_BLACK = "\u001B[30m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_BLUE = "\u001B[34m"; + public static final String WHITE_BOLD = "\033[1;37m"; + public static final String BLACK_BOLD = "\033[1;30m"; + + // Reset colour + public static final String ANSI_RESET = "\u001B[0m"; + + public GameMap() { + } + + public void printEmptyMap(String[][] map) { + + System.out.println(ANSI_BLUE_BACKGROUND + ANSI_BLACK + + " OCEAN MAP " + ANSI_RESET); + + for (int line = 1; line < map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + + for (int y = 1; y < map.length; y++) { + for (int x = 1; x < map.length; x++) { + map[x][y] = " "; + } + } + + System.out.println(); + for (int column = 1; column < map.length; column++) { + String square = ""; + for (int row = 1; row < map.length; row++) { + square += " [" + map[row][column] + "] "; + } + System.out.print(ANSI_BLUE + square + ANSI_RESET); + System.out.println(ANSI_RED + "|" + column + "Y" + "|" + ANSI_RESET); + } + + for (int line = 1; line < map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + + System.out.println(); + System.out.print(" "); + + for (int k = 1; k < map.length; k++) { + System.out.print(ANSI_RED + "" + k + "X" + " | " + ANSI_RESET); + } + + System.out.println("\n" + "\n" + + YELLOW_BACKGROUND_BRIGHT + WHITE_BOLD + "S: SUBMARINE (1) " + ANSI_RESET + " " + + BLACK_BACKGROUND_BRIGHT + WHITE_BOLD + "D: DESTROYER (1) " + ANSI_RESET + " " + + GREEN_BACKGROUND_BRIGHT + BLACK_BOLD + "C: CRUISER (1) " + ANSI_RESET + " " + + PURPLE_BACKGROUND_BRIGHT + WHITE_BOLD + "B: BATTLESHIP (1) " + ANSI_RESET + " " + + CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + "c: CARRIER (2) " + ANSI_RESET + ); + System.out.println("\n"); + } + + private void AIRandomCoordinatesToMap(String map[][], int size, ShipType shipType) { + + Random random = new Random(); + try { + int randomX = random.nextInt(10 - 1) + 1; + int randomY = random.nextInt(10 - 1) + 1; + + while (randomY < 1 || randomY > 8 && shipType.equals(ShipType.SUBMARINE)) { + randomY = random.nextInt(10 - 1) + 1; + } + + while (randomY < 1 || randomY > 9 && shipType.equals(ShipType.DESTROYER)) { + randomY = random.nextInt(10 - 1) + 1; + } + + while (randomY < 1 || randomY > 7 && shipType.equals(ShipType.CRUISER)) { + randomY = random.nextInt(10 - 1) + 1; + } + + while (randomY < 1 || randomY > 6 && shipType.equals(ShipType.BATTLESHIP)) { + randomY = random.nextInt(10 - 1) + 1; + } + + while (randomY < 1 || randomY > 8 && shipType.equals(ShipType.CARRIER1)) { + randomY = random.nextInt(10 - 1) + 1; + } + + while (randomY < 1 || randomY > 8 && shipType.equals(ShipType.CARRIER2)) { + randomY = random.nextInt(10 - 1) + 1; + } + + while (!map[randomX][randomY].equals(" ")) { + for (int i = 0; i < size; i++) { + for (int y = randomY; y <= randomY; y++) { + y += i; + for (int x = randomX; x <= randomX; x++) { + if (!map[randomX][randomY].equals(" ")) { + randomX = random.nextInt(10 - 1) + 1; + randomY = random.nextInt(10 - 1) + 1; + } else { + break; + } + } + } + } + } + + for (int i = 0; i < size; i++) { + for (int y = randomY; y <= randomY; y++) { + y += i; + for (int x = randomX; x <= randomX; x++) { + + switch (shipType) { + case SUBMARINE: + map[x][y] = YELLOW_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.SUBMARINE.getShipType() + ANSI_RESET + ANSI_BLUE; + Submarine submarine = new Submarine(x, y); + ships.add(submarine); + break; + case DESTROYER: + map[x][y] = BLACK_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.DESTROYER.getShipType() + ANSI_RESET + ANSI_BLUE; + Destroyer destroyer = new Destroyer(x, y); + ships.add(destroyer); + break; + case CRUISER: + map[x][y] = GREEN_BACKGROUND_BRIGHT + BLACK_BOLD + ShipType.CRUISER.getShipType() + ANSI_RESET + ANSI_BLUE; + Cruiser cruiser = new Cruiser(x, y); + ships.add(cruiser); + break; + case BATTLESHIP: + map[x][y] = PURPLE_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.BATTLESHIP.getShipType() + ANSI_RESET + ANSI_BLUE; + BattleShip battleShip = new BattleShip(x, y); + ships.add(battleShip); + break; + case CARRIER1: + map[x][y] = CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.CARRIER1.getShipType() + ANSI_RESET + ANSI_BLUE; + Carrier carrier1 = new Carrier(x, y); + ships.add(carrier1); + break; + case CARRIER2: + map[x][y] = CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.CARRIER2.getShipType() + ANSI_RESET + ANSI_BLUE; + Carrier carrier2 = new Carrier(x, y); + ships.add(carrier2); + break; + default: + System.out.println("Incorrect"); + break; + } + } + } + } + + } + catch(Exception e){ + System.out.println("Something went wrong. "); + } + } + + private void addCoordinateToMap(String map[][], int size, ShipType shipType) { + + try { + System.out.println("Add X-coordinate for your " + shipType + " with size " + size); + int xInput = input.nextInt(); + + System.out.println("Add Y-coordinate for your " + shipType + " with size " + size); + int yInput = input.nextInt(); + + while (xInput < 1 || xInput > 10) { + System.out.println("Please Enter Valid X- Coordinate"); + xInput = input.nextInt(); + } + + while (yInput < 1 || yInput > 8 && shipType.equals(ShipType.SUBMARINE)) { + System.out.println("Please Enter Valid Y-Coordinate"); + yInput = input.nextInt(); + } + + while (yInput < 1 || yInput > 9 && shipType.equals(ShipType.DESTROYER)) { + System.out.println("Please Enter Valid Y-Coordinate"); + yInput = input.nextInt(); + } + + while (yInput < 1 || yInput > 7 && shipType.equals(ShipType.CRUISER)) { + System.out.println("Please Enter Valid Y-Coordinate"); + yInput = input.nextInt(); + } + + while (yInput < 1 || yInput > 6 && shipType.equals(ShipType.BATTLESHIP)) { + System.out.println("Please Enter Valid Y-Coordinate"); + yInput = input.nextInt(); + } + + while (yInput < 1 || yInput > 8 && shipType.equals(ShipType.CARRIER1)) { + System.out.println("Please Enter Valid Y-Coordinate"); + yInput = input.nextInt(); + } + + while (yInput < 1 || yInput > 8 && shipType.equals(ShipType.CARRIER2)) { + System.out.println("Please Enter Valid Y-Coordinate"); + yInput = input.nextInt(); + } + + while (!map[xInput][yInput].equals(" ")) { + for (int i = 0; i < size; i++){ + for (int y = yInput; y <= yInput; y++) { + y += i; + for (int x = xInput; x <= xInput; x++) { + if (map[x][y] != " ") { + System.out.println("You can't place a boat on another boat!"); + System.out.println("Add X-coordinate for your " + shipType + " with size " + size); + xInput = input.nextInt(); + + System.out.println("Add Y-coordinate for your " + shipType + " with size " + size); + yInput = input.nextInt(); + } else { + break; + } + } + } + } + } + + for (int i = 0; i < size; i++) { + for (int y = yInput; y <= yInput; y++) { + y += i; + for (int x = xInput; x <= xInput; x++) { + + switch (shipType) { + case SUBMARINE: + map[x][y] = YELLOW_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.SUBMARINE.getShipType() + ANSI_RESET + ANSI_BLUE; + Submarine submarinePlayer = new Submarine(x, y); + ships.add(submarinePlayer); + if(i==1){ + System.out.println(submarinePlayer.toString()); + } + break; + case DESTROYER: + map[x][y] = BLACK_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.DESTROYER.getShipType() + ANSI_RESET + ANSI_BLUE; + Destroyer destroyerPlayer = new Destroyer(x, y); + ships.add(destroyerPlayer); + if(i==1){ + System.out.println(destroyerPlayer.toString()); + } + break; + case CRUISER: + map[x][y] = GREEN_BACKGROUND_BRIGHT + BLACK_BOLD + ShipType.CRUISER.getShipType() + ANSI_RESET + ANSI_BLUE; + Cruiser cruiserPlayer = new Cruiser(x, y); + ships.add(cruiserPlayer); + if(i==1){ + System.out.println(cruiserPlayer.toString()); + } + break; + case BATTLESHIP: + map[x][y] = PURPLE_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.BATTLESHIP.getShipType() + ANSI_RESET + ANSI_BLUE; + BattleShip battleShipPlayer = new BattleShip(x, y); + ships.add(battleShipPlayer); + if(i==1){ + System.out.println(battleShipPlayer.toString()); + } + break; + case CARRIER1: + map[x][y] = CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.CARRIER1.getShipType() + ANSI_RESET + ANSI_BLUE; + Carrier carrier1Player = new Carrier(x, y); + ships.add(carrier1Player); + if(i==1){ + System.out.println(carrier1Player.toString()); + } + break; + case CARRIER2: + map[x][y] = CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + ShipType.CARRIER2.getShipType() + ANSI_RESET + ANSI_BLUE; + Carrier carrier2Player = new Carrier(x, y); + ships.add(carrier2Player); + if(i==1){ + System.out.println(carrier2Player.toString()); + } + break; + default: + System.out.println("Incorrect"); + break; + } + } + } + } + } catch (InputMismatchException e) { + e.getMessage(); + } + } + + + public void printPlayerMapShips (String[][] map, int size, ShipType shipType){ + + addCoordinateToMap(map, size, shipType); + System.out.println(ANSI_BLUE_BACKGROUND + ANSI_BLACK + + " OCEAN MAP " + ANSI_RESET); + + for (int line = 1; line <= map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + + System.out.println(); + + for (int column = 1; column < map.length; column++) { + String square = ""; + for (int row = 1; row < map.length; row++) { + square += " [" + map[row][column] + "] "; + } + + System.out.print(ANSI_BLUE + square + ANSI_RESET); + System.out.println(ANSI_RED + "|" + column + "Y" + "|" + ANSI_RESET); + } + + for (int line = 1; line <= map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + + System.out.println(); + System.out.print(" "); + + for (int k = 1; k < map.length; k++) { + System.out.print(ANSI_RED + "" + k + "X" + " | " + ANSI_RESET); + } + + System.out.println("\n" + "\n" + + YELLOW_BACKGROUND_BRIGHT + WHITE_BOLD + "S: SUBMARINE (1) " + ANSI_RESET + " " + + BLACK_BACKGROUND_BRIGHT + WHITE_BOLD + "D: DESTROYER (1) " + ANSI_RESET + " " + + GREEN_BACKGROUND_BRIGHT + BLACK_BOLD + "C: CRUISER (1) " + ANSI_RESET + " " + + PURPLE_BACKGROUND_BRIGHT + WHITE_BOLD + "B: BATTLESHIP (1) " + ANSI_RESET + " " + + CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + "c: CARRIER (2) " + ANSI_RESET + ); + + System.out.println("\n"); + } + + public void printAIMapShips (String map[][],int size, ShipType shipType){ + + AIRandomCoordinatesToMap(map, size, shipType); + + System.out.println(ANSI_BLUE_BACKGROUND + ANSI_BLACK + + " OCEAN MAP " + ANSI_RESET); + + for (int line = 1; line <= map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + + System.out.println(); + for (int column = 1; column < map.length; column++) { + String square = ""; + for (int row = 1; row < map.length; row++) { + square += " [" + map[row][column] + "] "; + } + + System.out.print(ANSI_BLUE + square + ANSI_RESET); + System.out.println(ANSI_RED + "|" + column + "Y" + "|" + ANSI_RESET); + } + + for (int line = 1; line <= map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + + System.out.println(); + System.out.print(" "); + + for (int k = 1; k < map.length; k++) { + System.out.print(ANSI_RED + "" + k + "X" + " | " + ANSI_RESET); + } + + System.out.println("\n" + "\n" + + YELLOW_BACKGROUND_BRIGHT + WHITE_BOLD + "S: SUBMARINE (1) " + ANSI_RESET + " " + + BLACK_BACKGROUND_BRIGHT + WHITE_BOLD + "D: DESTROYER (1) " + ANSI_RESET + " " + + GREEN_BACKGROUND_BRIGHT + BLACK_BOLD + "C: CRUISER (1) " + ANSI_RESET + " " + + PURPLE_BACKGROUND_BRIGHT + WHITE_BOLD + "B: BATTLESHIP (1) " + ANSI_RESET + " " + + CYAN_BACKGROUND_BRIGHT + WHITE_BOLD + "c: CARRIER (2) " + ANSI_RESET + ); + System.out.println("\n"); + } + + public void printBattle (String[][] map, int x, int y, String battle){ + + System.out.println(ANSI_BLUE_BACKGROUND + ANSI_BLACK + + " OCEAN MAP " + ANSI_RESET); + + for (int line = 1; line <= map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + System.out.println(); + + for (int column = 1; column < map.length; column++) { + String square = ""; + for (int row = 1; row < map.length; row++) { + square += " [" + map[row][column] + "] "; + } + System.out.print(ANSI_BLUE + square + ANSI_RESET); + System.out.println(ANSI_RED + "|" + column + "Y" + "|" + ANSI_RESET); + } + + for (int line = 1; line <= map.length; line++) { + System.out.print(ANSI_BLUE + "_____" + ANSI_RESET); + } + System.out.println(); + System.out.print(" "); + + for (int k = 1; k < map.length; k++) { + System.out.print(ANSI_RED + "" + k + "X" + " | " + ANSI_RESET); + } + + System.out.println("\n" + "\n" + + RED_BACKGROUND_BRIGHT + WHITE_BOLD + "HIT (*) " + ANSI_RESET + " " + + BLACK_BACKGROUND_BRIGHT + WHITE_BOLD + "MISS (X) " + ANSI_RESET + " " + ); + System.out.println("\n"); + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/engine/Menu.java b/src/main/java/course_project/engine/Menu.java new file mode 100644 index 00000000..4b15bf2e --- /dev/null +++ b/src/main/java/course_project/engine/Menu.java @@ -0,0 +1,105 @@ +package course_project.engine; + +import course_project.engine.BattleShipGame; +import course_project.players.ComputerPlayer; +import course_project.players.HumanPlayer; +import course_project.utils.FontColors; +import lombok.Data; + +import java.util.InputMismatchException; +import java.util.Scanner; + +@Data +public class Menu { + + private String[][] playerOneMap = new String[11][11]; + private String[][] playerTwoMap = new String[11][11]; + private String[][] computerMap = new String[11][11]; + private Scanner input = new Scanner(System.in); + private boolean gameStillRunning; + + public boolean isGameStillRunning() { + return gameStillRunning; + } + + public void chooseGameOptions() { + + try { + do { + FontColors logo = new FontColors(); + logo.menuLogo(); + + System.out.println("Welcome to Sea Battle! Please select mode using key 1, 2 or 3. Press "); + System.out.println("1. Player VS Player (PvP)"); + System.out.println("2. Player VS Computer (PvE)"); + System.out.println("3. Quit"); + int userChoice = input.nextInt(); + + + Scanner inputFromUser = new Scanner(System.in); + + switch (userChoice) { + case 1: + System.out.println("You have chosen 'Player VS Player' (PvP)" + "\n"); + + //Welcoming players and let them enter their name + System.out.println("Player 1, please type in your name"); + String playerOneName = inputFromUser.nextLine(); + HumanPlayer player1 = new HumanPlayer(playerOneName); // playerOneName is the input from user. + System.out.println("Welcome," + " " + player1.getName() + "!" + "\n"); + + System.out.println("Player 2, please type in your name"); + String playerTwoName = inputFromUser.nextLine(); + HumanPlayer player2 = new HumanPlayer(playerTwoName); + System.out.println("Welcome," + " " + player2.getName() + "!" + "\n"); + + + // Let player 1 and player 2 place their ships + System.out.println(player1.getName() + "," + " " + "please place your ships (6) as shown below"); + player1.placeShips(playerOneMap, player1.getName()); + + System.out.println(player2.getName() + "," + " " + "please place your ships (6) as shown below"); + player2.placeShips(playerTwoMap, player2.getName()); + + + // Let player ONE shoot first, then let each player take turn on shooting. + player1.shoot(playerOneMap, playerTwoMap, player1.getName(), player2.getName()); + + break; + + case 2: + System.out.println("You have chosen 'Player VS Computer' (PvE)" + "\n \n" + "Please enter your name:"); + + String humanName = inputFromUser.nextLine(); + HumanPlayer humanPlayer = new HumanPlayer(humanName); + System.out.println("Welcome," + " " + humanPlayer.getName() + "!"); + + // Name of Computer will include automatically via Computer-Class + ComputerPlayer computerPlayer = new ComputerPlayer(); + System.out.println("You'll be playing against the" + " " + computerPlayer.getName() + "\n"); + + System.out.println(humanPlayer.getName() + "," + " " + "please place your ships (6) as shown below"); + humanPlayer.placeShips(playerOneMap, humanPlayer.getName()); + + computerPlayer.AIDeployShips(computerMap); + + computerPlayer.shootAI(computerMap, playerOneMap, humanPlayer.getName(), computerPlayer.getName()); + + break; + + + case 3: + System.out.println("You will now Quit Sea Wars"); + System.exit(0); // Shuts down program + default: + throw new IllegalStateException("Unexpected value: " + userChoice); + } + + } while (gameStillRunning = true); + } catch (InputMismatchException e) { + e.getMessage(); + System.out.println("Invalid choice. Please select 1, 2 or 3."); + BattleShipGame bA = new BattleShipGame(); + } + } +} \ No newline at end of file diff --git a/src/main/java/course_project/engine/Position.java b/src/main/java/course_project/engine/Position.java new file mode 100644 index 00000000..9557b6c5 --- /dev/null +++ b/src/main/java/course_project/engine/Position.java @@ -0,0 +1,19 @@ +package course_project.engine; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class Position { + + private int x; + private int y; + + public String toString() { + return "Position{" + + "x=" + x + + ", y=" + y + + '}'; + } +} diff --git a/src/main/java/course_project/engine/SquareState.java b/src/main/java/course_project/engine/SquareState.java new file mode 100644 index 00000000..d470f060 --- /dev/null +++ b/src/main/java/course_project/engine/SquareState.java @@ -0,0 +1,20 @@ +package course_project.engine; + +import lombok.Getter; + +import static course_project_1.utils.ConsoleColors.*; + +@Getter +public enum SquareState { + + NONE(CYAN_BACKGROUND + " " + RESET), + MISS(YELLOW + "º" + RESET), + HIT(RED_BOLD + "•" + RESET); + + private String squareSymbol; + + SquareState (String squareSymbol) { + this.squareSymbol = squareSymbol; + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/players/ComputerPlayer.java b/src/main/java/course_project/players/ComputerPlayer.java new file mode 100644 index 00000000..636a116c --- /dev/null +++ b/src/main/java/course_project/players/ComputerPlayer.java @@ -0,0 +1,194 @@ +package course_project.players; + +import course_project.engine.GameMap; +import course_project.ships.ShipSize; +import course_project.ships.ShipType; +import course_project.engine.SquareState; + +import java.util.Random; +import java.util.Scanner; + +public class ComputerPlayer extends Player { + + private static final String RED_BACKGROUND_BRIGHT = "\033[0;101m"; + private static final String ANSI_BLUE = "\u001B[34m"; + private static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m"; + private static final String ANSI_WHITE_BACKGROUND = "\u001B[47m"; + + private static final String ANSI_RESET = "\u001B[0m"; + + private GameMap gameMap = new GameMap(); + + private String[][] battleMap1 = new String[11][11]; + private String[][] battleMapAI = new String[11][11]; + private String[][] emptyMap = new String[11][11]; + + private Scanner input = new Scanner(System.in); + + public ComputerPlayer() { + super("Computer"); + } + + public void shootAI(String[][] playerOneMap, String[][] computerMap, String player1, String AI) { + + System.out.println(player1 + " , let's get started! "); + gameMap.printEmptyMap(emptyMap); + + String hitBarPlayer1 = ""; + String hitBarAI = ""; + String winBar = "********************"; + + int hitsPlayer1 = 0; + int hitsAI = 0; + + Random random = new Random(); + + int countPlayer = 0; + int countAI = 0; + + for (int y = 1; y < battleMap1.length; y++) { + for (int x = 1; x < battleMap1.length; x++) { + battleMap1[x][y] = SquareState.NONE.getSquareSymbol(); + } + } + + for (int y = 1; y < battleMapAI.length; y++) { + for (int x = 1; x < battleMapAI.length; x++) { + battleMapAI[x][y] = SquareState.NONE.getSquareSymbol(); + } + } + + do { + String ships[] = {"S", "D", "C", "B", "c"}; + + System.out.println("Your turn to shoot, " + player1 + "!"); + System.out.println("Enter X-coordinate: "); + int xShoot = input.nextInt(); + System.out.println("Enter Y-coordinate: "); + int yShoot = input.nextInt(); + + while (xShoot < 1 || xShoot > 10 || yShoot < 1 || yShoot > 10) { + System.out.println("Incorrect choice! "); + System.out.println("Enter X-coordinate: "); + xShoot = input.nextInt(); + System.out.println("Enter Y-coordinate: "); + yShoot = input.nextInt(); + } + + for (int i = 0; i < ships.length; i++) { + + if (computerMap[xShoot][yShoot].contains(ships[i])) { + + if (battleMapAI[xShoot][yShoot].contains(SquareState.HIT.getSquareSymbol())) { + System.out.println("You've already hit this cell. " + "\n"); + } else { + System.out.println("HIT! " + "\n"); + + battleMapAI[xShoot][yShoot] = RED_BACKGROUND_BRIGHT + SquareState.HIT.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + hitBarPlayer1 += SquareState.HIT.getSquareSymbol(); + hitsPlayer1++; + } + } + } + + if (computerMap[xShoot][yShoot].contains(SquareState.NONE.getSquareSymbol())) { + System.out.println("MISS!"); + battleMapAI[xShoot][yShoot] = BLACK_BACKGROUND_BRIGHT + SquareState.MISS.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + } + + System.out.println("MAP OF PLAYER " + AI); + gameMap.printBattle(battleMapAI, xShoot, yShoot, "battle"); + if (hitsPlayer1 == 20) { + System.out.println(player1 + " WINS! GAME OVER FOR: " + AI); + break; + } + + int xShootAI = random.nextInt(10 - 1) + 1; + int yShootAI = random.nextInt(10 - 1) + 1; + + for (int i = 0; i < ships.length; i++) { + if (playerOneMap[xShootAI][yShootAI].contains(ships[i])) { + if (battleMap1[xShoot][yShoot].contains(SquareState.HIT.getSquareSymbol())) { + System.out.println("You've already hit this cell. " + "\n"); + } else { + System.out.println("HIT! " + "\n"); + battleMap1[xShoot][yShoot] = RED_BACKGROUND_BRIGHT + SquareState.HIT.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + hitBarPlayer1 += SquareState.HIT.getSquareSymbol(); + hitsAI++; + } + } + } + + if (playerOneMap[xShootAI][yShootAI].contains(SquareState.NONE.getSquareSymbol())) { + System.out.println("MISS!"); + battleMap1[xShootAI][yShootAI] = BLACK_BACKGROUND_BRIGHT + SquareState.MISS.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + } + + System.out.println("MAP OF PLAYER " + player1); + gameMap.printBattle(battleMap1, xShootAI, yShootAI, "battle"); + + if (hitsAI == 20) { + System.out.println(AI + " WINS! GAME OVER FOR: " + player1); + break; + } + + System.out.println("Number of hits for " + player1 + " is: " + hitsPlayer1); + System.out.println(ANSI_WHITE_BACKGROUND + winBar + ANSI_RESET); + System.out.println(RED_BACKGROUND_BRIGHT + hitBarPlayer1 + ANSI_RESET); + System.out.println("Number of hits for " + AI + " is: " + hitsAI); + System.out.println(ANSI_WHITE_BACKGROUND + winBar + ANSI_RESET); + System.out.println(RED_BACKGROUND_BRIGHT + hitBarAI + ANSI_RESET); + + } + while (true); + } + + public void AIDeployShips(String playerMap[][]) { + + int submarineSize = ShipSize.SUBMARINE.getSize(); + int destroyerSize = ShipSize.DESTROYER.getSize(); + int cruiserSize = ShipSize.CRUISER.getSize(); + int battleshipSize = ShipSize.BATTLESHIP.getSize(); + int carrier1Size = ShipSize.CARRIER1.getSize(); + int carrier2Size = ShipSize.CARRIER2.getSize(); + + ShipType submarine = ShipType.SUBMARINE; + ShipType destroyer = ShipType.DESTROYER; + ShipType cruiser = ShipType.CRUISER; + ShipType battleship = ShipType.BATTLESHIP; + ShipType carrier1 = ShipType.CARRIER1; + ShipType carrier2 = ShipType.CARRIER2; + + ShipType[] shipNames = {submarine, destroyer, cruiser, battleship, carrier1, carrier2}; + gameMap.printEmptyMap(playerMap); + + for (int i = 0; i < shipNames.length; i++) { + int[] coordinates; + + switch (shipNames[i]) { + case SUBMARINE: + gameMap.printAIMapShips(playerMap, submarineSize, submarine); + break; + case DESTROYER: + gameMap.printAIMapShips(playerMap, destroyerSize, destroyer); + break; + case CRUISER: + gameMap.printAIMapShips(playerMap, cruiserSize, cruiser); + break; + case BATTLESHIP: + gameMap.printAIMapShips(playerMap, battleshipSize, battleship); + break; + case CARRIER1: + gameMap.printAIMapShips(playerMap, carrier1Size, carrier1); + break; + case CARRIER2: + gameMap.printAIMapShips(playerMap, carrier2Size, carrier2); + break; + default: + System.out.println("Incorrect"); + break; + } + } + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/players/HumanPlayer.java b/src/main/java/course_project/players/HumanPlayer.java new file mode 100644 index 00000000..5fdee482 --- /dev/null +++ b/src/main/java/course_project/players/HumanPlayer.java @@ -0,0 +1,247 @@ +package course_project.players; + +import course_project.engine.GameMap; +import course_project.engine.SquareState; +import course_project.ships.ShipSize; +import course_project.ships.ShipType; + +import java.util.Scanner; + +public class HumanPlayer extends Player { + + private static final String RED_BACKGROUND_BRIGHT = "\033[0;101m"; + private static final String ANSI_WHITE_BACKGROUND = "\u001B[47m"; + private static final String BLACK_BACKGROUND_BRIGHT = "\033[0;100m"; + private static final String ANSI_BLUE = "\u001B[34m"; + private static final String ANSI_RESET = "\u001B[0m"; + private Scanner input = new Scanner(System.in); + private GameMap gameMap = new GameMap(); + private String[][] battleMap1 = new String[11][11]; + private String[][] battleMap2 = new String[11][11]; + private String[][] emptyMap = new String[11][11]; + + public HumanPlayer(String name) { + super(name); + } + + public void shoot(String[][] playerOneMap, String[][] playerTwoMap, String player1, String player2){ + + System.out.println(player1 + " get ready to battle! "); + gameMap.printEmptyMap(emptyMap); + String hitBarPlayer1 = ""; + String hitBarPlayer2 = ""; + String winBar = "********************"; + + int hitsPlayer1 = 0; + int hitsPlayer2 = 0; + + int countPlayer1 = 0; + int countPlayer2 = 0; + + for (int y = 1; y < battleMap2.length; y++) { + for (int x = 1; x < battleMap2.length; x++) { + battleMap2[x][y] = SquareState.NONE.getSquareSymbol(); + } + } + + for (int y = 1; y < battleMap1.length; y++) { + for (int x = 1; x < battleMap1.length; x++) { + battleMap1[x][y] = SquareState.NONE.getSquareSymbol(); + } + } + + do { + String[] ships = {"S", "D", "C", "B", "c"}; + System.out.println("Your turn to shoot, " + player1 + "!"); + System.out.println("Shoot! Enter X-coordinate: "); + int xShoot = input.nextInt(); + System.out.println("Shoot! Enter Y-coordinate: "); + int yShoot = input.nextInt(); + + while(xShoot <1 || xShoot>10 || yShoot<1 || yShoot>10){ + System.out.println("Invalid choice! "); + System.out.println("Shoot! Enter X-coordinate: "); + xShoot = input.nextInt(); + System.out.println("Shoot! Enter Y-coordinate: "); + yShoot = input.nextInt(); + } + + for (int i = 0; i < ships.length; i++) { + if (playerTwoMap[xShoot][yShoot].contains(ships[i])) { + if(battleMap2[xShoot][yShoot].contains(SquareState.HIT.getSquareSymbol())){ + System.out.println("You have hit this cell. " + "\n"); + } + else{ + System.out.println("HIT! " + "\n"); + countPlayer1++; + if(countPlayer1 == ShipSize.SUBMARINE.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.SUBMARINE.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.SUBMARINE + "!"); + countPlayer1 = 0; + } + if(countPlayer1 == ShipSize.DESTROYER.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.DESTROYER.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.DESTROYER + "!"); + countPlayer1 = 0; + } + if(countPlayer1 == ShipSize.CRUISER.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.CRUISER.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.CRUISER + "!"); + countPlayer1 = 0; + } + if(countPlayer1 == ShipSize.BATTLESHIP.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.BATTLESHIP.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.BATTLESHIP + "!"); + countPlayer1 = 0; + } + if(countPlayer1 == ShipSize.CARRIER1.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.CARRIER1.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.CARRIER1 + "!"); + countPlayer1 = 0; + } + if(countPlayer1 == ShipSize.CARRIER2.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.CARRIER2.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.CARRIER2 + "!"); + countPlayer1 = 0; + } + + battleMap2[xShoot][yShoot] = RED_BACKGROUND_BRIGHT + SquareState.HIT.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + hitBarPlayer1 += SquareState.HIT.getSquareSymbol(); + hitsPlayer1++; + } + } + } + + if(playerTwoMap[xShoot][yShoot].contains(SquareState.NONE.getSquareSymbol())) { + System.out.println("MISS! " + "\n"); + battleMap2[xShoot][yShoot] = BLACK_BACKGROUND_BRIGHT + SquareState.MISS.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + } + + System.out.println("MAP OF PLAYER " + player2); + gameMap.printBattle(battleMap2, xShoot, yShoot, "battle"); + if (hitsPlayer1 == 20) { + System.out.println(player1 + " WINS! GAME OVER FOR: " + player2); + break; + } + + System.out.println("Your turn to shoot, " + player2 + "!"); + System.out.println("Shoot! Enter X-coordinate: "); + xShoot = input.nextInt(); + System.out.println("Shoot! Enter Y-coordinate: "); + yShoot = input.nextInt(); + + while(xShoot <1 || xShoot>10 || yShoot<1 || yShoot>10){ + System.out.println("Incorrect choice"); + System.out.println("Shoot! Enter X-coordinate: "); + xShoot = input.nextInt(); + System.out.println("Shoot! Enter Y-coordinate: "); + yShoot = input.nextInt(); + } + + for (int i = 0; i < ships.length; i++) { + if (playerOneMap[xShoot][yShoot].contains(ships[i])) { + + if(battleMap1[xShoot][yShoot].contains(SquareState.HIT.getSquareSymbol())){ + System.out.println("You have hit this cell. " + "\n"); + } + else{ + System.out.println("HIT! " + "\n"); + countPlayer2++; + if(countPlayer2 == ShipSize.SUBMARINE.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.SUBMARINE.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.SUBMARINE + "!"); + countPlayer2 = 0; + } + if(countPlayer2 == ShipSize.DESTROYER.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.DESTROYER.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.DESTROYER + "!"); + countPlayer2 = 0; + } + if(countPlayer2 == ShipSize.CRUISER.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.CRUISER.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.CRUISER + "!"); + countPlayer2 = 0; + } + if(countPlayer2 == ShipSize.BATTLESHIP.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.BATTLESHIP.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.BATTLESHIP + "!"); + countPlayer2 = 0; + } + if(countPlayer2 == ShipSize.CARRIER1.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.CARRIER1.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.CARRIER1 + "!"); + countPlayer2 = 0; + } + if(countPlayer2 == ShipSize.CARRIER2.getSize() && playerOneMap[xShoot][yShoot].contains(ShipType.CARRIER2.getShipType())){ + System.out.println("YOU SUNK THE " + ShipType.CARRIER2 + "!"); + countPlayer2 = 0; + } + + battleMap1[xShoot][yShoot] = RED_BACKGROUND_BRIGHT + SquareState.HIT.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + hitBarPlayer2 += SquareState.HIT.getSquareSymbol(); + hitsPlayer2++; + } + } + } + + if(playerOneMap[xShoot][yShoot].contains(SquareState.NONE.getSquareSymbol())) { + System.out.println("MISS! " + "\n"); + battleMap1[xShoot][yShoot] = BLACK_BACKGROUND_BRIGHT + SquareState.MISS.getSquareSymbol() + ANSI_RESET + ANSI_BLUE; + } + + System.out.println("MAP OF PLAYER " + player1); + gameMap.printBattle(battleMap1, xShoot, yShoot, "battle"); + + if (hitsPlayer2 == 20) { + System.out.println(player2 + " WINS! GAME OVER FOR: " + player1); + break; + } + + System.out.println("Number of hits for " + player1 + " is: " + hitsPlayer1); + System.out.println(ANSI_WHITE_BACKGROUND + winBar + ANSI_RESET); + System.out.println(RED_BACKGROUND_BRIGHT + hitBarPlayer1 + ANSI_RESET); + System.out.println("Number of hits for " + player2 + " is: " + hitsPlayer2); + System.out.println(ANSI_WHITE_BACKGROUND + winBar + ANSI_RESET); + System.out.println(RED_BACKGROUND_BRIGHT + hitBarPlayer2 + ANSI_RESET); + + }while(true); + } + + + public void placeShips(String[][] playerMap, String playerName) { + int submarineSize = 3; + int destroyerSize = 2; + int cruiserSize = 4; + int battleshipSize = 5; + int carrier1Size = 3; + int carrier2Size = 3; + + ShipType submarine = ShipType.SUBMARINE; + ShipType destroyer = ShipType.DESTROYER; + ShipType cruiser = ShipType.CRUISER; + ShipType battleship = ShipType.BATTLESHIP; + ShipType carrier1 = ShipType.CARRIER1; + ShipType carrier2 = ShipType.CARRIER2; + + ShipType[] shipNames = {submarine, destroyer, cruiser, battleship, carrier1, carrier2}; + + gameMap.printEmptyMap(playerMap); + + for (int i = 0; i < shipNames.length; i++) { + int[] coordinates; + + switch (shipNames[i]) { + case SUBMARINE: + gameMap.printPlayerMapShips(playerMap, submarineSize, submarine); + break; + case DESTROYER: + gameMap.printPlayerMapShips(playerMap, destroyerSize, destroyer); + break; + case CRUISER: + gameMap.printPlayerMapShips(playerMap, cruiserSize, cruiser); + break; + case BATTLESHIP: + gameMap.printPlayerMapShips(playerMap, battleshipSize, battleship); + break; + case CARRIER1: + gameMap.printPlayerMapShips(playerMap, carrier1Size, carrier1); + break; + case CARRIER2: + gameMap.printPlayerMapShips(playerMap, carrier2Size, carrier2); + break; + default: + System.out.println("Incorrect"); + break; + } + } + } +} diff --git a/src/main/java/course_project/players/Player.java b/src/main/java/course_project/players/Player.java new file mode 100644 index 00000000..0f18d816 --- /dev/null +++ b/src/main/java/course_project/players/Player.java @@ -0,0 +1,22 @@ +package course_project.players; + +import course_project.engine.GameMap; + +public abstract class Player { + + private String name; + public GameMap playerGameMap; + + + public Player(String name){ + this.name = name; + playerGameMap = new GameMap(); + } + public void shoot(String[][] playerOneMap, String[][] computerMap, String name){ + + } + public String getName(){ + return this.name; + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/BattleShip.java b/src/main/java/course_project/ships/BattleShip.java new file mode 100644 index 00000000..63b73cc6 --- /dev/null +++ b/src/main/java/course_project/ships/BattleShip.java @@ -0,0 +1,8 @@ +package course_project.ships; + +public class BattleShip extends Ship { + + public BattleShip(int posX, int posY) { + super("Battleship", 5, posX, posY); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Carrier.java b/src/main/java/course_project/ships/Carrier.java new file mode 100644 index 00000000..eef60b76 --- /dev/null +++ b/src/main/java/course_project/ships/Carrier.java @@ -0,0 +1,8 @@ +package course_project.ships; + +public class Carrier extends Ship { + + public Carrier(int posX, int posY){ + super("Carrier", 3, posX, posY); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Cruiser.java b/src/main/java/course_project/ships/Cruiser.java new file mode 100644 index 00000000..5758c0c0 --- /dev/null +++ b/src/main/java/course_project/ships/Cruiser.java @@ -0,0 +1,8 @@ +package course_project.ships; + +public class Cruiser extends Ship { + public Cruiser(int posX, int posY){ + super("Cruiser", 4, posX, posY); + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Destroyer.java b/src/main/java/course_project/ships/Destroyer.java new file mode 100644 index 00000000..cbbabc9b --- /dev/null +++ b/src/main/java/course_project/ships/Destroyer.java @@ -0,0 +1,9 @@ +package course_project.ships; + +public class Destroyer extends Ship { + public Destroyer(int posX, int posY) { + super("Destroyer", 2, posX, posY); + + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Ship.java b/src/main/java/course_project/ships/Ship.java new file mode 100644 index 00000000..13b67a1b --- /dev/null +++ b/src/main/java/course_project/ships/Ship.java @@ -0,0 +1,44 @@ +package course_project.ships; + +import course_project.engine.Position; + +import java.util.ArrayList; + +public class Ship { + private int size; + private String typeOfShip; + private int posX; + private int posY; + private ArrayList positionsArrayList = new ArrayList<>(); + + public Ship(String type, int size, int posX, int posY) { + this.size = size; + this.typeOfShip = type; + this.posX = posX; + this.posY = posY; + + Position position = new Position(this.posX, this.posY); + positionsArrayList.add(position); + } + + private int getSize() { + return this.size; + } + + private int getPosX() { + return this.posX; + } + + private int getPosY() { + return this.posY - 1; + } + + public String toString() { + return "You have added the following ship: " + "\n" + + "Type of ship: " + typeOfShip + "\n" + + "Size: " + getSize() + "\n" + + "X-position: " + getPosX() + "\n" + + "Y-position: " + getPosY() + "\n"; + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/ShipSize.java b/src/main/java/course_project/ships/ShipSize.java new file mode 100644 index 00000000..2a04c067 --- /dev/null +++ b/src/main/java/course_project/ships/ShipSize.java @@ -0,0 +1,19 @@ +package course_project.ships; + +import lombok.Getter; + +@Getter +public enum ShipSize { + SUBMARINE(3), + DESTROYER(2), + CRUISER(4), + BATTLESHIP(5), + CARRIER1(3), + CARRIER2(3); + + private int size; + + ShipSize(int size){ + this.size = size; + } +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/ShipType.java b/src/main/java/course_project/ships/ShipType.java new file mode 100644 index 00000000..b51ffc8d --- /dev/null +++ b/src/main/java/course_project/ships/ShipType.java @@ -0,0 +1,20 @@ +package course_project.ships; + +import lombok.Getter; + +@Getter +public enum ShipType { + SUBMARINE("S"), + DESTROYER("D"), + CRUISER("C"), + BATTLESHIP("B"), + CARRIER1("c"), + CARRIER2("c"); + + private String shipType; + + ShipType(String shipType) { + this.shipType = shipType; + } + +} \ No newline at end of file diff --git a/src/main/java/course_project/ships/Submarine.java b/src/main/java/course_project/ships/Submarine.java new file mode 100644 index 00000000..3428ccd9 --- /dev/null +++ b/src/main/java/course_project/ships/Submarine.java @@ -0,0 +1,8 @@ +package course_project.ships; + +public class Submarine extends Ship { + + public Submarine(int posX, int posY) { + super("Submarine", 3, posX, posY); + } +} \ No newline at end of file diff --git a/src/main/java/course_project/utils/FontColors.java b/src/main/java/course_project/utils/FontColors.java new file mode 100644 index 00000000..74cd8a4f --- /dev/null +++ b/src/main/java/course_project/utils/FontColors.java @@ -0,0 +1,34 @@ +package course_project.utils; + +public class FontColors { + + + // Colours for background + public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m"; + public static final String RED_BACKGROUND = "\033[41m"; + + // Reset colour + public static final String ANSI_RESET = "\u001B[0m"; + + // Colours for String + public static final String BLACK_BOLD = "\033[1;30m"; // BLACK + + + public FontColors() { + //menuLogo(); + } + + + // Method prints a colorful logo + + public void menuLogo() { + + System.out.println( + RED_BACKGROUND + BLACK_BOLD + " WELCOME TO SEA BATTLE! " + ANSI_RESET + + "\n" + "\n" + + + + " " + ANSI_BLUE_BACKGROUND + " " + ANSI_RESET + "\n" + ); + } +} \ No newline at end of file diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..d9b09c46 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -1,9 +1,18 @@ package homework_1; public class Main { + public static final String RESET = "\033[0m"; // Text Reset + public static final String RED_BOLD = "\033[1;31m"; // RED public static void main(String[] args) { - System.out.println("Hello homework!"); + //HW1 from 05.07.2021 (after review 09.07.2021) + for (String arg : args) { + if (arg.equals("error")) { + System.out.println(Main.RED_BOLD + "Alarm!" + Main.RESET); + break; + } else { + System.out.println(arg + ": " + arg.length() + " 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..71e33035 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,8 @@ +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..31869af8 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,54 @@ +package homework_2.pyramid_printer; + +import java.util.Scanner; +import java.util.regex.Pattern; + +public class PyramidPrinter implements Runnable { + + public static final String ERROR_MESSAGE; + public static final String WELCOME_MESSAGE; + public static final String ENTER_HEIGHT_MESSAGE; + public static final String REGEX; + + static { + ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + WELCOME_MESSAGE = "Welcome to the Pyramid Printer Application"; + ENTER_HEIGHT_MESSAGE = "Enter the height parameter"; + REGEX = "\\d+"; + } + + Pattern pattern = Pattern.compile(REGEX); + + @Override + public void run() { + startGreeting(); + Scanner scanner = new Scanner(System.in); + String consoleString = scanner.nextLine(); + scanner.close(); + if (numberFormatIsValid(consoleString)) { + printPyramid(Integer.parseInt(consoleString)); + } + } + + protected void startGreeting() { + System.out.println(WELCOME_MESSAGE); + System.out.println(ENTER_HEIGHT_MESSAGE); + } + + protected boolean numberFormatIsValid(String consoleString) { + if (!pattern.matcher(consoleString).matches()) { + System.out.println(ERROR_MESSAGE); + return false; + } + return true; + } + + protected void printPyramid(int height) { + for (int i = 1; i <= height; i++) { + for (int j = 0; j < i; j++) { + System.out.print("x"); + } + System.out.println(); + } + } +} diff --git a/src/main/java/homework_2/random_chars_table/Main.java b/src/main/java/homework_2/random_chars_table/Main.java new file mode 100644 index 00000000..be586c4b --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,8 @@ +package homework_2.random_chars_table; + +public class Main { + + public static void main(String[] args) { + new RandomCharsTable().run(); + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTable.java b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java new file mode 100644 index 00000000..a48b57ac --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,106 @@ +package homework_2.random_chars_table; + +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class RandomCharsTable implements Runnable { + + public static final String WELCOME_MESSAGE; + public static final String ENTER_PARAM_MESSAGE; + public static final String ERROR_MESSAGE; + public static final String REGEX; + + static { + WELCOME_MESSAGE = "Welcome to the Random Chars Table Application"; + ENTER_PARAM_MESSAGE = "Enter in one line 2 numbers and a line - " + + "the length and width of the table / two-dimensional array," + + " and the strategy (even or odd)"; + ERROR_MESSAGE = "Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]"; + REGEX = "\\s*[1-9]+\\s+[1-9]+\\s+(even|odd){1}$"; + } + + Pattern pattern = Pattern.compile(REGEX); + + @Override + public void run() { + startGreeting(); + String consoleString = readConsoleString(); + solveTask(consoleString); + } + + void startGreeting() { + System.out.println(WELCOME_MESSAGE); + System.out.println(ENTER_PARAM_MESSAGE); + } + + String readConsoleString() { + Scanner scanner = new Scanner(System.in); + String consoleString = scanner.nextLine(); + scanner.close(); + return consoleString; + } + + void printOddCapitalLetters(char[][] table) { + List oddChars = new ArrayList<>(); + for (char[] line : table) { + for (char column : line) { + if (column % 2 != 0) { + oddChars.add(column); + } + } + } + System.out.println("Odd letters - " + + oddChars.toString().replaceAll("[\\[\\]]", "")); + } + + void printEvenCapitalLetters(char[][] charsTable) { + List evenChars = new ArrayList<>(); + for (char[] line : charsTable) { + for (char column : line) { + if (column % 2 == 0) { + evenChars.add(column); + } + } + } + System.out.println("Even letters - " + + evenChars.toString().replaceAll("[\\[\\]]", "")); + } + + + void printCapitalLetters(char[][] charsTable, String strategy) { + if (strategy.equalsIgnoreCase("odd")) { + printOddCapitalLetters(charsTable); + } else if (strategy.equalsIgnoreCase("even")) { + printEvenCapitalLetters(charsTable); + } else { + System.out.println(ERROR_MESSAGE); + throw new IllegalArgumentException(); + } + } + void printTable(char[][] charsTable) { + for (char[] line : charsTable) { + System.out.print("| "); + for (char column : line) { + System.out.print(column + " | "); + } + System.out.println(); + } + } + + void solveTask(String consoleString) { + if (pattern.matcher(consoleString).matches()) { + String[] consoleStringArr = consoleString.split(" "); + int height = Integer.parseInt(consoleStringArr[0]); + int width = Integer.parseInt(consoleStringArr[1]); + String strategy = consoleStringArr[2]; + char[][] charsTable = new RandomCharsTableCreator().createRandomCharsTable(height, width); + printTable(charsTable); + printCapitalLetters(charsTable, strategy); + } else { + System.out.println(ERROR_MESSAGE); + } + } +} diff --git a/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java new file mode 100644 index 00000000..26eb7798 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTableCreator.java @@ -0,0 +1,26 @@ +package homework_2.random_chars_table; + +import java.util.concurrent.ThreadLocalRandom; + +public class RandomCharsTableCreator { + + + char[][] createRandomCharsTable(int height, int width) { + if (height < 1 || width < 1) { + System.out.println(RandomCharsTable.ERROR_MESSAGE); + throw new IllegalArgumentException(); + } + char[][] randomCharsTable = new char[height][width]; + for (int i = 0; i < height; i++) { + for (int j = 0; j < width; j++) { + randomCharsTable[i][j] = getRandomChar(); + } + } + return randomCharsTable; + } + + char getRandomChar() { + int randomNum = ThreadLocalRandom.current().nextInt(65, 90 + 1); + return (char) randomNum; + } +} 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..3ff7f428 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,8 @@ +package homework_2.traffic_light; + +public class Main { + + public static void main(String[] args) { + new 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..445f1e7d --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,76 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Scanner; +import java.util.regex.Pattern; + +public class TrafficLight implements Runnable { + + public static final String ERROR_MESSAGE; + public static final String RED_LIGHT_MESSAGE; + public static final String YELLOW_LIGHT_MESSAGE; + public static final String GREEN_LIGHT_MESSAGE; + public static final String DAY_IS_OVER_MESSAGE; + public static final String REGEX; + + static { + ERROR_MESSAGE = "Only 1 non-negative integer is allowed as passed parameter"; + DAY_IS_OVER_MESSAGE = "The day is over"; + RED_LIGHT_MESSAGE = "\u001b[31m RED \u001b[0m"; + YELLOW_LIGHT_MESSAGE = "\u001b[33m YELLOW \u001b[0m"; + GREEN_LIGHT_MESSAGE = "\u001b[32m GREEN \u001b[0m"; + REGEX = "\\d+"; + } + + Pattern pattern = Pattern.compile(REGEX); + + @Override + public void run() { + startGreeting(); + Scanner scanner = new Scanner(System.in); + String consoleString = scanner.nextLine(); + scanner.close(); + if (numberFormatIsValid(consoleString)) { + consoleString = consoleString.replaceAll("\\D+", ""); + System.out.println(getTrafficLightColor(Integer.parseInt(consoleString))); + } + } + + protected void startGreeting() { + System.out.println("Welcome to the Traffic Light Application"); + System.out.println("Enter the number of seconds since the start of the day"); + } + + protected boolean numberFormatIsValid(String consoleString) { + if (consoleString == null || consoleString.length() == 0) { + return false; + } + if (!pattern.matcher(consoleString).matches()) { + System.out.println(ERROR_MESSAGE); + return false; + } + if (Integer.parseInt(consoleString) > 86399) { + System.out.println(DAY_IS_OVER_MESSAGE); + return false; + } + return true; + } + + protected String getTrafficLightColor(int seconds) { + int secInMin = Math.floorMod(seconds, 60); + System.out.println("seconds= " + seconds); + System.out.println("secInMin= " + secInMin); + if (secInMin >= 0 && secInMin < 35) { + return GREEN_LIGHT_MESSAGE; + } + if ((secInMin >= 35 && secInMin < 40) || (secInMin >= 55 && secInMin < 60)) { + return YELLOW_LIGHT_MESSAGE; + } + if (secInMin >= 40 && secInMin < 55) { + return RED_LIGHT_MESSAGE; + } + return ERROR_MESSAGE; + } +} diff --git a/src/main/java/homework_3/ImmutableClassEmployee.java b/src/main/java/homework_3/ImmutableClassEmployee.java new file mode 100644 index 00000000..0d059807 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClassEmployee.java @@ -0,0 +1,46 @@ +package homework_3; + +import java.util.Date; + +//1. Declare your class as final, +// so other classes will not be able to extend it and break its immutability +final class ImmutableClassEmployee { + + //2. Mark all the fields private. So, they they can't be accessed outside the class + //3. Mark all fields final as well. So, no one can modify them anywhere else apart from the constructor. + private final int id; + private final String name; + private final Date dateOfBirth; + + //4. Provide an argument constructor with all initialization logic + public ImmutableClassEmployee(int id, String name, Date dateOfBirth) { + this.id = id; + this.name = name; + //5. Initialize all your fields by deeply copying them if they are not immutable by nature + this.dateOfBirth = new Date(dateOfBirth.getTime()); + } + + //6. Do not provide setters of your fields + public int getId() { + return id; + } + + public String getName() { + return name; + } + + //7. Instead of returning objects from the getters + // return a deep copy of them if this objects are not immutable by nature + public Date getDateOfBirth() { + return new Date(dateOfBirth.getTime()); + } + + @Override + public String toString() { + return "ImmutableClassEmployee{" + + "id = " + id + + ", name = '" + name + '\'' + + ", dateOfBirth = " + dateOfBirth + + ", dateOfBirth = " + dateOfBirth + "}"; + } +} diff --git a/src/main/java/homework_3/ImmutableClassRequirements b/src/main/java/homework_3/ImmutableClassRequirements new file mode 100644 index 00000000..c648a2bf --- /dev/null +++ b/src/main/java/homework_3/ImmutableClassRequirements @@ -0,0 +1,21 @@ +Following are the requirements for immutable class: + +1. Mark your class final, +2. Mark all the fields private, +3. Mark all fields final as well, +4. Provide an argument constructor with all initialization logic, +5. Initialize all mutable fields by deep copying, +6. Do not provide setters for your fields, +7. Return a deep copy of mutable fields from the getters. + +OR IN OTHER WORDS + +1. The class must be declared as final (So that child classes can’t be created) +2. Data members in the class must be declared as private (So that direct access is not allowed) +3. Data members in the class must be declared as final + (So that we can’t change the value of it after object creation) +4. A parameterized constructor should initialize all the fields performing a deep copy + (So that data members can’t be modified with object reference) +5. Deep Copy of objects should be performed in the getter methods + (To return a copy rather than returning the actual object reference) +6. No setters (To not have the option to change the value of the instance variable) diff --git a/src/main/java/homework_4/custom_annotation/ClassInfo.java b/src/main/java/homework_4/custom_annotation/ClassInfo.java new file mode 100644 index 00000000..2650800f --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/ClassInfo.java @@ -0,0 +1,17 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; +import java.text.SimpleDateFormat; +import java.util.Calendar; + + +@Documented +@Target(ElementType.TYPE) +@Inherited +@Retention(RetentionPolicy.RUNTIME) +public @interface ClassInfo { + String author() default "Khlebnikov Evgeniy"; + String date(); + int version() default 1; + String specification(); +} diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotationTaskDescription b/src/main/java/homework_4/custom_annotation/CustomAnnotationTaskDescription new file mode 100644 index 00000000..9fad52fc --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotationTaskDescription @@ -0,0 +1,4 @@ +CustomAnnotation: +Реализовать кастомную аннотацию. +Название и реализация - на выбор, главное чтобы она где-то ставилась и что-то делала +(например, из нее мы бы инжектили дефолтные значения в конструктор) diff --git a/src/main/java/homework_4/custom_annotation/CustomAnnotationTestClass.java b/src/main/java/homework_4/custom_annotation/CustomAnnotationTestClass.java new file mode 100644 index 00000000..5e0ddb5d --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/CustomAnnotationTestClass.java @@ -0,0 +1,9 @@ +package homework_4.custom_annotation; + +@FilePathCustomAnnotation +@ClassInfo(date = "15/08/2021", specification = "Class for testing annotations") +public class CustomAnnotationTestClass { + + protected static final String FILE_PATH = CustomAnnotationTestClass.class.getAnnotation(FilePathCustomAnnotation.class).path(); + +} diff --git a/src/main/java/homework_4/custom_annotation/FilePathCustomAnnotation.java b/src/main/java/homework_4/custom_annotation/FilePathCustomAnnotation.java new file mode 100644 index 00000000..663d437a --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/FilePathCustomAnnotation.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 FilePathCustomAnnotation { + String path() default "C:\\Users\\admin\\IdeaProjects\\Java_Core_June_2021\\src\\main\\resources\\custom_file_reader\\testFile.txt"; +} \ No newline at end of file diff --git a/src/main/java/homework_4/custom_annotation/MaxFieldLength.java b/src/main/java/homework_4/custom_annotation/MaxFieldLength.java new file mode 100644 index 00000000..46b97ccf --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/MaxFieldLength.java @@ -0,0 +1,10 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Target({ElementType.FIELD, ElementType.METHOD}) +@Inherited +@Retention(RetentionPolicy.RUNTIME) +public @interface MaxFieldLength { + int maxLength() default 100; +} diff --git a/src/main/java/homework_4/custom_annotation/MethodInfo.java b/src/main/java/homework_4/custom_annotation/MethodInfo.java new file mode 100644 index 00000000..55f03162 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/MethodInfo.java @@ -0,0 +1,14 @@ +package homework_4.custom_annotation; + +import java.lang.annotation.*; + +@Documented +@Target({ElementType.METHOD}) +@Inherited +@Retention(RetentionPolicy.RUNTIME) +public @interface MethodInfo { + String author() default "Khlebnikov Evgeniy"; + int version() default 1; + boolean suppressExceptions() default false; + String description(); +} \ No newline at end of file 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..748f705e --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,64 @@ +package homework_4.custom_file_reader; + +import homework_4.custom_annotation.ClassInfo; +import homework_4.custom_annotation.FilePathCustomAnnotation; +import homework_4.custom_annotation.MethodInfo; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Scanner; + +@ClassInfo(date = "15/08/2021", specification = "Customized FileReader Class") +@FilePathCustomAnnotation + +public class CustomFileReader { + private String filePath = CustomFileReader.class.getAnnotation(FilePathCustomAnnotation.class).path(); + @MethodInfo(description = "NIO2") + public void run1() { + Path path = Paths.get(filePath); + try (BufferedReader bufferedReader = Files.newBufferedReader(path)) { + String result = bufferedReader.readLine(); + printResult(result); + } catch (IOException e) { + System.out.println("NIO2"); + printErrorMessage(); + e.printStackTrace(); + } + } + @MethodInfo(description = "BufferedReaderFileReader") + public void run2() { + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) { + String result = bufferedReader.readLine(); + printResult(result); + } catch (IOException e) { + printErrorMessage(); + e.printStackTrace(); + } + } + + @MethodInfo(description = "ScannerFileReader") + public void run3() { + try (Scanner scanner = new Scanner(new File(filePath))) { + scanner.useDelimiter("[.,]"); + StringBuilder stringBuilder = new StringBuilder(); + while (scanner.hasNext()) { + stringBuilder.append(scanner.next()); + } + System.out.println(stringBuilder); + } catch (FileNotFoundException e) { + printErrorMessage(); + e.printStackTrace(); + } + } + + + public void printResult(String result) { + System.out.println(result.replaceAll("[.,]", "")); + } + + private void printErrorMessage() { + System.out.println(Messages.FILE_NOT_FOUND_MESSAGE); + } + +} 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..8f4b2b91 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,12 @@ +package homework_4.custom_file_reader; + +public class Main { + + public static void main(String[] args) { + + new CustomFileReader().run1(); + new CustomFileReader().run2(); + new CustomFileReader().run3(); + + } +} diff --git a/src/main/java/homework_4/custom_file_reader/Messages.java b/src/main/java/homework_4/custom_file_reader/Messages.java new file mode 100644 index 00000000..5db40e30 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Messages.java @@ -0,0 +1,7 @@ +package homework_4.custom_file_reader; + +public class Messages { + + static final String FILE_NOT_FOUND_MESSAGE = "File not found. Incorrect path"; + +} 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..85fbcf94 --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,18 @@ +package homework_4.singleton; + +class Singleton { + private static volatile Singleton instance = null; + private Singleton(){ + } + public static Singleton getInstance() { + //Double checked locking for correct operation in multithreaded applications + if (instance == null) { + synchronized (Singleton.class) { + if (instance == null) { + instance = new Singleton(); + } + } + } + return instance; + } +} diff --git a/src/main/java/homework_4/singleton/SingletonTaskDescription b/src/main/java/homework_4/singleton/SingletonTaskDescription new file mode 100644 index 00000000..80492592 --- /dev/null +++ b/src/main/java/homework_4/singleton/SingletonTaskDescription @@ -0,0 +1,7 @@ +Singleton: +Написать приложение-синглтон. +Максимум 1 обьект этого класса. +Приватный конструктор и публичный метод getInstance(); + + + 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..56d4cf18 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,42 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Pattern; + +public class CustomRegexMatcher implements Runnable { + + @Override + public void run() { + System.out.println("Enter an URL address"); + checkURL(); + } + + public static String CustomRegexForURL; + + static { + CustomRegexForURL = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; + } + + private void checkURL() { + + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) { + String string = bufferedReader.readLine(); + if (checkURLMatch(string)) { + System.out.println("URL is valid"); + } else { + System.out.println("URL is not valid"); + } + + } catch (IOException e) { + e.printStackTrace(); + } + + } + + private boolean checkURLMatch(String string) { + return Pattern.matches(CustomRegexForURL, string); + } + +} \ 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..a4aeb0ca --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,10 @@ +package homework_5.custom_regex_matcher; + +public class Main { + + public static void main(String[] args) { + + new CustomRegexMatcher().run(); + + } +} \ No newline at end of file diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..64417702 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,9 @@ +package homework_5.power_of_number; + +public class Main { + + public static void main(String[] args) { + new PowerOfNumber().run(); + } + +} \ No newline at end of file diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..50494b94 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,67 @@ +package homework_5.power_of_number; + +import java.math.BigInteger; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + + +public class PowerOfNumber { + + private int number; + private int power; + private BigInteger powerOfNumber; + + public static final String ERROR_MESSAGE; + public static final String ENTER_MESSAGE; + + static { + ERROR_MESSAGE = "Only 2 non-negative integers are allowed"; + ENTER_MESSAGE = "Enter 2 positive integer numbers: "; + } + + protected void run() { + try { + readConsole(); + if (power == 0) { + powerOfNumber = BigInteger.ONE; + } else if (number == 0) { + powerOfNumber = BigInteger.ZERO; + } else { + powerOfNumber = BigInteger.valueOf(number); + riseNumberToPower(power); + } + System.out.printf("The number %s raised to the power %s equals: %s", number, power, powerOfNumber); + } catch (IOException | NullPointerException e) { + System.out.println(ERROR_MESSAGE); + } + + } + + private void riseNumberToPower(int power) { + + if (power != 1) { + powerOfNumber = powerOfNumber.multiply(BigInteger.valueOf(number)); + power--; + riseNumberToPower(power); + } + + } + + private void readConsole() throws IOException, NullPointerException { + + System.out.print(ENTER_MESSAGE); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) { + String inputString = bufferedReader.readLine(); + + if (inputString.matches("^\\d+\\s\\d+$")) { + String[] argsArray = inputString.split("\\s+"); + number = Integer.parseInt(argsArray[0]); + power = Integer.parseInt(argsArray[1]); + } else { + System.out.println(ERROR_MESSAGE); + } + } + } + +} \ No newline at end of file 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..0aa49a17 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsGenerator.java @@ -0,0 +1,34 @@ +package homework_6.map_problems_generator; + +import lombok.*; +import java.util.Objects; + +public class MapProblemsGenerator { + + @Data + @AllArgsConstructor + public static class MapProblemsCollisionGenerator { + private int number; + private String name; + + @Override + public boolean equals(Object object) { + if (this == object) return true; + if (object == null || getClass() != object.getClass()) return false; + MapProblemsCollisionGenerator mpcg = (MapProblemsCollisionGenerator) object; + return number == mpcg.number && Objects.equals(name, mpcg.name); + } + + @Override + public int hashCode() { + return 1; + } + } + + @Data + @AllArgsConstructor + public static class MapProblemsMutableGenerator { + private int number; + private String name; + } +} \ 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..65e5277b --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,11 @@ +package homework_7; + +import homework_7.pets.Cat; +import homework_7.pets.Kitten; + +@FunctionalInterface +public interface KittenToCatFunction { + + R grow(T t); + +} \ No newline at end of file diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..cf48d293 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,19 @@ +package homework_7; + +import homework_7.pets.Cat; +import homework_7.pets.Kitten; + +public class Main { + public static void main(String[] args) { + + Kitten kitten = new Kitten("Lilac", 1, 1.5); + System.out.println(kitten); + + KittenToCatFunction function = (k -> new Cat(k.getColor(), + k.getAgeInMonth() + 11, k.getWeight() * 2.5)); + + Cat cat = function.grow(kitten); + System.out.println(cat); + + } +} \ No newline at end of file diff --git a/src/main/java/homework_7/pets/Cat.java b/src/main/java/homework_7/pets/Cat.java new file mode 100644 index 00000000..2a08ef7a --- /dev/null +++ b/src/main/java/homework_7/pets/Cat.java @@ -0,0 +1,13 @@ +package homework_7.pets; + +import lombok.*; + +@Data +@AllArgsConstructor +public class Cat { + + private String color; + private int ageInMonth; + private double weight; + +} \ No newline at end of file diff --git a/src/main/java/homework_7/pets/Kitten.java b/src/main/java/homework_7/pets/Kitten.java new file mode 100644 index 00000000..6ff5aa7e --- /dev/null +++ b/src/main/java/homework_7/pets/Kitten.java @@ -0,0 +1,13 @@ +package homework_7.pets; + +import lombok.*; + +@Data +@AllArgsConstructor +public class Kitten { + + private String color; + private int ageInMonth; + private double weight; + +} \ No newline at end of file diff --git a/src/main/resources/custom_file_reader/testFile b/src/main/resources/custom_file_reader/testFile new file mode 100644 index 00000000..e69de29b diff --git a/src/main/resources/custom_file_reader/testFile.txt b/src/main/resources/custom_file_reader/testFile.txt new file mode 100644 index 00000000..4ea53c2b --- /dev/null +++ b/src/main/resources/custom_file_reader/testFile.txt @@ -0,0 +1 @@ +, Test , ,,file \ No newline at end of file diff --git a/src/test/java/base/UnitBase.java b/src/test/java/base/UnitBase.java index 97e2685b..8df5dcf8 100644 --- a/src/test/java/base/UnitBase.java +++ b/src/test/java/base/UnitBase.java @@ -70,4 +70,4 @@ protected void printOut() { // assertEquals("xx", getOutputLines()[1]); // } -} +} \ No newline at end of file diff --git a/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java new file mode 100644 index 00000000..443781d9 --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,89 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; +import java.util.NoSuchElementException; +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterTest extends UnitBase { + + @Test + void givenEmptyArgument_whenRun_thenNoSuchElementException() { + setInput(""); + assertThrows(NoSuchElementException.class, () -> new PyramidPrinter().run()); + } + + @Test + void givenZeroAsArgument_whenRun_thenEmptyString() { + setInput("0"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Welcome to the Pyramid Printer Application"); + removeFromOutput("Enter the height parameter"); + assertEquals("", getOutputLines()[0]); + } + + + @Test + void givenTenAsArgument_whenRun_thenTenRowsPyramid() { + setInput("10"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Welcome to the Pyramid Printer Application"); + removeFromOutput("Enter the height parameter"); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + assertEquals("xxxxx", getOutputLines()[4]); + assertEquals("xxxxxx", getOutputLines()[5]); + assertEquals("xxxxxxx", getOutputLines()[6]); + assertEquals("xxxxxxxx", getOutputLines()[7]); + assertEquals("xxxxxxxxx", getOutputLines()[8]); + assertEquals("xxxxxxxxxx", getOutputLines()[9]); + } + + @Test + void givenMinusOneAsArgument_whenRun_thenErrorMessage() { + setInput("-1"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Welcome to the Pyramid Printer Application"); + removeFromOutput("Enter the height parameter"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + + @Test + void givenStringValueAsArgument_whenRun_thenErrorMessage() { + setInput("StringAsValue"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Welcome to the Pyramid Printer Application"); + removeFromOutput("Enter the height parameter"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + + @Test + void givenTwoArgumentsAsArgument_whenRun_thenErrorMessage() { + setInput("1 2"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Welcome to the Pyramid Printer Application"); + removeFromOutput("Enter the height parameter"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + + @Test + void givenDoubleAsArgument_whenRun_thenErrorMessage() { + setInput("0.12345"); + new PyramidPrinter().run(); + printOut(); + removeFromOutput("Welcome to the Pyramid Printer Application"); + removeFromOutput("Enter the height parameter"); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java new file mode 100644 index 00000000..77ca7dff --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableCreatorTest.java @@ -0,0 +1,48 @@ +package homework_2.random_chars_table; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class RandomCharsTableCreatorTest { + + private List evenLettersArrayList; + private List oddLettersArrayList; + + @BeforeEach + void setUp() { + evenLettersArrayList = Arrays.asList(new Character[]{60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90}); + oddLettersArrayList = Arrays.asList(new Character[]{61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89}); + } + + @Test + void createRandomCharsTableTest1() { + RandomCharsTableCreator randomCharsTableCreator = new RandomCharsTableCreator(); + char[][] charsTable = randomCharsTableCreator.createRandomCharsTable(20, 40); + + assertEquals(20, charsTable.length); + for (char[] chars : charsTable) { + assertEquals(40, chars.length); + for (char ch : chars) { + assertTrue(evenLettersArrayList.contains(ch) || oddLettersArrayList.contains(ch)); + } + } + } + + @Test + void createRandomCharsTableTest2() { + RandomCharsTableCreator randomCharsTableCreator = new RandomCharsTableCreator(); + char[][] charsTable = randomCharsTableCreator.createRandomCharsTable(12, 122); + + assertEquals(12, charsTable.length); + for (char[] chars : charsTable) { + assertEquals(122, chars.length); + for (char ch : chars) { + assertTrue(evenLettersArrayList.contains(ch) || oddLettersArrayList.contains(ch)); + } + } + } +} \ No newline at end of file diff --git a/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java new file mode 100644 index 00000000..515a4679 --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,119 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.NoSuchElementException; + +import static org.junit.jupiter.api.Assertions.*; + +class RandomCharsTableTest extends UnitBase { + + public final String WELCOME_MESSAGE_TEST = "Welcome to the Random Chars Table Application"; + public final String ENTER_PARAM_MESSAGE_TEST = "Enter in one line 2 numbers and a line - " + + "the length and width of the table / two-dimensional array," + + " and the strategy (even or odd)"; + public final String ERROR_MESSAGE_TEST = "Passed parameters should match the format " + + "[positive integer] [positive integer] [even|odd]"; + + @Test + void givenZeroAsArgument_whenRun_thenErrorMessage() { + setInput("0 0 odd"); + new RandomCharsTable().run(); + printOut(); + removeFromOutput(WELCOME_MESSAGE_TEST); + removeFromOutput(ENTER_PARAM_MESSAGE_TEST); + assertEquals(ERROR_MESSAGE_TEST, getOutputLines()[0]); + } + + @Test + void givenEmptyArgument_whenRun_thenNoSuchElementException() { + setInput(""); + assertThrows(NoSuchElementException.class, () -> new RandomCharsTable().run()); + } + + @Test + void givenNegativeIntegerAsFirstArgument_whenRun_thenPrintErrorMessage() { + setInput("-2 2 even"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenNnegativeIntegerAsSecondArgument_whenRun_thenPrintErrorMessage() { + setInput("2 -2 even"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenWrongStrategy_whenRun_thenPrintErrorMessage() { + setInput("2 2 wrongStrategy"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenLetterAsFirstArgument_whenRun_thenPrintErrorMessage() { + setInput("w 2 even"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenLetterAsSecondrgument_whenRun_thenPrintErrorMessage() { + setInput("2 W even"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenDoubleAsFirstArgument_whenRun_thenPrintErrorMessage() { + setInput("0.12345 2 even"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenDoubleAsSecondArgument_whenRun_thenPrintErrorMessage() { + setInput("2 0.12345 even"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenMoreThanThreeArguments_whenRun_thenPrintErrorMessage() { + setInput("1 2 3 odd"); + new RandomCharsTable().run(); + assertTrue(getOutput().contains(ERROR_MESSAGE_TEST)); + } + + @Test + void givenLengthWidthEvenStrategy_whenRun_thenPrintEvenChars() { + setInput("8 8 even"); + new RandomCharsTable().run(); + removeFromOutput("Even letters - "); + removeFromOutput(","); + removeFromOutput(" "); + String str = getOutputLines()[getOutputLines().length - 1]; + for (int i = 0; i < str.length(); i++) { + assertEquals(0, str.charAt(i) % 2); + } + } + + + @Test + void givenLengthWidthOddStrategy_whenRun_thenPrintOddChars() { + setInput("8 8 odd"); + new RandomCharsTable().run(); + removeFromOutput("Odd letters - "); + removeFromOutput(","); + removeFromOutput(" "); + String str = getOutputLines()[getOutputLines().length - 1]; + for (int i = 0; i < str.length(); i++) { + assertEquals(1, str.charAt(i) % 2); + } + } + + +} \ No newline at end of file diff --git a/src/test/java/homework_2/traffic_light/TrafficLightTest.java b/src/test/java/homework_2/traffic_light/TrafficLightTest.java new file mode 100644 index 00000000..9e51ca6f --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,80 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class TrafficLightTest extends UnitBase { + + @Test + void givenMinValue_whenRun_thenPrintColor() { + setInput("0"); + new TrafficLight().run(); + assertTrue(getOutput().contains("GREEN")); + } + + @Test + void givenNumberFrom0InclusiveTo35NotInclusive_whenRun_thenPrintColor() { + setInput("34"); + new TrafficLight().run(); + assertTrue(getOutput().contains("GREEN")); + } + + + @Test + void givenNumberFrom35InclusiveTo40NotInclusive_whenRun_thenPrintColor() { + setInput("39"); + new TrafficLight().run(); + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void givenNumberFrom40InclusiveTo55NotInclusive_whenRun_thenPrintColor() { + setInput("54"); + new TrafficLight().run(); + assertTrue(getOutput().contains("RED")); + } + + @Test + void givenNumberFrom55InclusiveTo60NotInclusive_whenRun_thenPrintColor() { + setInput("59"); + new TrafficLight().run(); + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void givenMaxValue86399_whenRun_thenPrintColor() { + setInput("86399"); + new TrafficLight().run(); + assertTrue(getOutput().contains("YELLOW")); + } + + @Test + void givenNumberBiggerThanItIsAllowed_whenRun_then_printErrorMessage() { + setInput("86400"); + new TrafficLight().run(); + assertTrue(getOutput().contains("The day is over")); + } + + @Test + void givenNegativeInteger_whenRun_thenPrintErrorMessage() { + setInput("-1"); + new TrafficLight().run(); + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void givenString_whenRun_thenPrintErrorMessage() { + setInput("abc"); + new TrafficLight().run(); + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } + + @Test + void givenSeveralArguments_whenRun_thenPrintErrorMessage() { + setInput("2 2"); + new TrafficLight().run(); + assertTrue(getOutput().contains("Only 1 non-negative integer is allowed as passed parameter")); + } +} \ No newline at end of file diff --git a/src/test/java/homework_3/ImmutableClassEmployeeTest.java b/src/test/java/homework_3/ImmutableClassEmployeeTest.java new file mode 100644 index 00000000..00a51793 --- /dev/null +++ b/src/test/java/homework_3/ImmutableClassEmployeeTest.java @@ -0,0 +1,20 @@ +package homework_3; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ImmutableClassEmployeeTest { + + @Test + void getId() { + } + + @Test + void getName() { + } + + @Test + void getDateOfBirth() { + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/ClassInfoTest.java b/src/test/java/homework_4/custom_annotation/ClassInfoTest.java new file mode 100644 index 00000000..454b8c3b --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/ClassInfoTest.java @@ -0,0 +1,24 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class ClassInfoTest extends UnitBase { + + private final String AUTHOR_TEST = "Khlebnikov Evgeniy"; + private final String DATE_STRING_TEST = "15/08/2021"; + private final int VERSION_TEST = 1; + private final String DESCRIPTION_TEST = "Class for testing annotations"; + + @Test + void testAnnotation() { + + assertEquals(AUTHOR_TEST, CustomAnnotationTestClass.class.getAnnotation(ClassInfo.class).author()); + assertEquals(DATE_STRING_TEST, CustomAnnotationTestClass.class.getAnnotation(ClassInfo.class).date()); + assertEquals(VERSION_TEST, CustomAnnotationTestClass.class.getAnnotation(ClassInfo.class).version()); + assertEquals(DESCRIPTION_TEST, CustomAnnotationTestClass.class.getAnnotation(ClassInfo.class).specification()); + + } +} \ No newline at end of file diff --git a/src/test/java/homework_4/custom_annotation/FilePathCustomAnnotationTest.java b/src/test/java/homework_4/custom_annotation/FilePathCustomAnnotationTest.java new file mode 100644 index 00000000..442891e6 --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/FilePathCustomAnnotationTest.java @@ -0,0 +1,18 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class FilePathCustomAnnotationTest extends UnitBase { + + private final String DEFAULT_FILE_PATH_TEST = "./src/main/resources/custom_file_reader/testFile.txt"; + + @Test + void testAnnotation() { + + assertEquals( DEFAULT_FILE_PATH_TEST, CustomAnnotationTestClass.class.getAnnotation(FilePathCustomAnnotation.class).path()); + + } +} \ No newline at end of file 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..87ad7db1 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,31 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + + CustomFileReader reader = new CustomFileReader(); + private final String stringTest = "Test file"; + + @Test + void testNIO2() { + reader.run1(); + assertTrue(getOutput().contains(stringTest)); + } + + @Test + void testBufferedReaderFileReader() { + reader.run2(); + assertTrue(getOutput().contains(stringTest)); + } + + @Test + void testScannerFileReader() { + reader.run3(); + assertTrue(getOutput().contains(stringTest)); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_4/singleton/SingletonTest.java b/src/test/java/homework_4/singleton/SingletonTest.java new file mode 100644 index 00000000..730f2556 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,16 @@ +package homework_4.singleton; + +import base.UnitBase; +import homework_4.singleton.Singleton; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +class SingletonTest extends UnitBase { + + @Test + void getInstance() { + Singleton singletonInstance1 = Singleton.getInstance(); + Singleton singletonInstance2 = Singleton.getInstance(); + Assertions.assertSame(singletonInstance1, singletonInstance2); + } +} \ No newline at end of file diff --git a/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java new file mode 100644 index 00000000..9827544c --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,47 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + + CustomRegexMatcher customRegexMatcher = new CustomRegexMatcher(); + + @Test + void givenRegexAndGoogle_whenRun_returnURLIsValid() { + setInput("https://www.google.com/"); + customRegexMatcher.run(); + assertEquals("URL is valid", getOutputLines()[1]); + } + + @Test + void givenRegexAndEpam_whenRun_returnURLIsValid() { + setInput("https://www.epam.com/careers"); + customRegexMatcher.run(); + assertEquals("URL is valid", getOutputLines()[1]); + } + + @Test + void givenRegexAndFPT_whenRun_returnURLIsValid() { + setInput("ftp://websiteaddress.com"); + customRegexMatcher.run(); + assertEquals("URL is valid", getOutputLines()[1]); + } + + @Test + void givenRegexAndNumber_whenRun_returnURLIsNotValid() { + setInput("123456789"); + customRegexMatcher.run(); + assertEquals("URL is not valid", getOutputLines()[1]); + } + + @Test + void givenRegexAndString_whenRun_returnURLIsNotValid() { + setInput("String"); + customRegexMatcher.run(); + assertEquals("URL is not valid", getOutputLines()[1]); + } + +} \ No newline at end of file diff --git a/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java new file mode 100644 index 00000000..63b4f794 --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,114 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + + PowerOfNumber powerOfNumber = new PowerOfNumber(); + + + @Test + void given2and3_whenRun_then8() { + setInput("2 3"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + removeFromOutput("The number 2 raised to the power 3 equals: "); + assertEquals("8", getOutputLines()[0]); + } + + @Test + void give3and2_whenRun_then9() { + setInput("3 2"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + removeFromOutput("The number 3 raised to the power 2 equals: "); + assertEquals("9", getOutputLines()[0]); + } + + @Test + void given0and0_whenRun_thenReturn() { + setInput("0 0"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + removeFromOutput("The number 0 raised to the power 0 equals: "); + assertEquals("1", getOutputLines()[0]); + } + + @Test + void given0and3_whenRun_thenReturn() { + setInput("0 3"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + removeFromOutput("The number 0 raised to the power 3 equals: "); + assertEquals("0", getOutputLines()[0]); + } + + @Test + void given3and0_whenRun_thenReturn() { + setInput("3 0"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + removeFromOutput("The number 3 raised to the power 0 equals: "); + assertEquals("1", getOutputLines()[0]); + } + + @Test + void givenStringAndNumber_whenRun_thenError() { + setInput("two 2"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void giveNegativeAndNumber_whenRun_thenError() { + setInput("-7 3"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void givenNumberAndNegative_whenRun_thenError() { + setInput("5 -2"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void givenNullString_whenRun_thenError() { + setInput(""); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void givenEmptyStting_whenRun_thenError() { + setInput(" "); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void givenLessParams_whenRun_thenError() { + setInput("1"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void giveMoreParams_whenRun_thenError() { + setInput("1 2 3"); + powerOfNumber.run(); + removeFromOutput("Enter 2 positive integer numbers: "); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + +} \ No newline at end of file diff --git a/testFile.txt b/testFile.txt new file mode 100644 index 00000000..79c09680 --- /dev/null +++ b/testFile.txt @@ -0,0 +1 @@ +, , Test ,,, file , \ No newline at end of file