add stars code

This commit is contained in:
2026-09-11 13:49:36 +03:00
commit 71d6d27a2f
+308
View File
@@ -0,0 +1,308 @@
// Класс для храниения звезд
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
))
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 main(){
// Главное меню
println("Меню")
println("1. Вывести все звезды")
println("2. Вывести все созвездия")
println("3. Вывести звездную карту")
println("4. Изменить созвездие")
println("5. Удалить созвездие (вместе со звездами)")
println("6. Выйти из программы")
println("Выберете цифру из меню: ")
while (true){
// Получаем ввод
val input = readln()
when (input){
"1" -> {
// Перебираем все звезды и выводим информацию о них
for (item in stars){
printStarInfo(item)
}
}
"2" -> {
// Перебираем все созвездия и выводим информацию о них
for (item in constellations){
printConstellationInfo(item)
}
}
"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" -> {
println("Введите созвездие:")
val constellationsList = constellations.map { it.name }
var constellationName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (constellationName in constellationsList){
break
}
else {
println("Список созвездий: ${constellationsList.joinToString(", ")}")
}
constellationName = readln().lowercase().replaceFirstChar { it.uppercase() }
}
println("Введите название звезды:")
var starName: String = readln()
while (true) {
if (starName == "" || starName == " ") {
println("Введите название звезды")
}
else {
break
}
starName = readln()
}
println("Введите описание звезды:")
var starDescription: String = readln()
while (true) {
if (starDescription == "" || starDescription == " ") {
println("Введите описание звезды")
}
else {
break
}
starDescription = readln()
}
println("Введите координаты звезды:")
var starCoordinates = readln().split(" ").mapNotNull { it.toIntOrNull() }
while (true) {
if (starCoordinates.size == 2 && starCoordinates[0] < 30 && starCoordinates[1] < 30) {
break
}
else {
println("Введите координаты через пробел от 0 до 30")
}
starCoordinates = readln().split(" ").mapNotNull { it.toIntOrNull() }
}
println("Введите размер звезды:")
var starSize: Double? = readln().toDoubleOrNull()
while (true) {
if (starSize != null) {
break
}
else {
println("Введите размер звезды")
}
starSize = readln().toDoubleOrNull()
}
// Cоздаем id для звезды
val starId:Int = (stars.maxOfOrNull {it.identifier } ?:0) + 1
// Находим id созвездия
val constellationId: Int? = (constellations.find{it.name == constellationName})?.identifier
// Создаем звезду
stars.add(Star(starId,constellationId!!,starName,starDescription,starCoordinates,starSize))
// Выводим созданную звезду
print("Создана звезда: ")
printStarInfo(stars.find {it.identifier == starId}!!)
break
}
"b" -> {
println("Введите созвездие:")
val constellationsList = constellations.map { it.name }
var constellationName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (constellationName in constellationsList){
break
}
else {
println("Список созвездий: ${constellationsList.joinToString(", ")}")
}
constellationName = readln().lowercase().replaceFirstChar { it.uppercase() }
}
println("Введите новое описание созвездия:")
var constellationDescription: String = readln()
while (true) {
if (constellationDescription == "" || constellationDescription == " ") {
println("Введите описание созвездия")
}
else {
break
}
constellationDescription = readln()
}
val constellation = constellations.find{it.name == constellationName}
constellation!!.description = constellationDescription
print("Измененное созвездие: ")
printConstellationInfo(constellation)
break
}
"c" -> {
println("Введите созвездие:")
val constellationsList = constellations.map { it.name }
var constellationName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (constellationName in constellationsList){
break
}
else {
println("Список созвездий: ${constellationsList.joinToString(", ")}")
}
constellationName = readln().lowercase().replaceFirstChar { it.uppercase() }
}
println("Введите звезду:")
val starsList = stars.map { it.name }
var starName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (starName in starsList){
break
}
else {
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" -> {
println("Введите созвездие:")
val constellationsList = constellations.map { it.name }
var constellationName: String = readln().lowercase().replaceFirstChar { it.uppercase() }
while (true) {
if (constellationName in constellationsList){
break
}
else {
println("Список созвездий: ${constellationsList.joinToString(", ")}")
}
constellationName = readln().lowercase().replaceFirstChar { it.uppercase() }
}
println("Вы точно хотите удалить созведие и звезды? Y/N")
val input = readln()
if (input in "Yy"){
// Находим id созвездия
val constellationId: Int? = (constellations.find{it.name == constellationName})?.identifier
stars.removeIf{it.constellation == constellationId}
constellations.removeIf{it.name == constellationName}
println("Созвездия и звезды успешно удалены")
}
else {
println("Отмена")
}
}
"6" -> {
println("До свидания!")
break
}
else -> {
println("Такого нет в меню")
}
}
}
}