Files
profi/stars/Main.kt
T
2026-09-11 15:55:42 +03:00

286 lines
13 KiB
Kotlin

// Класс для храниения звезд
data class Star (val identifier: Int,
val constellation: Int,
val name: String,
val description: String,
val coordinates: List<Int>,
val size: Double)
// Класс для хранения созвездий
data class Constellation (val identifier: Int,
val name: String,
var description: String)
// Пробная звезда
val starFirst = Star(1,1,
"Бетельгейзе",
"Яркий красный сверхгигант на правом плече Охотника. Полурегулярная переменная звезда, находящаяся на поздней стадии эволюции.",
listOf(1,1),
877.0
)
// Пробное созвездие
val constellationFirst = Constellation(1, "Орион",
"одно из самых ярких и узнаваемых созвездий на ночном небе, расположенное в области небесного экватора")
// Списки для храниения звезд и созвездий
val stars = mutableListOf(starFirst,
Star(2,1,
"Бетельгейзе2",
"Яркий красный сверхгигант на правом плече Охотника. Полурегулярная переменная звезда, находящаяся на поздней стадии эволюции.",
listOf(5,17),
60.0
),
Star(3,1,
"Бетельгейзе3",
"Яркий красный сверхгигант на правом плече Охотника. Полурегулярная переменная звезда, находящаяся на поздней стадии эволюции.",
listOf(15,29),
5.0
),
Star(4,2,
"Бетельгейзе4",
"Яркий красный сверхгигант на правом плече Охотника. Полурегулярная переменная звезда, находящаяся на поздней стадии эволюции.",
listOf(1,29),
960.0
))
val constellations = mutableListOf(constellationFirst)
// Функция вывода информации о звезде
fun printStarInfo(star: Star){
println("${star.name} ${star.constellation} ${star.description.take(30)}")
}
fun printConstellationInfo(constellation: Constellation){
println("${constellation.name} ${stars.count{it.constellation == constellation.identifier}} ${constellation.description.take(30)}")
}
fun getConstellation(): String{
println("Введите созвездие:")
val constellationsList = constellations.map { it.name }
var constellationName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (constellationName in constellationsList){
break
}
println("Список созвездий: ${constellationsList.joinToString(", ")}")
constellationName = readln().lowercase().replaceFirstChar { it.uppercase() }
}
return constellationName
}
// Главная функция
fun main(){
// Главное меню
println("Меню")
println("1. Вывести все звезды")
println("2. Вывести все созвездия")
println("3. Вывести звездную карту")
println("4. Изменить созвездие")
println("5. Удалить созвездие (вместе со звездами)")
println("6. Выйти из программы")
println("Выберете цифру из меню: ")
while (true){
// Получаем ввод
val input = readln()
when (input){
"1" -> {
// Перебираем все звезды и выводим информацию о них
stars.forEach { printStarInfo(it)}
}
"2" -> {
// Перебираем все созвездия и выводим информацию о них
constellations.forEach { printConstellationInfo(it)}
}
"3" -> {
val map = Array(30) { CharArray(30) { ' ' }}
for (star in stars){
val symbol = when {
star.size > 500.0 -> '★'
star.size > 50.0 -> '✦'
else -> '•'
}
map[star.coordinates[0]][star.coordinates[1]] = symbol
}
for (row in map) {
println(row.joinToString(" "))
}
}
"4" -> {
while (true) {
println("Меню")
println("a. Добавить новую звезду в созвездие")
println("b. Изменить описание")
println("c. Удалить звезду по идентификатору")
println("d. Назад")
val input = readln()
when (input) {
"a" -> {
val constellationName = getConstellation()
println("Введите название звезды:")
var starName: String = readln()
while (true) {
if (starName.isNotBlank()) {
break
}
println("Введите название звезды")
starName = readln()
}
println("Введите описание звезды:")
var starDescription: String = readln()
while (true) {
if (starDescription.isNotBlank()) {
break
}
println("Введите описание звезды")
starDescription = readln()
}
println("Введите координаты звезды:")
var starCoordinates = readln().split(" ").mapNotNull { it.toIntOrNull() }
while (true) {
if (starCoordinates.size == 2 && starCoordinates[0] < 30 && starCoordinates[1] < 30) {
break
}
println("Введите координаты через пробел от 0 до 30")
starCoordinates = readln().split(" ").mapNotNull { it.toIntOrNull() }
}
println("Введите размер звезды:")
var starSize: Double? = readln().toDoubleOrNull()
while (true) {
if (starSize != null) {
break
}
println("Введите размер звезды")
starSize = readln().toDoubleOrNull()
}
// Cоздаем id для звезды
val starId:Int = (stars.maxOfOrNull {it.identifier } ?:0) + 1
// Находим id созвездия
val constellationId: Int? = (constellations.firstOrNull {it.name == constellationName})?.identifier
// Создаем звезду
if (constellationId != null) {
stars.add(
Star(
starId,
constellationId,
starName,
starDescription,
starCoordinates,
starSize
)
)
}
// Выводим созданную звезду
print("Создана звезда: ")
val star = stars.firstOrNull {it.identifier == starId}
if (star != null) {
printStarInfo(star)
}
break
}
"b" -> {
val constellationName = getConstellation()
println("Введите новое описание созвездия:")
var constellationDescription: String = readln()
while (true) {
if (constellationDescription.isNotBlank()) {
break
}
println("Введите описание созвездия")
constellationDescription = readln()
}
val constellation = constellations.firstOrNull {it.name == constellationName}
if (constellation != null) {
constellation.description = constellationDescription
print("Измененное созвездие: ")
printConstellationInfo(constellation)
}
break
}
"c" -> {
val constellationName = getConstellation()
println("Введите звезду:")
// Находим id созвездия
val constellationId: Int? = (constellations.firstOrNull {it.name == constellationName})?.identifier
val starsList = stars.filter{it.constellation == constellationId }.map{it.name}
var starName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (starName in starsList){
break
}
println("Список звезд: ${starsList.joinToString(", ")}")
starName = readln().lowercase().replaceFirstChar { it.uppercase() }
}
println("Вы точно хотите удалить звезду? Y/N")
val input = readln()
if (input in "Yy"){
stars.removeIf{it.name == starName}
println("Звезда успешно удалена")
}
else {
println("Отмена")
}
break
}
"d" -> {
break
}
else -> {
println("Такого нет в меню")
}
}
}
}
"5" -> {
val constellationName = getConstellation()
println("Вы точно хотите удалить созведие и звезды? Y/N")
val input = readln().lowercase()
if (input == "y"){
// Находим id созвездия
val constellationId: Int? = (constellations.firstOrNull {it.name == constellationName})?.identifier
stars.removeIf{it.constellation == constellationId}
constellations.removeIf{it.name == constellationName}
println("Созвездия и звезды успешно удалены")
}
else {
println("Отмена")
}
}
"6" -> {
println("До свидания!")
break
}
else -> {
println("Такого нет в меню")
}
}
}
}