Добавил новые работы
@@ -0,0 +1,10 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Ignored default folder with query files
|
||||
/queries/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
@@ -0,0 +1 @@
|
||||
Main.kt
|
||||
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="ReplaceUntilWithRangeUntil" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Kotlin2JvmCompilerArguments">
|
||||
<option name="jvmTarget" value="1.8" />
|
||||
</component>
|
||||
<component name="KotlinCommonCompilerArguments">
|
||||
<option name="apiVersion" value="2.4" />
|
||||
<option name="languageVersion" value="2.4" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
<component name="libraryTable">
|
||||
<library name="KotlinJavaRuntime" type="repository">
|
||||
<properties maven-id="org.jetbrains.kotlin:kotlin-stdlib:2.4.10" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10-javadoc.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10-sources.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
</component>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="graalvm-jdk-21" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/lab-05.iml" filepath="$PROJECT_DIR$/lab-05.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,67 @@
|
||||
# Лабораторная работа №5
|
||||
---
|
||||
|
||||
## Ключевой код
|
||||
```kotlin
|
||||
|
||||
fun main() {
|
||||
println("=== ФОРМИРОВАНИЕ КОЛОДЫ ===")
|
||||
|
||||
val deck: MutableList<String> = mutableListOf()
|
||||
var counter = 1
|
||||
repeat(3) {
|
||||
print("Введите карту №$counter: ")
|
||||
val card = readln()
|
||||
deck.add(card)
|
||||
counter++
|
||||
}
|
||||
|
||||
println("Колода собрана (${deck.size} карт): ${deck.joinToString(", ")}")
|
||||
|
||||
print("Какую карту сбросить? ")
|
||||
val discardedCard = readln()
|
||||
val wasDiscarded = deck.remove(discardedCard)
|
||||
if (wasDiscarded) {
|
||||
println("Карта '$discardedCard' сброшена. Осталось: ${deck.size}")
|
||||
} else {
|
||||
println("Карта '$discardedCard' не найдена в колоде.")
|
||||
}
|
||||
|
||||
println("\n=== АНАЛИЗ РУКИ ===")
|
||||
|
||||
val hand = mapOf(
|
||||
"Pikachu" to "Pokemon",
|
||||
"Potion" to "Trainer",
|
||||
"Fire Energy" to "Energy",
|
||||
"Professor's Research" to "Trainer"
|
||||
)
|
||||
|
||||
val trainerCards = hand.filter {it.value == "Trainer"}
|
||||
val trainerNames = trainerCards.map { it.key }
|
||||
println("Карт Тренеров в руке: ${trainerCards.size} (${trainerNames.joinToString(", ")})")
|
||||
|
||||
val allCards = hand.map {it.key}
|
||||
|
||||
val energyCount = hand.count {it.value == "Energy"}
|
||||
println("Карт энергии в руке: $energyCount")
|
||||
println("Содержимое руки: ${allCards.joinToString(", ")}")
|
||||
|
||||
println("\n=== УЧЕТ РЕСУРСОВ ===")
|
||||
|
||||
print("Сколько энергии прикрепить? ")
|
||||
val energyToAttach = readln().toInt()
|
||||
|
||||
val resources = mutableMapOf("Trainer" to 2, "Energy" to 1)
|
||||
resources["Energy"] = resources.getValue("Energy") + energyToAttach
|
||||
|
||||
println("Ресурсы на столе: ")
|
||||
for ((type, count) in resources) {
|
||||
println("$type: $count шт.")
|
||||
}
|
||||
|
||||
println("\n========================================")
|
||||
println("ИТОГ: Колода: ${deck.size} карт | Рука: ${hand.size} карт | Энергия на столе: ${resources["Energy"]}")
|
||||
println("========================================")
|
||||
}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/testResources" type="java-test-resource" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,59 @@
|
||||
fun main() {
|
||||
println("=== ФОРМИРОВАНИЕ КОЛОДЫ ===")
|
||||
|
||||
val deck: MutableList<String> = mutableListOf()
|
||||
var counter = 1
|
||||
repeat(3) {
|
||||
print("Введите карту №$counter: ")
|
||||
val card = readln()
|
||||
deck.add(card)
|
||||
counter++
|
||||
}
|
||||
|
||||
println("Колода собрана (${deck.size} карт): ${deck.joinToString(", ")}")
|
||||
|
||||
print("Какую карту сбросить? ")
|
||||
val discardedCard = readln()
|
||||
val wasDiscarded = deck.remove(discardedCard)
|
||||
if (wasDiscarded) {
|
||||
println("Карта '$discardedCard' сброшена. Осталось: ${deck.size}")
|
||||
} else {
|
||||
println("Карта '$discardedCard' не найдена в колоде.")
|
||||
}
|
||||
|
||||
println("\n=== АНАЛИЗ РУКИ ===")
|
||||
|
||||
val hand = mapOf(
|
||||
"Pikachu" to "Pokemon",
|
||||
"Potion" to "Trainer",
|
||||
"Fire Energy" to "Energy",
|
||||
"Professor's Research" to "Trainer"
|
||||
)
|
||||
|
||||
val trainerCards = hand.filter {it.value == "Trainer"}
|
||||
val trainerNames = trainerCards.map { it.key }
|
||||
println("Карт Тренеров в руке: ${trainerCards.size} (${trainerNames.joinToString(", ")})")
|
||||
|
||||
val allCards = hand.map {it.key}
|
||||
|
||||
val energyCount = hand.count {it.value == "Energy"}
|
||||
println("Карт энергии в руке: $energyCount")
|
||||
println("Содержимое руки: ${allCards.joinToString(", ")}")
|
||||
|
||||
println("\n=== УЧЕТ РЕСУРСОВ ===")
|
||||
|
||||
print("Сколько энергии прикрепить? ")
|
||||
val energyToAttach = readln().toInt()
|
||||
|
||||
val resources = mutableMapOf("Trainer" to 2, "Energy" to 1)
|
||||
resources["Energy"] = resources.getValue("Energy") + energyToAttach
|
||||
|
||||
println("Ресурсы на столе: ")
|
||||
for ((type, count) in resources) {
|
||||
println("$type: $count шт.")
|
||||
}
|
||||
|
||||
println("\n========================================")
|
||||
println("ИТОГ: Колода: ${deck.size} карт | Рука: ${hand.size} карт | Энергия на столе: ${resources["Energy"]}")
|
||||
println("========================================")
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
### IntelliJ IDEA ###
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Kotlin ###
|
||||
.kotlin
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
@@ -0,0 +1,10 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Ignored default folder with query files
|
||||
/queries/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="ReplaceUntilWithRangeUntil" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Kotlin2JvmCompilerArguments">
|
||||
<option name="jvmTarget" value="1.8" />
|
||||
</component>
|
||||
<component name="KotlinCommonCompilerArguments">
|
||||
<option name="apiVersion" value="2.4" />
|
||||
<option name="languageVersion" value="2.4" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
<component name="libraryTable">
|
||||
<library name="KotlinJavaRuntime" type="repository">
|
||||
<properties maven-id="org.jetbrains.kotlin:kotlin-stdlib:2.4.10" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10-javadoc.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10-sources.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
</component>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" default="true" project-jdk-name="openjdk-27" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/lab-06.iml" filepath="$PROJECT_DIR$/lab-06.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/testResources" type="java-test-resource" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,98 @@
|
||||
|
||||
fun calcDamage(power: Int, multiplier: Double = 1.0): Int = (power * multiplier).toInt()
|
||||
|
||||
fun checkStatus(hp: Int): String {
|
||||
return if (hp > 0) "В строю" else "Нокаут"
|
||||
}
|
||||
|
||||
fun printBattleLog(
|
||||
attacker: String,
|
||||
defender: String,
|
||||
damage: Int
|
||||
): Unit {
|
||||
println("[БОЙ] $attacker атакует $defender и наносит $damage урона!")
|
||||
}
|
||||
|
||||
fun useTrainerCard(
|
||||
cardName: String,
|
||||
healAmount: Int = 20,
|
||||
drawCards: Int = 0
|
||||
): Unit {
|
||||
println(
|
||||
"Применена карта '$cardName': восстанавливает $healAmount HP, " +
|
||||
"берёт карт: $drawCards."
|
||||
)
|
||||
}
|
||||
|
||||
fun processTurn(
|
||||
hp: Int,
|
||||
damage: Int,
|
||||
effect: (Int) -> Int
|
||||
): Int {
|
||||
val remainingHp = hp - damage
|
||||
return effect(remainingHp)
|
||||
}
|
||||
|
||||
fun main() {
|
||||
println("=== ИНИЦИАЛИЗАЦИЯ БОЯ ===")
|
||||
|
||||
print("Введите имя вашего Покемона: ")
|
||||
val pokemonName = readln()
|
||||
|
||||
print("Введите стартовое HP (по умолчанию 60): ")
|
||||
val startHp = readln().toIntOrNull() ?: 60
|
||||
|
||||
println()
|
||||
|
||||
println("=== РАУНД 1: АТАКА И КРАТКИЕ ФУНКЦИИ ===")
|
||||
|
||||
val defender = "Charizard"
|
||||
val baseDamage = 20
|
||||
val weaknessMultiplier = 1.5
|
||||
|
||||
println("Атакующий: $pokemonName | Защищающийся: $defender")
|
||||
println("Базовый урон: $baseDamage | Множитель слабости: $weaknessMultiplier")
|
||||
|
||||
val damage = calcDamage(baseDamage, weaknessMultiplier)
|
||||
printBattleLog(pokemonName, defender, damage)
|
||||
|
||||
val charizardHp = 100 - damage
|
||||
println("Статус $defender: ${checkStatus(charizardHp)}.")
|
||||
|
||||
println()
|
||||
|
||||
println("=== РАУНД 2: ИСПОЛЬЗОВАНИЕ КАРТ (ИМЕНОВАННЫЕ АРГУМЕНТЫ) ===")
|
||||
|
||||
println("Применяем карту Potion:")
|
||||
useTrainerCard("Potion")
|
||||
|
||||
println("Применяем карту Professor's Research (только берутся карты):")
|
||||
useTrainerCard(
|
||||
cardName = "Professor's Research",
|
||||
drawCards = 3
|
||||
)
|
||||
|
||||
println()
|
||||
|
||||
println("=== РАУНД 3: ФУНКЦИЯ ВЫСШЕГО ПОРЯДКА И ЛЯМБДА ===")
|
||||
|
||||
println("$defender наносит ответный урон!")
|
||||
print("Введите полученный $pokemonName урон: ")
|
||||
val receivedDamage = readln().toIntOrNull() ?: 0
|
||||
|
||||
println("Применяем зелье лечения (+15 HP) через лямбда-эффект...")
|
||||
|
||||
val finalHp = processTurn(
|
||||
hp = startHp,
|
||||
damage = receivedDamage,
|
||||
effect = { currentHp -> currentHp + 15 }
|
||||
)
|
||||
|
||||
println("Итоговое HP $pokemonName после атаки и лечения: $finalHp")
|
||||
println("Текущий статус $pokemonName: ${checkStatus(finalHp)}")
|
||||
|
||||
println()
|
||||
println("========================================")
|
||||
println("ИТОГ БОЯ: Бой завершен успешно. Все функции выполнены.")
|
||||
println("========================================")
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
### IntelliJ IDEA ###
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Kotlin ###
|
||||
.kotlin
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
@@ -0,0 +1,10 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# Editor-based HTTP Client requests
|
||||
/httpRequests/
|
||||
# Ignored default folder with query files
|
||||
/queries/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="UserContentModel">
|
||||
<attachedFolders />
|
||||
<explicitIncludes />
|
||||
<explicitExcludes />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="ReplaceUntilWithRangeUntil" enabled="true" level="WEAK WARNING" enabled_by_default="true" />
|
||||
</profile>
|
||||
</component>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Kotlin2JvmCompilerArguments">
|
||||
<option name="jvmTarget" value="1.8" />
|
||||
</component>
|
||||
<component name="KotlinCommonCompilerArguments">
|
||||
<option name="apiVersion" value="2.4" />
|
||||
<option name="languageVersion" value="2.4" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,17 @@
|
||||
<component name="libraryTable">
|
||||
<library name="KotlinJavaRuntime" type="repository">
|
||||
<properties maven-id="org.jetbrains.kotlin:kotlin-stdlib:2.4.10" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10-javadoc.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/kotlin/kotlin-stdlib/2.4.10/kotlin-stdlib-2.4.10-sources.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/org/jetbrains/annotations/13.0/annotations-13.0-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
</component>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" default="true" project-jdk-name="openjdk-27" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/lab-07.iml" filepath="$PROJECT_DIR$/lab-07.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="RiderProjectSettingsUpdater">
|
||||
<option name="singleClickDiffPreview" value="1" />
|
||||
<option name="unhandledExceptionsIgnoreList" value="1" />
|
||||
<option name="vcsConfiguration" value="3" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
|
After Width: | Height: | Size: 9.9 KiB |
@@ -0,0 +1,40 @@
|
||||
# Task 1
|
||||

|
||||
|
||||
## Контрольные вопросы
|
||||
* ``!!`` - утверждение, что выражение не равно ``null``
|
||||
* Оператор ``!!`` это осознанный выбор отключить проверку null, но компилятор всеровно будет предупреждать об ошибки
|
||||
* Я бы сказал что оператор ``!!`` является инструментом обнаружение ошибок и его лучше не вписывать в свой код если нет полной уверенности что значение не null
|
||||
|
||||
# Task 2
|
||||

|
||||
|
||||
# Task 3
|
||||
!
|
||||
|
||||
# Task 4
|
||||

|
||||
|
||||
# Task 5
|
||||

|
||||

|
||||
|
||||
## Контрольный вопрос
|
||||
* При проверке неизменяемой переменной (val) компилятор гарантирует, что её значение не поменяется внутри блока if, поэтому позволяет вызывать методы напрямую. Для изменяемой переменной (var) после присваивания null внутри блока умное приведение типа отключается, и код перестаёт компилироваться, так как другой поток или код ниже мог обнулить значение.
|
||||
|
||||
# Task 6
|
||||

|
||||
|
||||
## Контрольные вопрос
|
||||
* Для очистки списка без счётчика используйте цикл ``while (list.removeLastOrNull() != null) {}``, который остановится, когда элементы закончатся
|
||||
|
||||
# Task 7
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
# Task 8
|
||||

|
||||
|
After Width: | Height: | Size: 107 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 110 KiB |
|
After Width: | Height: | Size: 56 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 5.0 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 10 KiB |
|
After Width: | Height: | Size: 9.7 KiB |
|
After Width: | Height: | Size: 6.9 KiB |
|
After Width: | Height: | Size: 148 KiB |
@@ -0,0 +1,15 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/resources" type="java-resource" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/testResources" type="java-test-resource" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,144 @@
|
||||
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
|
||||
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
|
||||
fun main() {
|
||||
|
||||
// Task 1
|
||||
/*
|
||||
val card: String? = null
|
||||
println(card!!.length) // программа упадет с ошибкой NullPointerException
|
||||
*/
|
||||
|
||||
// Task 2
|
||||
/*
|
||||
val cardA: String? = null
|
||||
println("Длина карты A: ${cardA?.length ?: 0}")
|
||||
|
||||
val cardB: String? = "Pikachu"
|
||||
println("Длина карты B: ${cardB?.length ?: 0}")
|
||||
|
||||
val cardC: String? = ""
|
||||
println("Длина карты C: ${cardC?.length ?: 0}")
|
||||
}
|
||||
*/
|
||||
|
||||
// Task 3
|
||||
// выведет "ASH"
|
||||
/*
|
||||
val rawName1: String? = " Ash "
|
||||
val result1: String = rawName1?.trim()?.uppercase() ?: "ИМЯ НЕ УКАЗАНО"
|
||||
println(result1)
|
||||
|
||||
val rawName2: String? = null
|
||||
val result2: String = rawName2?.trim()?.uppercase() ?: "ИМЯ НЕ УКАЗАНО"
|
||||
println(result2)
|
||||
|
||||
val rawName3: String? = " "
|
||||
val result3: String = rawName3?.trim()?.uppercase() ?: "ИМЯ НЕ УКАЗАНО"
|
||||
println("Результат для пробелов: '$result3'")
|
||||
}
|
||||
*/
|
||||
|
||||
// Task 4
|
||||
/*
|
||||
val energy: String? = "Fire Energy"
|
||||
|
||||
if (energy != null) {
|
||||
println("A: длина = ${energy.length}")
|
||||
} else {
|
||||
println("A: энергии нет")
|
||||
}
|
||||
energy?.let {
|
||||
println("B: длина = ${it.length}")
|
||||
} ?: println("B: энергии нет")
|
||||
|
||||
|
||||
val emptyEnergy: String? = null
|
||||
|
||||
if (emptyEnergy != null) {
|
||||
println("A: длина = ${emptyEnergy.length}")
|
||||
} else {
|
||||
println("A: энергии нет")
|
||||
}
|
||||
|
||||
emptyEnergy?.let {
|
||||
println("B: длина = ${it.length}")
|
||||
} ?: println("B: энергии нет")
|
||||
*/
|
||||
|
||||
// Task 5
|
||||
/*
|
||||
val input: String? = "Potion"
|
||||
if (input != null) {
|
||||
println(input.length)
|
||||
println(input.uppercase())
|
||||
}
|
||||
*/
|
||||
/*
|
||||
var mutableInput: String? = "Potion"
|
||||
if (mutableInput != null) {
|
||||
mutableInput = null
|
||||
println(mutableInput.length)
|
||||
}
|
||||
*/
|
||||
|
||||
// Task 6
|
||||
/*
|
||||
val hand: MutableList<String> = mutableListOf("Pikachu", "Potion")
|
||||
|
||||
println(hand.getOrNull(10)) // null (индекс 10 за пределами списка)
|
||||
println(hand.firstOrNull { it.length > 10 }) // null (длина "Pikachu" = 7, "Potion" = 6)
|
||||
println(hand.lastOrNull()) // Potion (последний элемент)
|
||||
println(hand.randomOrNull()) // Pikachu или Potion (случайный элемент)
|
||||
|
||||
|
||||
hand.clear()
|
||||
println(hand.lastOrNull()) // null (список пуст)
|
||||
println(hand.randomOrNull()) // null (список пуст)
|
||||
|
||||
val deck: MutableList<String> = mutableListOf("A", "B", "C")
|
||||
while (deck.removeLastOrNull() != null) {
|
||||
|
||||
}
|
||||
println("Колода пуста: ${deck.isEmpty()}") // Колода пуста: true
|
||||
}
|
||||
*/
|
||||
|
||||
// Task 7
|
||||
/*
|
||||
println("Сколько энергии прикрепить к покемону?")
|
||||
val raw: String? = readlnOrNull()
|
||||
val energy: Int = raw?.trim()?.toIntOrNull() ?: 0
|
||||
|
||||
if (energy <= 0) {
|
||||
println("Прикреплено 0 энергии (ввод некорректен или пуст)")
|
||||
} else {
|
||||
println("Прикреплено $energy энергии")
|
||||
}
|
||||
*/
|
||||
|
||||
// Task 8
|
||||
println("Введите имя карты (Enter — пропустить):")
|
||||
val cardRaw: String? = readlnOrNull()
|
||||
|
||||
println("Введите урон (Enter — по умолчанию 0):")
|
||||
val damageRaw: String? = readlnOrNull()
|
||||
|
||||
println("Введите бонус-множитель (Enter — по умолчанию 1):")
|
||||
val bonusRaw: String? = readlnOrNull()
|
||||
|
||||
val cardName: String = cardRaw?.trim()?.takeIf { it.isNotEmpty() } ?: "Безымянная карта"
|
||||
val damage: Int = damageRaw?.trim()?.toIntOrNull() ?: 0
|
||||
val bonus: Double = bonusRaw?.trim()?.toDoubleOrNull() ?: 1.0
|
||||
|
||||
val finalDamage: Double = damage * bonus
|
||||
|
||||
println("========================================")
|
||||
println("ОТЧЁТ О ХОДЕ")
|
||||
println("========================================")
|
||||
println("Карта: $cardName")
|
||||
println("Базовый урон: $damage")
|
||||
println("Множитель: $bonus")
|
||||
println("Итоговый урон: $finalDamage")
|
||||
println("========================================")
|
||||
}
|
||||
|
||||