Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/main/java/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
public class Car {
int speed;
String name;
Comment on lines +2 to +3

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поля лучше пометить final, тем самым исключив возможность их модификации извне


public Car(String name, int speed) {
this.name = name;
this.speed = speed;
}
}
78 changes: 75 additions & 3 deletions src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,78 @@

public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
public static void main(String[] args) throws InterruptedException {
showGameStartAnimation();
Race race = new Race();
String raceWinnerName = race.findRaceWinner(race.createRace()).name;
showWinner(raceWinnerName);

}

public static void showWinner(String raceWinnerName) throws InterruptedException {

Thread.sleep(500);

String[] fireworks = {
"🎆 ",
" 🎇 ",
" 🎆 ",
" 🎇",
" 🎆 ",
" 🎇 "
};

for (int i = 0; i < 2; i++) {
for (String fire : fireworks) {
System.out.print("\r" + fire);
Thread.sleep(150);
}
}

System.out.println("\n====================================");
System.out.println("🚗💨 " + raceWinnerName.toUpperCase() + " пересёк финиш первым! 💨🚗");
System.out.println("====================================");


String message = "🏆 П О Б Е Д А ! 🏆";
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
Thread.sleep(120);
}

System.out.println("\n🎇 Поздравляем чемпиона! 🎇");
}
}

public static void showGameStartAnimation() throws InterruptedException {
String[] frames = {
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨",
" 🚗💨"
};
Comment on lines +46 to +57

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Массив можно вынести в константу, чтобы не создавать на каждый вызов функции новый массив


for (String frame : frames) {
System.out.print("\r" + frame);
Thread.sleep(150);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Значение задержки лучше вынести в константу для повышения читабельности кода

}

Thread.sleep(500);

String message = "🚀 И Г Р А Н А Ч А Л А С Ь ! 🚀";
for (int i = 0; i < message.length(); i++) {
System.out.print(message.charAt(i));
Thread.sleep(120);
}

System.out.println("\n===============================");
System.out.println(" Добро пожаловать! ");
System.out.println("===============================");
}

}

67 changes: 67 additions & 0 deletions src/main/java/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import java.util.ArrayList;
import java.util.Scanner;

public class Race {
ArrayList<Car> raceParticipants = new ArrayList<>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

От хранения массива машин и лишнего цикла при определении победителя можно избавиться, если при вводе данных сразу вычислять победителя и хранить его в отдельной переменной, тогда программа будет требовать меньше памяти и работать быстрее


public ArrayList<Car> createRace() {

Scanner scanner = new Scanner(System.in);
String name;
int speed;

for (int i = 1; i < 4; i++) {

while (true) {
Print("Введите название машины №" + i + ":");
name = scanner.nextLine().trim();
if (!name.isEmpty()) {
break;
} else {
Print("Ошибка!!! Имя машины НЕ может быть пустым. Попробуйте снова:");

}
}

while (true) {
Print("Введите скорость машины №" + i + ":");
if (scanner.hasNextInt()) {
speed = scanner.nextInt();
scanner.nextLine();
if (speed > 0 && speed <= 250) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Минимальную и максимальную скорости лучше вынести в константы для повышения читабельности кода

break;
} else {
Print("Ошибка!!! Скорость должна быть от 1 до 250. Попробуйте снова.");
}
} else {
Print("Ошибка!!! Введите целое число!");
scanner.next();
}
}
raceParticipants.add(new Car(name, speed));
}
return raceParticipants;
}

public Car findRaceWinner(ArrayList<Car> participants) {
int maxSpeed = 0;
Car winner = null;
for (Car car : participants) {

if (car.name.equalsIgnoreCase("Lada") || car.name.equalsIgnoreCase("Лада") || car.name.equalsIgnoreCase("Жигули")) {
System.out.println("🚗 " + car.name + " получает бонус! +100 к скорости 💨");
car.speed += 100;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Интересное авторское решение, но от требований все-таки лучше не отходить =)

}

if (car.speed > maxSpeed) {
winner = car;
maxSpeed = car.speed;
}
}
return winner;
}

static void Print(String text) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В джава функции принято именовать с маленькой буквы

System.out.println(text);
}
}