Skip to content

Домашнее задание Kotlin-5 #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
7 changes: 6 additions & 1 deletion src/main/kotlin/ru/otus/cars/Car.kt
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package ru.otus.cars


/**
* Машина целиком
*/
interface Car : CarInput {
var fuelLevel: Int
var tankMouth: TankMouth
val MODEL: String

/**
* Номерной знак
*/
Expand All @@ -28,4 +33,4 @@ interface Car : CarInput {
* Внутренний статический класс - номерой знак
*/
data class Plates(val number: String, val region: Int)
}
}
25 changes: 25 additions & 0 deletions src/main/kotlin/ru/otus/cars/CarBuilder.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.otus.cars

import kotlin.random.Random

/**
* Сборщик машины
*/
Expand All @@ -8,4 +10,27 @@ sealed interface CarBuilder {
* Собери машину
*/
fun build(plates: Car.Plates): Car

object Tank {
fun getContents(car: Car): Int {
return car.fuelLevel
}

fun receiveFuel(car: Car, liters: Int) {
car.fuelLevel += liters
}
}


}

enum class TankMouth(val typeOfFuel: String) {
LADA_2107("Lpg"),
SAMARA_2108("Petrol"),
Taz(
when (Random.nextInt(0, 2)) {
1 -> "Lpg"
else -> "Petrol"
}
)
}
5 changes: 5 additions & 0 deletions src/main/kotlin/ru/otus/cars/CarOutput.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,9 @@ interface CarOutput {
* Скажи текущую скорость
*/
fun getCurrentSpeed(): Int

/**
* Покажи уровень топлива
*/
fun getFuelContents(): Int
}
9 changes: 8 additions & 1 deletion src/main/kotlin/ru/otus/cars/Taz.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package ru.otus.cars

object Taz: Car {
object Taz : Car {
override var fuelLevel: Int = 10
set(value) = throw NotImplementedError("Взрыв бензобака")
override var tankMouth: TankMouth = TankMouth.Taz
override val MODEL = "Taz"

/**
* Номерной знак
*/
Expand Down Expand Up @@ -36,4 +41,6 @@ object Taz: Car {
override fun wheelToLeft(degrees: Int) {
throw NotImplementedError("Руля нет")
}


}
10 changes: 9 additions & 1 deletion src/main/kotlin/ru/otus/cars/Vaz2107.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import kotlin.random.Random
* Семёрочка
*/
class Vaz2107 private constructor(color: String) : VazPlatform(color) {
override val MODEL: String = "Vaz2107"
override var tankMouth: TankMouth= TankMouth.LADA_2107

/**
* Сам-себе-сборщик ВАЗ 2107.
*/
Expand Down Expand Up @@ -59,7 +62,8 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) {

// Выводим состояние машины
override fun toString(): String {
return "Vaz2107(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed)"
return "Vaz2107(plates=$plates, wheelAngle=$wheelAngle, " +
"currentSpeed=$currentSpeed, fuel level=${carOutput.getFuelContents()})"
}

/**
Expand All @@ -74,5 +78,9 @@ class Vaz2107 private constructor(color: String) : VazPlatform(color) {
override fun getCurrentSpeed(): Int {
return [email protected]
}

override fun getFuelContents(): Int {
return CarBuilder.Tank.getContents(this@Vaz2107)
}
}
}
19 changes: 16 additions & 3 deletions src/main/kotlin/ru/otus/cars/Vaz2108.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import kotlin.random.Random
/**
* Восьмерка
*/
class Vaz2108 private constructor(color: String) : VazPlatform(color) {
class Vaz2108 private constructor(color: String) : VazPlatform(color), Car {
override val MODEL: String = "Vaz2108"
override var tankMouth: TankMouth = TankMouth.SAMARA_2108

/**
* Сам-себе-сборщик ВАЗ 2108.
*/
Expand Down Expand Up @@ -38,6 +41,7 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) {
override lateinit var engine: VazEngine
private set


/**
* Восьмерка едет так
*/
Expand All @@ -63,7 +67,8 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) {

// Выводим состояние машины
override fun toString(): String {
return "Vaz2108(plates=$plates, wheelAngle=$wheelAngle, currentSpeed=$currentSpeed)"
return "Vaz2108(plates=$plates, wheelAngle=$wheelAngle, " +
"currentSpeed=$currentSpeed, fuel level=${carOutput.getFuelContents()})"
}

/**
Expand All @@ -78,5 +83,13 @@ class Vaz2108 private constructor(color: String) : VazPlatform(color) {
override fun getCurrentSpeed(): Int {
return [email protected]
}

override fun getFuelContents(): Int {
return CarBuilder.Tank.getContents(this@Vaz2108)
}
}
}
}




14 changes: 11 additions & 3 deletions src/main/kotlin/ru/otus/cars/VazPlatform.kt
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
package ru.otus.cars


abstract class VazPlatform(override val color: String) : Car {
// Положение руля. Доступно только внутри класса и наследникам
protected var wheelAngle: Int = 0 // Положение руля

// Реализация интерфейса CarInput
override fun wheelToRight(degrees: Int) { wheelAngle += degrees }
override fun wheelToRight(degrees: Int) {
wheelAngle += degrees
}

// Реализация интерфейса CarInput
override fun wheelToLeft(degrees: Int) { wheelAngle -= degrees }
override fun wheelToLeft(degrees: Int) {
wheelAngle -= degrees
}

// Получить оборудование
override fun getEquipment(): String = "Кузов, колеса, движок"

// Абстрактное свойство двигателя
abstract val engine: VazEngine

override var fuelLevel: Int = 10
}

// Перечисление двигателей ВАЗ
Expand All @@ -23,4 +31,4 @@ sealed class VazEngine {

data class LADA_2107(override val volume: Int) : VazEngine()
data class SAMARA_2108(override val volume: Int) : VazEngine()
}
}
47 changes: 46 additions & 1 deletion src/main/kotlin/ru/otus/cars/main.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package ru.otus.cars


fun main() {
println("\n===> drive cars...")
driveCars()
Expand All @@ -16,6 +17,9 @@ fun main() {
techChecks()
println("\n===> Taz...")
println(Taz.color)
println("\n===> refuel...")
reFuel(Taz, 5)
reFuelCars()
}

fun driveCars() {
Expand All @@ -36,6 +40,7 @@ fun innerNestedCheck() {
println("Скорость до проверки: ${output.getCurrentSpeed()}") // Выводит 0
Vaz2107.test(vaz) // Газуем...
println("Скорость после проверки: ${output.getCurrentSpeed()}") // Выводит случайную скорость
println("Уровень топлива: ${output.getFuelContents()}") //Ввыводит уровень топлива
}

fun garageMake() {
Expand Down Expand Up @@ -90,4 +95,44 @@ fun repairEngine(car: VazPlatform) {
is VazEngine.LADA_2107 -> println("Чистка карбюратора у двигателя объемом ${car.engine.volume} куб.см у машины $car")
is VazEngine.SAMARA_2108 -> println("Угол зажигания у двигателя объемом ${car.engine.volume} куб.см у машины $car")
}
}
}

/**
* Заправка топливом
*/
fun reFuel(car: Car, liters: Int) {
println()
println(car.MODEL)
println(car.tankMouth.typeOfFuel)
try {
println("Уровень топлива до заправки= ${car.carOutput.getFuelContents()}")
when (car.tankMouth.typeOfFuel) {
"Petrol" -> fuelPetrol(car, liters)
"Lpg" -> fuelLpg(car, liters)
}
println("Заправляем топливо: ${car.tankMouth.typeOfFuel}")
println("Уровень топлива после заправки= ${car.carOutput.getFuelContents()}")
} catch (e: Error) {
println("Бак взорвался")
}
}

fun fuelPetrol(car: Car, liters: Int) {
CarBuilder.Tank.receiveFuel(car, liters)
}

fun fuelLpg(car: Car, liters: Int) {
CarBuilder.Tank.receiveFuel(car, liters)
}

fun reFuelCars() {
val cars = listOf(
Vaz2107.build(Car.Plates("123", 77)),
Vaz2108.build(Car.Plates("321", 78)),
)
cars.forEach { car ->
reFuel(car, 20)
println("Автомобиль: ${car.MODEL} состояние:${car.toString()}")
}
}