diff --git a/README.md b/README.md index 5d686e9f..8cba6186 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,23 @@ # Java Core June 2021 -## *Nikolaev Artem* +## *Dmitriy Prihodko* | 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](./src/main/java/homework_1) | The app that reads input arguments and prints them, until "error" argument | +| HW2 | [TrafficLight](./src/main/java/homework_2/traffic_light)
:wrench:[TrafficLightTest](./src/test/java/homework_2/traffic_light) | App reads one time the number of seconds since the beginning of the day and prints the traffic light| +| HW2 | [PyramidPrinter](./src/main/java/homework_2/pyramid_printer)
:wrench:[PyramidPrinterTest](./src/test/java/homework_2/pyramid_printer)| App reads the number one time from the command line, and prints a pyramid of "x". | +| HW2 | [RandomCharsTable](./src/main/java/homework_2/random_chars_table)
:wrench:[RandomCharsTableTest](./src/test/java/homework_2/random_chars_table)| App reads width and length of the table array, and strategy keyword (even or odd). App adds random chars from A to Z in table. Prints a table and all even or odd letters. | +| HW3 | [ImmutableClass](./src/main/java/homework_3)| ImmutableClass| +| HW4 | [CustomFileReader](./src/main/java/homework_4/custom_file_reader)
:wrench:[CustomFileReaderTest](./src/test/java/homework_4/custom_file_reader)| This application reads the text from the file, removes commas and periods and them outputs the text to the console. | +| HW4 | [CustomAnnotation](./src/main/java/homework_4/custom_annotation)
:wrench:[CustomAnnotationTest](./src/test/java/homework_4/custom_annotation)| Create custom annotation| +| HW4 | [Singleton](./src/main/java/homework_4/singleton)
:wrench:[SingletonTest](./src/test/java/homework_4/singleton)| This is a singleton app. you can create only 1 instance of this class.| +| HW5 | [CustomRegexMatcher](./src/main/java/homework_5/custom_regex_matcher)
:wrench:[CustomRegexMatcherTest](./src/test/java/homework_5/custom_regex_matcher)| This app that accepts 2 numbers from the command line, and raises 1 number to the power of 2 numbers.| +| HW5 | [PowerOfNumber](./src/main/java/homework_4/power_of_number)
:wrench:[PowerOfNumberTest](./src/test/java/homework_4/power_of_number)| This app checks whether the email is entered correctly.| +| HW6 | [MapProblemsCollisionGenerator](./src/main/java/homework_6/map_problems_generator) | This app creates collisions in HashMap.| +| HW6 | [MapProblemsMutableGenerator](./src/main/java/homework_6/map_problems_generator) | A mutable class is declared, this object in HashMap we will not be able to get this object by the key. | +| HW7 | [KittenToCatFunction](./src/main/java/homework_7/) | the KittenToCatFunction functional interface, with the abstract grow () method, accepts Kitten and return only Cat.. | +| CourseProject |[SeaBattle](./src/main/java/course_project/sea_battle)
:wrench:[SeaBattleTest](./src/test/java/course_project/sea_battle)| the game follows the standard rules of sea battle | + +[Link to CodingBat](https://codingbat.com/done?user=bomba_25@mail.ru&tag=8601275236) -[Link to markdown giude](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) diff --git a/build.gradle b/build.gradle index b91dc843..84cf5a18 100644 --- a/build.gradle +++ b/build.gradle @@ -10,6 +10,7 @@ repositories { } dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0' } diff --git a/src/main/java/course_project/sea_battle/Main.java b/src/main/java/course_project/sea_battle/Main.java new file mode 100644 index 00000000..ff7cf31f --- /dev/null +++ b/src/main/java/course_project/sea_battle/Main.java @@ -0,0 +1,12 @@ +package course_project.sea_battle; + +import course_project.sea_battle.conroller.SeaBattle; + +import java.io.IOException; + +public class Main { + public static void main(String[] args) throws IOException { + SeaBattle game = new SeaBattle(); + game.start(); + } +} diff --git a/src/main/java/course_project/sea_battle/animated/AnimateStartGame.java b/src/main/java/course_project/sea_battle/animated/AnimateStartGame.java new file mode 100644 index 00000000..c189b8b2 --- /dev/null +++ b/src/main/java/course_project/sea_battle/animated/AnimateStartGame.java @@ -0,0 +1,20 @@ +package course_project.sea_battle.animated; + +public class AnimateStartGame extends Thread { + @Override + public void run() { + System.out.println("*****************************"); + String str = "\u001B[31m" + " WELCOME TO BATTLESHIPS GAME" + "\u001B[0m"; + + try { + Thread.sleep(2000); + for (Character character : str.toCharArray()) { + System.out.print(character); + Thread.sleep(100); + } + } catch (InterruptedException e) { + e.printStackTrace(); + } + System.out.println("\n*****************************"); + } +} diff --git a/src/main/java/course_project/sea_battle/conroller/Dialog.java b/src/main/java/course_project/sea_battle/conroller/Dialog.java new file mode 100644 index 00000000..7f601096 --- /dev/null +++ b/src/main/java/course_project/sea_battle/conroller/Dialog.java @@ -0,0 +1,83 @@ +package course_project.sea_battle.conroller; + +import course_project.sea_battle.model.CoordinateTranslator; +import course_project.sea_battle.model.ModelPlayer; +import course_project.sea_battle.model.Ship; +import course_project.sea_battle.view.PaintFieldPlayer; +import course_project.sea_battle.view.Speaker; + +import java.util.Locale; +import java.util.Scanner; + +public class Dialog { + + private final Scanner reader; + + public Dialog(final Scanner reader) { + this.reader = reader; + } + + public void generateShips(ModelPlayer player) { + PaintFieldPlayer paint = new PaintFieldPlayer(player); + Speaker.voice("inputInstruction"); + while (!player.readyToGame()) { + paint.paintField(); + String dateShip = reader.nextLine(); + tryAddShipInField(dateShip, player); + } + } + + public String namePlayerGet() { + try { + String name = reader.nextLine(); + return name; + } catch (Exception e) { + + } + return "Empty"; + } + + public String shotPlayer(ModelPlayer player) { + while (true) { + String shot = reader.nextLine(); + if (shot.matches("(([1-9])|([1][0])) [a-jA-J]")) { + return player.shot(shot); + } else { + Speaker.voice("notCorrect"); + } + } + } + + public boolean autoGenerate() { + while (true) { + String choice = reader.nextLine().toLowerCase(Locale.ROOT); + if (choice.matches("y|n")) { + if (choice.equals("y")) { + return true; + } + if (choice.equals("n")) { + return false; + } + } else { + Speaker.voice("notCorrect"); + } + } + } + + private void tryAddShipInField(String dateShip, ModelPlayer player){ + if (dateShip.matches("[1-2] (([1-9])|([1][0])) [a-jA-J] [1-4]")) { + + String[] dateShipSplit = dateShip.split(" "); + boolean orient = dateShipSplit[0].equals("2"); + int start = Integer.parseInt(dateShipSplit[1]) - 1; + int end = CoordinateTranslator.coordinate(dateShipSplit[2].toLowerCase(Locale.ROOT)); + int size = Integer.parseInt(dateShipSplit[3]); + + String message = player.addShip(new Ship(orient, start, end, size)); + Speaker.voice(message); + } else { + Speaker.voice("notCorrect"); + } + } + +} diff --git a/src/main/java/course_project/sea_battle/conroller/SeaBattle.java b/src/main/java/course_project/sea_battle/conroller/SeaBattle.java new file mode 100644 index 00000000..d5548ced --- /dev/null +++ b/src/main/java/course_project/sea_battle/conroller/SeaBattle.java @@ -0,0 +1,73 @@ +package course_project.sea_battle.conroller; + +import course_project.sea_battle.model.Field; +import course_project.sea_battle.model.ModelPlayer; +import course_project.sea_battle.animated.AnimateStartGame; +import course_project.sea_battle.view.PaintFieldInPlay; +import course_project.sea_battle.view.Speaker; + +import java.util.Scanner; + +public class SeaBattle extends Thread { + + public void run() { + try (Scanner scanner = new Scanner(System.in)) { + Dialog dialog = new Dialog(scanner); + Thread anim = new AnimateStartGame(); + anim.start(); + anim.join(); + Speaker.voice("dialogName"); + + String PlayerName = dialog.namePlayerGet(); + + ModelPlayer player = new ModelPlayer(PlayerName, new Field(10, 10)); + ModelPlayer IIPlayer = new ModelPlayer("BOT2", new Field(10, 10)); + Speaker.voice("autoGenerate"); + boolean choiceGenerate = dialog.autoGenerate(); + + if (choiceGenerate) { + player.autoGenerateShips(); + } else { + dialog.generateShips(player); + } + IIPlayer.autoGenerateShips(); + + PaintFieldInPlay play = new PaintFieldInPlay(player, IIPlayer); + boolean whoCanGo = true; + play.paintFields(); + do { + if (whoCanGo) { + Speaker.voice("queuePlayer"); + String shot1 = dialog.shotPlayer(IIPlayer); + Speaker.voice("shot", shot1); + + if ("Hit! And Kill!".equals(shot1)||"Hit!".equals(shot1)) { + whoCanGo = true; + } else { + whoCanGo = false; + } + } else { + Thread.sleep(1000); + String shot2 = player.autoShot(); + Speaker.voice("queueII", shot2); + + if ("Hit! And Kill!".equals(shot2)||"Hit!".equals(shot2)) { + whoCanGo = false; + } else { + whoCanGo = true; + } + Thread.sleep(1000); + } + Thread.sleep(1000); + play.paintFields(); + } while (!player.lose() && !IIPlayer.lose()); + + if (player.lose()) { + Speaker.voice("lose1", player.getName()); + } else Speaker.voice("lose1", IIPlayer.getName()); + + } catch (Exception e) { + System.out.println(e + " FAIL"); + } + } +} diff --git a/src/main/java/course_project/sea_battle/model/CoordinateTranslator.java b/src/main/java/course_project/sea_battle/model/CoordinateTranslator.java new file mode 100644 index 00000000..cd9ff996 --- /dev/null +++ b/src/main/java/course_project/sea_battle/model/CoordinateTranslator.java @@ -0,0 +1,25 @@ +package course_project.sea_battle.model; + +import java.util.HashMap; +import java.util.Map; + +public class CoordinateTranslator { + private static final Map coordinateTranslatorMap; + static { + coordinateTranslatorMap = new HashMap<>(); + coordinateTranslatorMap.put("a", 0); + coordinateTranslatorMap.put("b", 1); + coordinateTranslatorMap.put("c", 2); + coordinateTranslatorMap.put("d", 3); + coordinateTranslatorMap.put("e", 4); + coordinateTranslatorMap.put("f", 5); + coordinateTranslatorMap.put("g", 6); + coordinateTranslatorMap.put("h", 7); + coordinateTranslatorMap.put("i", 8); + coordinateTranslatorMap.put("j", 9); + } + public static int coordinate(String key){ + if(key == null) return 10; + return coordinateTranslatorMap.get(key); + } +} diff --git a/src/main/java/course_project/sea_battle/model/Field.java b/src/main/java/course_project/sea_battle/model/Field.java new file mode 100644 index 00000000..cc46f98c --- /dev/null +++ b/src/main/java/course_project/sea_battle/model/Field.java @@ -0,0 +1,214 @@ +package course_project.sea_battle.model; + +import course_project.sea_battle.service.ComputeHelper; + +import java.util.*; + +public class Field { + + private int[][] field; + private ShipsGame ships; + List autoShotsMap; + + public Field(int sizeA, int sizeB) { + field = new int[sizeA][sizeB]; + for (int i = 0; i < sizeA; i++) { + for (int j = 0; j < sizeB; j++) { + field[i][j] = 0; + } + } + ships = new ShipsGame(); + autoShotsMap = new ArrayList<>(); + } + + public String addShip(Ship ship) { + if (!canAddThisSize(ship.getSize())) { + return "sizeShipBad"; + } + + int pointA = ship.getStartPositionA(); + int pointB = ship.getStartPositionB(); + int size = ship.getSize(); + boolean orient = ship.getOrientation(); + + if (!correct(pointA, pointB, size, orient)) return "coordinateFalse"; + + List list = new ArrayList<>(); + for (int i = 0; i < ship.getSize(); i++) { + if (ship.getOrientation()) { + if (!ComputeHelper.chekCanPutShip(pointA + i, pointB, field)) return "fieldNotEmpty"; + list.add(new Integer[]{pointA + i, pointB}); + } else { + if (!ComputeHelper.chekCanPutShip(pointA, pointB + i, field)) return "fieldNotEmpty"; + list.add(new Integer[]{pointA, pointB + i}); + } + } + for (Integer[] list1 : list) { + int posA = list1[0]; + int posB = list1[1]; + field[posA][posB] = 5; + } + return ships.addShip(ship) ? "correct" : "coordinateFalse"; + } + + private boolean correct(int startPointA, int startPointB, int sizeField, boolean orientation) { + if (startPointA < 0 || startPointB < 0 || startPointA > 9 || startPointB > 9 || sizeField < 1 || sizeField >= 5) + return false; + if (orientation && field.length < startPointA + sizeField ) + return false; + if (!orientation && field.length < startPointB + sizeField) + return false; + return true; + } + + public int[][] getField() { + return field; + } + + public boolean readyToGame() { + return ships.ready(); + } + + public int getSize() { + return field.length; + } + + public String shot(String shot) { + String[] shots = shot.toLowerCase(Locale.ROOT).split(" "); + int pointA = Integer.parseInt(shots[0]) - 1; + int pointB = CoordinateTranslator.coordinate(shots[1].toLowerCase(Locale.ROOT)); + return shotResult(pointA, pointB); + } + + private void missAroundDeadShip(Ships ship) { + int positionA = ship.getStartPositionA(); + int positionB = ship.getStartPositionB(); + + if (ship.getOrientation()) { + for (; positionA < ship.getStartPositionA() + ship.getSize(); positionA++) { + addMissAroundPoint(positionA, positionB); + } + } else { + for (; positionB < ship.getStartPositionB() + ship.getSize(); positionB++) { + addMissAroundPoint(positionA, positionB); + } + } + } + + private void addMissAroundPoint(int positionA, int positionB) { + missAroundDeadShipLeft(positionA, positionB); + missAroundDeadShipRight(positionA, positionB); + missAroundDeadShipUp(positionA, positionB); + missAroundDeadShipDown(positionA, positionB); + } + + public boolean shipsDead() { + return ships.shipsDead(); + } + + public void autoGenerateShips() { + while (!ships.ready()) { + boolean orientation = new Random().nextInt(2) == 0; + int x = new Random().nextInt(10); + int y = new Random().nextInt(10); + int size = new Random().nextInt(4) + 1; + if (ships.canAddThisSize(size)) { + addShip(new Ship(orientation, x, y, size)); + } + } + } + + public boolean canAddThisSize(int size) { + return ships.canAddThisSize(size); + } + + public String autoShot() { + int pointA = new Random().nextInt(10); + int pointB = new Random().nextInt(10); + + while (autoShotsMap.contains(String.valueOf(pointA) + String.valueOf(pointB))) { + pointA = new Random().nextInt(10); + pointB = new Random().nextInt(10); + } + autoShotsMap.add(String.valueOf(pointA) + String.valueOf(pointB)); + return shotResult(pointA, pointB); + } + + private void missAroundDeadShipDown(int posA, int posB) { + if (posB - 1 >= 0 && field[posA][posB - 1] == 0) { + setPointInField(posA, posB - 1, 3); + } + if (posB - 1 >= 0 && posA - 1 >= 0 && field[posA - 1][posB - 1] == 0) { + setPointInField(posA - 1, posB - 1, 3); + } + if (posB - 1 >= 0 && posA + 1 < 10 && field[posA + 1][posB - 1] == 0) { + setPointInField(posA + 1, posB - 1, 3); + } + } + + private void missAroundDeadShipLeft(int posA, int posB) { + if (posA - 1 >= 0 && field[posA - 1][posB] == 0) { + setPointInField(posA - 1, posB, 3); + } + if (posA - 1 >= 0 && posB - 1 >= 0 && field[posA - 1][posB - 1] == 0) { + setPointInField(posA - 1, posB - 1, 3); + } + if (posA - 1 >= 0 && posB + 1 < 10 && field[posA - 1][posB + 1] == 0) { + setPointInField(posA - 1, posB + 1, 3); + } + } + + private void missAroundDeadShipRight(int posA, int posB) { + if (posA + 1 < 10 && field[posA + 1][posB] == 0) { + setPointInField(posA + 1, posB, 3); + } + if (posA + 1 < 10 && posB + 1 < 10 && field[posA + 1][posB + 1] == 0) { + setPointInField(posA + 1, posB + 1, 3); + } + } + + private void missAroundDeadShipUp(int posA, int posB) { + if (posB + 1 < 10 && field[posA][posB + 1] == 0) { + setPointInField(posA, posB + 1, 3); + } + } + + private void setPointInField(int pointA, int pointB, int in) { + if (pointA >= 0 && pointB >= 0 && pointA < 10 && pointB < 10) { + field[pointA][pointB] = in; + autoShotsMap.add(String.valueOf(pointA) + String.valueOf(pointB)); + } + } + + private boolean checkPointField(int pointA, int pointB, int checked) { + return field[pointA][pointB] == checked; + } + + private String shotResult(int pointA, int pointB) { + if (checkPointField(pointA, pointB, 0) || checkPointField(pointA, pointB, 5)) { + for (Ships ship : ships.getAllShips()) { + if (ship.shot(pointA, pointB)) { + setPointInField(pointA, pointB, 7); + if (ship.isDead()) { + missAroundDeadShip(ship); + return "Hit! And Kill!"; + } + return "Hit!"; + } + } + setPointInField(pointA, pointB, 3); + return "Miss"; + } else { + return "repeatShot"; + } + } + + @Override + public String toString() { + return "Field{" + + "field=" + Arrays.toString(field) + + ", ships=" + ships + + ", autoShotsMap=" + autoShotsMap + + '}'; + } +} diff --git a/src/main/java/course_project/sea_battle/model/ModelPlayer.java b/src/main/java/course_project/sea_battle/model/ModelPlayer.java new file mode 100644 index 00000000..7f8d4ada --- /dev/null +++ b/src/main/java/course_project/sea_battle/model/ModelPlayer.java @@ -0,0 +1,52 @@ +package course_project.sea_battle.model; + +public class ModelPlayer { + + String name; + Field playerField; + + public ModelPlayer(String name, Field playerField) { + this.name = name; + this.playerField = playerField; + } + + public String getName() { + return name; + } + + public Field getPlayerField() { + return playerField; + } + + public String addShip(Ship ship) { + return playerField.addShip(ship); + } + + public boolean readyToGame() { + return playerField.readyToGame(); + } + + public String shot(String shot){ + return playerField.shot(shot); + } + + public boolean lose() { + return playerField.shipsDead(); + } + + public void autoGenerateShips() { + playerField.autoGenerateShips(); + } + + public String autoShot(){ + return playerField.autoShot(); + } + + @Override + public String toString() { + return "ModelPlayer{" + + "name='" + name + '\'' + + ", playerField=" + playerField + + '}'; + } +} diff --git a/src/main/java/course_project/sea_battle/model/Ship.java b/src/main/java/course_project/sea_battle/model/Ship.java new file mode 100644 index 00000000..bdce9472 --- /dev/null +++ b/src/main/java/course_project/sea_battle/model/Ship.java @@ -0,0 +1,81 @@ +package course_project.sea_battle.model; + +public class Ship implements Ships { + + private final boolean orientation; + private final int startPositionA; + private final int startPositionB; + private final int size; + private int damage; + + public Ship(boolean orientation, int startPositionA, int startPositionB, int size) { + this.orientation = orientation; + this.startPositionA = startPositionA; + this.startPositionB = startPositionB; + this.size = size; + this.damage = 0; + } + + @Override + public int getStartPositionA() { + return startPositionA; + } + + @Override + public int getStartPositionB() { + return startPositionB; + } + + @Override + public boolean isDead() { + return size==damage; + } + + @Override + public boolean getOrientation() { + return orientation; + } + + @Override + public int getSize() { + return size; + } + + @Override + public boolean shot(int pointA, int pointB) { + boolean damageThis = false; + if(getOrientation()){ + for(int i = startPositionA; i speaker; + + static { + speaker = new HashMap<>(); + speaker.put("shotHit", "Hit!"); + speaker.put("shotMiss", "Miss!"); + speaker.put("coordinateFalse", "Not correct coordinates! Try again."); + speaker.put("dialogName", "Write you Name, cap:"); + speaker.put("lose1", "LOSE"); + speaker.put("win", "Winner: "); + speaker.put("correct", "Successfully"); + speaker.put("error", "ERROR:"); + speaker.put("shot", "Player shot:"); + speaker.put("autoGenerate", "Do you want to automatically arrange the ships?\nPress Y-yes/N-no"); + speaker.put("notCorrect", "Not correct data"); + speaker.put("queuePlayer", "You turn, press number, a space and letter:"); + speaker.put("queueII", "Turn Bot!"); + speaker.put("repeatShot", "Repeat shot;-)))"); + speaker.put("fieldNotEmpty", "This coordinate is occupied by another ship"); + speaker.put("sizeShipBad", "you can't create a ship of this size"); + speaker.put("inputInstruction", "The first element is the location of the ship vertically - 1 horizontally-2.\n" + + "Then a space, coordinates of the first number, a space, a letter.\n" + + "Space, the length of the ship. input."); +} + + public static void voice(String dialogName) { + System.out.println(speaker.get(dialogName)); + } + public static void voice(String dialogName, String add) { + System.out.println(speaker.get(dialogName) + " " + add); + } +} diff --git a/src/main/java/homework_1/Main.java b/src/main/java/homework_1/Main.java index 07c029a2..ef455615 100644 --- a/src/main/java/homework_1/Main.java +++ b/src/main/java/homework_1/Main.java @@ -2,8 +2,18 @@ public class Main { - public static void main(String[] args) { - System.out.println("Hello homework!"); - } + public static final String RED_COLOR = "\u001B[31m"; + public static final String CLOSE_COLOR = "\u001B[0m"; + public static void main(String[] args) { + for (String str : args) { + if (str.equals("ошибка")) { + System.out.println(RED_COLOR + "Тревога!" + CLOSE_COLOR); + break; + } + System.out.println(str + ": " + str.length() + " букв"); + } + + + } } 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..5bdd1d52 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/Main.java @@ -0,0 +1,10 @@ +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..fd0455b4 --- /dev/null +++ b/src/main/java/homework_2/pyramid_printer/PyramidPrinter.java @@ -0,0 +1,28 @@ +package homework_2.pyramid_printer; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +public class PyramidPrinter { + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + int x = Integer.parseInt(reader.readLine()); + if (x <= 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } + printPyramid(x); + } catch (Exception e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + } + } + + public static void printPyramid(int score) { + for (int i = 1; i <= score; 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..24ca0405 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/Main.java @@ -0,0 +1,10 @@ +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..64b83d42 --- /dev/null +++ b/src/main/java/homework_2/random_chars_table/RandomCharsTable.java @@ -0,0 +1,84 @@ +package homework_2.random_chars_table; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public class RandomCharsTable { + public void run() { + int x; + int y; + String word; + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + + String[] str = reader.readLine().split(" "); + x = Integer.parseInt(str[0]); + y = Integer.parseInt(str[1]); + word = str[2]; + + if (x < 1 || y < 1 || !(word.equals("even") || word.equals("odd")) || str.length > 3) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + return; + } + + } catch (Exception e) { + System.out.println("Passed parameters should match the format [positive integer] [positive integer] [even|odd]"); + return; + } + + char[][] table = new char[x][y]; + ArrayList words = new ArrayList<>(); + + for (int i = 0; i < x; i++) { + for (int j = 0; j < y; j++) { + int helper = getRandomNumber(); + table[i][j] = (char) helper; + words.add(helper); + } + } + + printTable(table, x, y); + + if (word.equals("even")) { + System.out.println(getResultChar(words, true)); + } + if (word.equals("odd")) { + System.out.println(getResultChar(words, false)); + } + } + + public static int getRandomNumber() { + return (int) ((Math.random() * ('Z' - 'A')) + 'A'); + } + + public static String getResultChar(ArrayList words, boolean even) { + String result; + Predicate predicate; + if (even) { + result = "Even letters - "; + predicate = i -> i % 2 == 0; + } else { + result = "Odd letters - "; + predicate = i -> i % 2 == 1; + } + result += words.stream().filter(predicate) + .distinct() + .map(i -> String.valueOf((char) i.intValue())) + .collect(Collectors.joining(", ")) + .trim(); + return result; + } + + public void printTable(char[][] table, int x, int y) { + for (int i = 0; i < x; i++) { + for (int j = 0; j < y; j++) { + System.out.print("|" + table[i][j]); + } + System.out.print("|"); + System.out.println(); + } + } +} 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..4092147c --- /dev/null +++ b/src/main/java/homework_2/traffic_light/Main.java @@ -0,0 +1,10 @@ +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..921440a5 --- /dev/null +++ b/src/main/java/homework_2/traffic_light/TrafficLight.java @@ -0,0 +1,44 @@ +package homework_2.traffic_light; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class TrafficLight { + + public void run() { + + int seconds; + int result; + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + seconds = Integer.parseInt(reader.readLine()); + + if (seconds > 86399) { + System.out.println("The day is over"); + return; + } + if (seconds < 0) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } + } catch (NumberFormatException | IOException e) { + System.out.println("Only 1 non-negative integer is allowed as passed parameter"); + return; + } + + if (seconds > 60) { + result = seconds % 60; + } else result = seconds; + + if (result < 35) { + System.out.println("GREEN"); + } else if (result < 40) { + System.out.println("YELLOW"); + } else if (result < 55) { + System.out.println("RED"); + } else { + System.out.println("YELLOW"); + } + } +} diff --git a/src/main/java/homework_3/ImmutableClass.java b/src/main/java/homework_3/ImmutableClass.java new file mode 100644 index 00000000..7165d907 --- /dev/null +++ b/src/main/java/homework_3/ImmutableClass.java @@ -0,0 +1,55 @@ +package homework_3; + +/* Requirements for the Immutable Class: + * 1. Class has 2 constructors with 2 required fields + * 2. Fields cannot be changed, you only have geters; + * 3. You can get the same one ImmutableClass with the changed field "three", + * using the method getImmutableClass(). He back new ImmutableClass. + * */ + +public final class ImmutableClass { + + private final int one; + private final String two; + private final Character three; + private final String[] names; + + public ImmutableClass(int one, String two, Character three, String[] names) { + this.one = one; + this.two = two; + this.three = three; + this.names = names; + } + + public int getOne() { + return one; + } + + public String getTwo() { + return two; + } + + public Character getThree() { + return three; + } + + public String[] getNames() { + return names.clone(); + } + + public ImmutableClass getImmutableClass(int one) { + return new ImmutableClass(one, getTwo(), getThree(), getNames()); + } + + public ImmutableClass getImmutableClass(Character someChar) { + if (someChar != null) { + return new ImmutableClass(getOne(), getTwo(), someChar, getNames()); + } else return new ImmutableClass(getOne(), getTwo(), getThree(), getNames()); + } + + public ImmutableClass getImmutableClass(String[] str) { + if (str != null) { + return new ImmutableClass(getOne(), getTwo(), getThree(), str); + } else return new ImmutableClass(getOne(), getTwo(), getThree(), getNames()); + } +} diff --git a/src/main/java/homework_3/Main.java b/src/main/java/homework_3/Main.java new file mode 100644 index 00000000..fecbd499 --- /dev/null +++ b/src/main/java/homework_3/Main.java @@ -0,0 +1,16 @@ +package homework_3; + +import java.util.Arrays; + +public class Main { + public static void main(String[] args) { + ImmutableClass imut = new ImmutableClass(2, "string", 'G', new String[]{"one", "two"}); + String[] b = imut.getNames(); + System.out.println(Arrays.toString(b)); + b[0] = "changes"; + System.out.println(Arrays.toString(b)); + System.out.println(Arrays.toString(imut.getNames())); + + + } +} diff --git a/src/main/java/homework_4/custom_annotation/Main.java b/src/main/java/homework_4/custom_annotation/Main.java new file mode 100644 index 00000000..9d72ac61 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/Main.java @@ -0,0 +1,10 @@ +package homework_4.custom_annotation; + +public class Main { + public static void main(String[] args) { + + MyTestAnnotationClass test = new MyTestAnnotationClass(); + System.out.println(test.getMyName()); + System.out.println(test.getAge()); + } +} diff --git a/src/main/java/homework_4/custom_annotation/MyAnnotation.java b/src/main/java/homework_4/custom_annotation/MyAnnotation.java new file mode 100644 index 00000000..a97a5126 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/MyAnnotation.java @@ -0,0 +1,12 @@ +package homework_4.custom_annotation; + + +import java.lang.annotation.*; + +@Documented +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface MyAnnotation { + String name() default "MySuperName"; + int age() default 2; +} diff --git a/src/main/java/homework_4/custom_annotation/MyTestAnnotationClass.java b/src/main/java/homework_4/custom_annotation/MyTestAnnotationClass.java new file mode 100644 index 00000000..15d808a1 --- /dev/null +++ b/src/main/java/homework_4/custom_annotation/MyTestAnnotationClass.java @@ -0,0 +1,36 @@ +package homework_4.custom_annotation; + +@MyAnnotation +public class MyTestAnnotationClass { + + String myName; + int age; + + public MyTestAnnotationClass() { + myName = getClass().getAnnotation(MyAnnotation.class).name(); + age = this.getClass().getAnnotation(MyAnnotation.class).age(); + } + + public MyTestAnnotationClass(int age) { + myName = getClass().getAnnotation(MyAnnotation.class).name(); + this.age = age; + } + + public MyTestAnnotationClass(String myName) { + this.myName = myName; + age = this.getClass().getAnnotation(MyAnnotation.class).age(); + } + + public MyTestAnnotationClass(String myName, int age) { + this.myName = myName; + this.age = age; + } + + public int getAge() { + return age; + } + + public String getMyName() { + return myName; + } +} 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..597fa6c7 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/CustomFileReader.java @@ -0,0 +1,63 @@ +package homework_4.custom_file_reader; + +import java.io.*; +import java.nio.CharBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +public class CustomFileReader { + private final String filePath = "src/main/resources/custom_file_reader/test_file"; + public void run1() { + if (Files.exists(Paths.get(filePath))) { + try { + byte[] bytes = Files.readAllBytes(Paths.get(filePath)); + String text = new String(bytes, StandardCharsets.UTF_8); + String resul = text.replaceAll("[,.]", ""); + System.out.println(resul); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + + public void run2() throws IOException { + + try(BufferedReader reader = new BufferedReader(new FileReader(filePath))) { + StringBuilder string = new StringBuilder(); + + while (reader.ready()) { + string.append(reader.readLine()).append("\n"); + } + String resul = string.toString().replaceAll("[,.]", ""); + System.out.println(resul); + } + } + + public void run3() throws IOException { + + try(FileReader reader = new FileReader(filePath)) { + StringBuffer stringBuffer = new StringBuffer(); + + while (reader.ready()) { + int scan = reader.read(); + if (scan == ',' || scan == '.') { + + } else { + stringBuffer.append((char) scan); + } + } + System.out.println(stringBuffer); + } + } + + //test helper + public void changeFileText(String text) throws IOException { + try(FileWriter writer = new FileWriter(filePath)) { + if (text == null) return; + writer.write(text); + } + } + +} 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..3376f163 --- /dev/null +++ b/src/main/java/homework_4/custom_file_reader/Main.java @@ -0,0 +1,12 @@ +package homework_4.custom_file_reader; + +import java.io.IOException; + +public class Main { + public static void main(String[] args) throws IOException { + CustomFileReader reader = new CustomFileReader(); + reader.run1(); + reader.run2(); + reader.run3(); + } +} diff --git a/src/main/java/homework_4/singleton/Singleton.java b/src/main/java/homework_4/singleton/Singleton.java new file mode 100644 index 00000000..76ee741f --- /dev/null +++ b/src/main/java/homework_4/singleton/Singleton.java @@ -0,0 +1,16 @@ +package homework_4.singleton; + +public class Singleton { + + private static Singleton singleton; + + private Singleton() { + } + + public static Singleton getInstance() { + if (singleton == null) { + singleton = new Singleton(); + } + return singleton; + } +} 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..80badfa1 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/CustomRegexMatcher.java @@ -0,0 +1,29 @@ +package homework_5.custom_regex_matcher; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class CustomRegexMatcher { + + public void run() { + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + System.out.println("Regex Email: "); + System.out.println(regex(reader.readLine())); + } catch (NullPointerException e) { + System.out.println(regex("")); + } catch (IOException e) { + e.printStackTrace(); + } + } + + private boolean regex(String readLine) { + if (readLine.length() < 3) { + return false; + } + return readLine.matches("(\\w+)@((mail)|(gmail)|(google)|(other)).([a-z]+)"); + } + +} diff --git a/src/main/java/homework_5/custom_regex_matcher/Main.java b/src/main/java/homework_5/custom_regex_matcher/Main.java new file mode 100644 index 00000000..f8b52c06 --- /dev/null +++ b/src/main/java/homework_5/custom_regex_matcher/Main.java @@ -0,0 +1,7 @@ +package homework_5.custom_regex_matcher; + +public class Main { + public static void main(String[] args) { + new CustomRegexMatcher().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/Main.java b/src/main/java/homework_5/power_of_number/Main.java new file mode 100644 index 00000000..930f2040 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/Main.java @@ -0,0 +1,7 @@ +package homework_5.power_of_number; + +public class Main { + public static void main(String[] args) { + new PowerOfNumber().run(); + } +} diff --git a/src/main/java/homework_5/power_of_number/PowerOfNumber.java b/src/main/java/homework_5/power_of_number/PowerOfNumber.java new file mode 100644 index 00000000..0e0d5b39 --- /dev/null +++ b/src/main/java/homework_5/power_of_number/PowerOfNumber.java @@ -0,0 +1,31 @@ +package homework_5.power_of_number; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class PowerOfNumber { + + public void run() { + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { + String[] input = reader.readLine().split(" "); + int a = Integer.parseInt(input[0]); + int b = Integer.parseInt(input[1]); + if (a < 0 || b < 0) { + System.out.println("Only 2 non-negative integers are allowed"); + return; + } + System.out.println(recursion(a, b)); + } catch (NullPointerException | IOException | NumberFormatException e) { + System.out.println("Only 2 non-negative integers are allowed"); + } + } + + private long recursion(int number, int power) { + if (number == 0) return 0; + if (number == 1 || power == 0) return 1; + if (power == 1) return number; + return number * recursion(number, power - 1); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/Main.java b/src/main/java/homework_6/map_problems_generator/Main.java new file mode 100644 index 00000000..4791a749 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/Main.java @@ -0,0 +1,16 @@ +package homework_6.map_problems_generator; + +import java.util.HashMap; + +public class Main { + public static void main(String[] args) { + HashMap myMap = new HashMap<>(); + MapProblemsMutableGenerator mutab = new MapProblemsMutableGenerator("first"); + + myMap.put(mutab, 100); + System.out.println(myMap.get(mutab)); + + mutab.setSomeString("three"); + System.out.println(myMap.get(mutab)); + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java new file mode 100644 index 00000000..bf1e89cd --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsCollisionGenerator.java @@ -0,0 +1,27 @@ +package homework_6.map_problems_generator; + +public class MapProblemsCollisionGenerator { + + private int a; + + public MapProblemsCollisionGenerator(int a) { + this.a = a; + } + + public int getA() { + return a; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsCollisionGenerator that = (MapProblemsCollisionGenerator) o; + return a == that.a; + } + + @Override + public int hashCode() { + return 0; + } +} diff --git a/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java new file mode 100644 index 00000000..8385d788 --- /dev/null +++ b/src/main/java/homework_6/map_problems_generator/MapProblemsMutableGenerator.java @@ -0,0 +1,34 @@ +package homework_6.map_problems_generator; + +import java.util.Objects; + +public class MapProblemsMutableGenerator { + + private String someInt; + + public MapProblemsMutableGenerator(String someInt) { + this.someInt = someInt; + } + + public void setSomeString(String someInt) { + this.someInt = someInt; + } + + @Override + public String toString() { + return String.valueOf(someInt); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MapProblemsMutableGenerator that = (MapProblemsMutableGenerator) o; + return someInt == that.someInt; + } + + @Override + public int hashCode() { + return Objects.hash(someInt); + } +} diff --git a/src/main/java/homework_7/Cat.java b/src/main/java/homework_7/Cat.java new file mode 100644 index 00000000..88cce434 --- /dev/null +++ b/src/main/java/homework_7/Cat.java @@ -0,0 +1,36 @@ +package homework_7; + +public class Cat { + private String name; + private int age; + + public Cat(String name, int age) { + this.name = name; + this.age = age; + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "Cat{" + + "name='" + name + '\'' + + ", age=" + age + + '}'; + } +} diff --git a/src/main/java/homework_7/Kitten.java b/src/main/java/homework_7/Kitten.java new file mode 100644 index 00000000..d58362e9 --- /dev/null +++ b/src/main/java/homework_7/Kitten.java @@ -0,0 +1,25 @@ +package homework_7; + +public class Kitten extends Cat{ + private String nameMother; + + public Kitten(String name, int age, String nameMam) { + super(name, age); + nameMother = nameMam; + } + + public String getNameMother() { + return nameMother; + } + + public void setNameMother(String nameMother) { + this.nameMother = nameMother; + } + + @Override + public String toString() { + return "Kitten{" + + "nameMother='" + nameMother + '\'' + + "} " + super.toString(); + } +} diff --git a/src/main/java/homework_7/KittenToCatFunction.java b/src/main/java/homework_7/KittenToCatFunction.java new file mode 100644 index 00000000..d14706b0 --- /dev/null +++ b/src/main/java/homework_7/KittenToCatFunction.java @@ -0,0 +1,6 @@ +package homework_7; + +@FunctionalInterface +public interface KittenToCatFunction { + Cat grow(Kitten kitten); +} diff --git a/src/main/java/homework_7/Main.java b/src/main/java/homework_7/Main.java new file mode 100644 index 00000000..e66336f1 --- /dev/null +++ b/src/main/java/homework_7/Main.java @@ -0,0 +1,16 @@ +package homework_7; + +public class Main { + public static void main(String[] args) { + Cat cat = new Cat("Myrka", 12); + Kitten tom = new Kitten("Tom", 3, "YYY"); + + KittenToCatFunction kittenToCatFunction = kitten -> new Cat(kitten.getName() + "Cat", kitten.getAge() + 10); + Cat oldTom = kittenToCatFunction.grow(tom); + + System.out.println(cat); + System.out.println(tom); + System.out.println(oldTom); + + } +} diff --git a/src/main/resources/custom_file_reader/test_file b/src/main/resources/custom_file_reader/test_file new file mode 100644 index 00000000..c7838189 --- /dev/null +++ b/src/main/resources/custom_file_reader/test_file @@ -0,0 +1,3 @@ +t.e,,w +r,,3,,,g +a,,,d...3 \ No newline at end of file diff --git a/src/test/java/course_project/sea_battle/model/CoordinateTranslatorTest.java b/src/test/java/course_project/sea_battle/model/CoordinateTranslatorTest.java new file mode 100644 index 00000000..b85c8d56 --- /dev/null +++ b/src/test/java/course_project/sea_battle/model/CoordinateTranslatorTest.java @@ -0,0 +1,56 @@ +package course_project.sea_battle.model; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CoordinateTranslatorTest extends UnitBase { + + @Test + void coordinateTestNull() { + assertEquals(10,CoordinateTranslator.coordinate(null)); + } + @Test + void coordinateTestA() { + assertEquals(0,CoordinateTranslator.coordinate("a")); + } + @Test + void coordinateTestB() { + + assertEquals(1,CoordinateTranslator.coordinate("b")); + } + @Test + void coordinateTestC() { + assertEquals(2,CoordinateTranslator.coordinate("c")); + } + @Test + void coordinateTestD() { + assertEquals(3,CoordinateTranslator.coordinate("d")); + } + @Test + void coordinateTestE() { + assertEquals(4,CoordinateTranslator.coordinate("e")); + } + @Test + void coordinateTestF() { + assertEquals(5,CoordinateTranslator.coordinate("f")); + } + @Test + void coordinateTestG() { + assertEquals(6,CoordinateTranslator.coordinate("g")); + } + @Test + void coordinateTestH() { + assertEquals(7,CoordinateTranslator.coordinate("h")); + } + @Test + void coordinateTestI() { + assertEquals(8,CoordinateTranslator.coordinate("i")); + } + @Test + void coordinateTestJ() { + assertEquals(9,CoordinateTranslator.coordinate("j")); + } + +} \ No newline at end of file diff --git a/src/test/java/course_project/sea_battle/model/FieldTest.java b/src/test/java/course_project/sea_battle/model/FieldTest.java new file mode 100644 index 00000000..e581085a --- /dev/null +++ b/src/test/java/course_project/sea_battle/model/FieldTest.java @@ -0,0 +1,42 @@ +package course_project.sea_battle.model; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class FieldTest extends UnitBase { + + Field field = new Field(10, 10); + @Test + void addShip() { + + assertEquals("correct", field.addShip(new Ship(true, 1,1, 1))); + assertEquals("fieldNotEmpty", field.addShip(new Ship(true, 1,1, 1 ))); + + assertEquals("correct", field.addShip(new Ship(true, 4,4, 4 ))); + assertEquals("sizeShipBad", field.addShip(new Ship(true, 4,2, 4 ))); + + assertEquals("correct", field.addShip(new Ship(false, 9,9, 1 ))); + assertEquals("fieldNotEmpty", field.addShip(new Ship(false, 9,9, 1 ))); + + assertEquals("correct", field.addShip(new Ship(false, 7,7, 2 ))); + assertEquals("fieldNotEmpty", field.addShip(new Ship(false, 7,5, 2))); + } + + @Test + void shot() { + } + + @Test + void autoGenerateShips() { + } + + @Test + void canAddThisSize() { + } + + @Test + void autoShot() { + } +} \ No newline at end of file diff --git a/src/test/java/course_project/sea_battle/model/ModelPlayerTest.java b/src/test/java/course_project/sea_battle/model/ModelPlayerTest.java new file mode 100644 index 00000000..4d446875 --- /dev/null +++ b/src/test/java/course_project/sea_battle/model/ModelPlayerTest.java @@ -0,0 +1,21 @@ +package course_project.sea_battle.model; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ModelPlayerTest extends UnitBase { + + public static ModelPlayer dima = new ModelPlayer("Dima", new Field(10,10)); + + @Test + void getName() { + assertEquals("Dima", dima.getName()); + } + + @Test + void getPlayerField() { + assertEquals(10, dima.getPlayerField().getSize()); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/sea_battle/model/ShipTest.java b/src/test/java/course_project/sea_battle/model/ShipTest.java new file mode 100644 index 00000000..9a7fee2e --- /dev/null +++ b/src/test/java/course_project/sea_battle/model/ShipTest.java @@ -0,0 +1,21 @@ +package course_project.sea_battle.model; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class ShipTest extends UnitBase { + + @Test + void shot() { + Ship ship = new Ship(true, 2, 2, 3); + assertTrue(ship.shot(2, 2)); + assertTrue(ship.shot(3, 2)); + assertTrue(ship.shot(4, 2)); + assertFalse(ship.shot(4, 3)); + assertFalse(ship.shot(2, 3)); + assertFalse(ship.shot(1, 1)); + assertFalse(ship.shot(11, 11)); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/sea_battle/model/ShipsGameTest.java b/src/test/java/course_project/sea_battle/model/ShipsGameTest.java new file mode 100644 index 00000000..11f35dc5 --- /dev/null +++ b/src/test/java/course_project/sea_battle/model/ShipsGameTest.java @@ -0,0 +1,40 @@ +package course_project.sea_battle.model; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class ShipsGameTest extends UnitBase { + ShipsGame shipsGame = new ShipsGame(); + @Test + void getAllShips() { + List list = shipsGame.getAllShips(); + assertEquals(0, list.size()); + } + + @Test + void ready() { + assertFalse(shipsGame.ready()); + } + + @Test + void addShip() { + shipsGame.addShip(new Ship(true, 1 , 1 ,1)); + assertEquals(1, shipsGame.getAllShips().size()); + } + + @Test + void shipsDead() { + assertFalse(shipsGame.shipsDead()); + } + + @Test + void canAddThisSize() { + assertTrue(shipsGame.canAddThisSize(4)); + shipsGame.addShip(new Ship(true, 3 , 3 ,4)); + assertFalse(shipsGame.canAddThisSize(4)); + } +} \ No newline at end of file diff --git "a/src/test/java/course_project/sea_battle/service/\320\241omputeHelperTest.java" "b/src/test/java/course_project/sea_battle/service/\320\241omputeHelperTest.java" new file mode 100644 index 00000000..55034231 --- /dev/null +++ "b/src/test/java/course_project/sea_battle/service/\320\241omputeHelperTest.java" @@ -0,0 +1,33 @@ +package course_project.sea_battle.service; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class СomputeHelperTest extends UnitBase { + + @Test + void chekCanPutShip() { + int[][] field = new int[10][10]; + assertTrue(ComputeHelper.chekCanPutShip(0,0, field)); + assertTrue(ComputeHelper.chekCanPutShip(1,0, field)); + assertTrue(ComputeHelper.chekCanPutShip(0,1, field)); + assertTrue(ComputeHelper.chekCanPutShip(3,0, field)); + field[1][1] = 5; + assertFalse(ComputeHelper.chekCanPutShip(1,0, field)); + assertFalse(ComputeHelper.chekCanPutShip(1,1, field)); + assertFalse(ComputeHelper.chekCanPutShip(0,1, field)); + assertFalse(ComputeHelper.chekCanPutShip(1,2, field)); + + assertTrue(ComputeHelper.chekCanPutShip(5,5, field)); + assertTrue(ComputeHelper.chekCanPutShip(4,6, field)); + assertTrue(ComputeHelper.chekCanPutShip(8,7, field)); + assertTrue(ComputeHelper.chekCanPutShip(7,4, field)); + field[5][6] = 5; + assertFalse(ComputeHelper.chekCanPutShip(5,5, field)); + assertFalse(ComputeHelper.chekCanPutShip(6,6, field)); + assertFalse(ComputeHelper.chekCanPutShip(6,7, field)); + assertFalse(ComputeHelper.chekCanPutShip(6,5, field)); + } +} \ No newline at end of file diff --git a/src/test/java/course_project/sea_battle/view/SpeakerTest.java b/src/test/java/course_project/sea_battle/view/SpeakerTest.java new file mode 100644 index 00000000..14ac0329 --- /dev/null +++ b/src/test/java/course_project/sea_battle/view/SpeakerTest.java @@ -0,0 +1,99 @@ +package course_project.sea_battle.view; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SpeakerTest extends UnitBase { + + @Test + void printTestHit() { + Speaker.voice("shotHit"); + assertEquals("Hit!", getOutputLines()[0]); + } + @Test + void printTestMiss() { + Speaker.voice("shotMiss"); + assertEquals("Miss!", getOutputLines()[0]); + } + @Test + void printTestNotCorrectCoordinate() { + Speaker.voice("coordinateFalse"); + assertEquals("Not correct coordinates! Try again.", getOutputLines()[0]); + } + @Test + void printTestWriteYouName() { + Speaker.voice("dialogName"); + assertEquals("Write you Name, cap:", getOutputLines()[0]); + } + @Test + void printTestLose() { + Speaker.voice("lose1"); + assertEquals("LOSE", getOutputLines()[0]); + } + @Test + void printTestWin() { + Speaker.voice("win"); + assertEquals("Winner:", getOutputLines()[0]); + } + @Test + void printTestSuccessfully() { + Speaker.voice("correct"); + assertEquals("Successfully", getOutputLines()[0]); + } + @Test + void printTestError() { + Speaker.voice("error"); + assertEquals("ERROR:", getOutputLines()[0]); + } + @Test + void printTestShot() { + Speaker.voice("shot"); + assertEquals("Player shot:", getOutputLines()[0]); + } + @Test + void printTestQuestionPressYOrN() { + Speaker.voice("autoGenerate"); + assertEquals("Do you want to automatically arrange the ships?", getOutputLines()[0]); + assertEquals("Press Y-yes/N-no", getOutputLines()[1]); + } + @Test + void printTestNotCorrectData() { + Speaker.voice("notCorrect"); + assertEquals("Not correct data", getOutputLines()[0]); + } + @Test + void printTestYouTurn() { + Speaker.voice("queuePlayer"); + assertEquals("You turn, press number, a space and letter:", getOutputLines()[0]); + } + @Test + void printTestTurnBot() { + Speaker.voice("queueII"); + assertEquals("Turn Bot!", getOutputLines()[0]); + } + @Test + void printTestReapeatShot() { + Speaker.voice("repeatShot"); + assertEquals("Repeat shot;-)))", getOutputLines()[0]); + } + @Test + void printTestThisCoordinateIsOccupied() { + Speaker.voice("fieldNotEmpty"); + assertEquals("This coordinate is occupied by another ship", getOutputLines()[0]); + } + @Test + void printTestYouNotCanCreateShip() { + Speaker.voice("sizeShipBad"); + assertEquals("you can't create a ship of this size", getOutputLines()[0]); + } + @Test + void printTestFirstElementLocation() { + Speaker.voice("inputInstruction"); + assertEquals("The first element is the location of the ship vertically - 1 horizontally-2.", getOutputLines()[0]); + assertEquals("Then a space, coordinates of the first number, a space, a letter.", getOutputLines()[1]); + assertEquals("Space, the length of the ship. input.", getOutputLines()[2]); + } + +} \ 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..2e1fee9f --- /dev/null +++ b/src/test/java/homework_2/pyramid_printer/PyramidPrinterTest.java @@ -0,0 +1,68 @@ +package homework_2.pyramid_printer; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PyramidPrinterTest extends UnitBase { + + @Test + void given_not_correct() { + setInput("tjtjs"); + + new PyramidPrinter().run(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void given_empty() { + setInput(""); + + new PyramidPrinter().run(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void given_big_integer() { + setInput("4236262634264754"); + + new PyramidPrinter().run(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void given_negative_integer() { + setInput("-1"); + + new PyramidPrinter().run(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void given_0() { + setInput("0"); + + new PyramidPrinter().run(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void given_1() { + setInput("1"); + + new PyramidPrinter().run(); + assertEquals("x", getOutputLines()[0]); + } + + @Test + void given_4() { + setInput("4"); + + new PyramidPrinter().run(); + assertEquals("x", getOutputLines()[0]); + assertEquals("xx", getOutputLines()[1]); + assertEquals("xxx", getOutputLines()[2]); + assertEquals("xxxx", getOutputLines()[3]); + } +} \ 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..efe4846c --- /dev/null +++ b/src/test/java/homework_2/random_chars_table/RandomCharsTableTest.java @@ -0,0 +1,68 @@ +package homework_2.random_chars_table; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; + +import static org.junit.jupiter.api.Assertions.*; + +class RandomCharsTableTest extends UnitBase { + + @Test + void given_first_bad() { + setInput("-1 1 even"); + + new RandomCharsTable().run(); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + + @Test + void given_second_bad() { + setInput("1 -31 odd"); + + new RandomCharsTable().run(); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + + @Test + void given_last_bad() { + setInput("1 -3 dfsdf"); + + new RandomCharsTable().run(); + assertEquals("Passed parameters should match the format [positive integer] [positive integer] [even|odd]", getOutputLines()[0]); + } + + @Test + void getResultCharTestEven() { + ArrayList array = new ArrayList<>(); + array.add(66); + array.add(86); + array.add(77); + array.add(88); + + assertEquals("Even letters - B, V, X", RandomCharsTable.getResultChar(array, true)); + } + + @Test + void getResultCharTestOdd() { + ArrayList array = new ArrayList<>(); + array.add(69); + array.add(67); + array.add(77); + array.add(88); + + assertEquals("Odd letters - E, C, M", RandomCharsTable.getResultChar(array, false)); + } + + @Test + void printTableTest() { + char[][] table = {{'H', 'A'}, {'F', 'T'}}; + + RandomCharsTable randomCharsTable = new RandomCharsTable(); + randomCharsTable.printTable(table, 2, 2); + + assertEquals("|H|A|", getOutputLines()[0]); + assertEquals("|F|T|", getOutputLines()[1]); + } +} \ 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..097e1ef3 --- /dev/null +++ b/src/test/java/homework_2/traffic_light/TrafficLightTest.java @@ -0,0 +1,65 @@ +package homework_2.traffic_light; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TrafficLightTest extends UnitBase { + + @Test + void input_negative_6(){ + setInput("-6"); + + new TrafficLight().run(); + assertEquals("Only 1 non-negative integer is allowed as passed parameter", getOutputLines()[0]); + } + + @Test + void input_0(){ + setInput("0"); + + new TrafficLight().run(); + assertEquals("GREEN", getOutputLines()[0]); + } + + @Test + void input_5(){ + setInput("5"); + + new TrafficLight().run(); + assertEquals("GREEN", getOutputLines()[0]); + } + + @Test + void input_35(){ + setInput("35"); + + new TrafficLight().run(); + assertEquals("YELLOW", getOutputLines()[0]); + } + + @Test + void input_55(){ + setInput("54"); + + new TrafficLight().run(); + assertEquals("RED", getOutputLines()[0]); + } + + @Test + void input_86401(){ + setInput("86401"); + + new TrafficLight().run(); + assertEquals("The day is over", getOutputLines()[0]); + } + + @Test + void input_86466(){ + setInput("86466"); + + new TrafficLight().run(); + assertEquals("The day is over", getOutputLines()[0]); + } +} diff --git a/src/test/java/homework_4/custom_annotation/MyTestAnnotationClassTest.java b/src/test/java/homework_4/custom_annotation/MyTestAnnotationClassTest.java new file mode 100644 index 00000000..c9746d3e --- /dev/null +++ b/src/test/java/homework_4/custom_annotation/MyTestAnnotationClassTest.java @@ -0,0 +1,35 @@ +package homework_4.custom_annotation; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class MyTestAnnotationClassTest extends UnitBase { + + @Test + void Empty_Const() { + MyTestAnnotationClass myClass = new MyTestAnnotationClass(); + assertEquals("MySuperName", myClass.getMyName()); + assertEquals(2, myClass.getAge()); + } + + @Test + void Name_Const() { + MyTestAnnotationClass myClass = new MyTestAnnotationClass("Stepan"); + assertEquals("Stepan", myClass.getMyName()); + assertEquals(2, myClass.getAge()); + } + @Test + void Age_Const() { + MyTestAnnotationClass myClass = new MyTestAnnotationClass(44); + assertEquals("MySuperName", myClass.getMyName()); + assertEquals(44, myClass.getAge()); + } + @Test + void Full_Const() { + MyTestAnnotationClass myClass = new MyTestAnnotationClass("Anna", 33); + assertEquals("Anna", myClass.getMyName()); + assertEquals(33, myClass.getAge()); + } +} \ 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..45deba91 --- /dev/null +++ b/src/test/java/homework_4/custom_file_reader/CustomFileReaderTest.java @@ -0,0 +1,44 @@ +package homework_4.custom_file_reader; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomFileReaderTest extends UnitBase { + + @Test + void test() throws IOException { + CustomFileReader reader = new CustomFileReader(); + String text = "t.e,,w\nr,,3,,,g\na,,,d...3"; + reader.changeFileText(text); + reader.run1(); + assertEquals("tew", getOutputLines()[0]); + assertEquals("r3g", getOutputLines()[1]); + assertEquals("ad3", getOutputLines()[2]); + reader.run2(); + assertEquals("tew", getOutputLines()[0]); + assertEquals("r3g", getOutputLines()[1]); + assertEquals("ad3", getOutputLines()[2]); + reader.run3(); + assertEquals("tew", getOutputLines()[0]); + assertEquals("r3g", getOutputLines()[1]); + assertEquals("ad3", getOutputLines()[2]); + } + + @Test + void text_empty () throws IOException { + CustomFileReader reader = new CustomFileReader(); + String text = ""; + reader.changeFileText(text); + reader.run1(); + assertEquals("", getOutputLines()[0]); + reader.run2(); + assertEquals("", getOutputLines()[0]); + reader.run3(); + assertEquals("", getOutputLines()[0]); + } + +} \ 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..d44ab3f3 --- /dev/null +++ b/src/test/java/homework_4/singleton/SingletonTest.java @@ -0,0 +1,17 @@ +package homework_4.singleton; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SingletonTest extends UnitBase { + + @Test + void equals_Singleton(){ + Singleton singleton1 = Singleton.getInstance(); + Singleton singleton2 = Singleton.getInstance(); + assertEquals(singleton1, singleton2); + } + +} \ 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..ca581acf --- /dev/null +++ b/src/test/java/homework_5/custom_regex_matcher/CustomRegexMatcherTest.java @@ -0,0 +1,78 @@ +package homework_5.custom_regex_matcher; + +import base.UnitBase; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class CustomRegexMatcherTest extends UnitBase { + @Test + void zero_test() { + setInput(""); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void one_test() { + setInput("1"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void normal_test() { + setInput("t@mail.com"); + new CustomRegexMatcher().run(); + assertEquals("true", getOutputLines()[1]); + } + + @Test + void address_bad_test1() { + setInput("t@mai.com"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void address_bad_test2() { + setInput("h55t@mail.44tm"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void address_bad_test3() { + setInput("4hht@mai.com"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void address_bad_test4() { + setInput("@mai.com"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void address_bad_test5() { + setInput("mai.comdfdf@frg"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void address_bad_test6() { + setInput("maic@@mail.com"); + new CustomRegexMatcher().run(); + assertEquals("false", getOutputLines()[1]); + } + + @Test + void address_bad_test7() { + setInput("maic@mail..com"); + new CustomRegexMatcher().run(); + assertEquals("false", 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..7ab2022e --- /dev/null +++ b/src/test/java/homework_5/power_of_number/PowerOfNumberTest.java @@ -0,0 +1,79 @@ +package homework_5.power_of_number; + +import base.UnitBase; +import homework_5.custom_regex_matcher.CustomRegexMatcher; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PowerOfNumberTest extends UnitBase { + @Test + void zero_test() { + setInput(""); + new PowerOfNumber().run(); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void bad_test() { + setInput("546 ftd"); + new PowerOfNumber().run(); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void negative_test() { + setInput("-3 3"); + new PowerOfNumber().run(); + assertEquals("Only 2 non-negative integers are allowed", getOutputLines()[0]); + } + + @Test + void zero_one_test() { + setInput("0 1"); + new PowerOfNumber().run(); + assertEquals("0", getOutputLines()[0]); + } + + @Test + void one_one_test() { + setInput("1 1"); + new PowerOfNumber().run(); + assertEquals("1", getOutputLines()[0]); + } + + @Test + void one_ten_test() { + setInput("1 10"); + new PowerOfNumber().run(); + assertEquals("1", getOutputLines()[0]); + } + + @Test + void two_two_test() { + setInput("2 2"); + new PowerOfNumber().run(); + assertEquals("4", getOutputLines()[0]); + } + + @Test + void two_four_test() { + setInput("2 4"); + new PowerOfNumber().run(); + assertEquals("16", getOutputLines()[0]); + } + + @Test + void ten_two_test() { + setInput("10 2"); + new PowerOfNumber().run(); + assertEquals("100", getOutputLines()[0]); + } + + @Test + void ten_three_test() { + setInput("10 3"); + new PowerOfNumber().run(); + assertEquals("1000", getOutputLines()[0]); + } +} \ No newline at end of file