Skip to content
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

[부나] 2단계 자동차 경주 제출합니다. #64

Merged
merged 99 commits into from
Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from 98 commits
Commits
Show all changes
99 commits
Select commit Hold shift + click to select a range
4d15ac7
docs: 기능 목록 초기 작성
tmdgh1592 Feb 7, 2023
2fb4547
feat: 최종 우승자 산출 기능 구현
tmdgh1592 Feb 7, 2023
d85e64e
feat: 자동차 이름들 입력 기능 구현
tmdgh1592 Feb 7, 2023
69fe601
feat: 시도 횟수 입력 기능 구현
tmdgh1592 Feb 7, 2023
ca51779
refactor: 조건 숫자, 에러문구 상수화
tmdgh1592 Feb 7, 2023
37462f6
feat: 자동차 랜덤 전진 기능 구현
tmdgh1592 Feb 7, 2023
8808d37
test: 테스트 커밋
tmdgh1592 Feb 8, 2023
1d86cdd
feat: 실행 결과 출력 기능 구현
tmdgh1592 Feb 8, 2023
e1f5fc1
feat: 최종 우승자 산출 기능 구현
tmdgh1592 Feb 8, 2023
118d2cb
docs: 기능 목록 추가
tmdgh1592 Feb 8, 2023
b826b0e
feat: 우승자 출력 기능 구현
tmdgh1592 Feb 8, 2023
972d412
feat: 기능 통합 구현
tmdgh1592 Feb 8, 2023
7b51f8c
test: Car class 테스트 초기 작성
tmdgh1592 Feb 8, 2023
b16841c
test: Validator class 테스트 초기 작성
tmdgh1592 Feb 8, 2023
e724948
test: Validator class 시도 횟수 입력 테스트 초기 작성
tmdgh1592 Feb 8, 2023
1381ae5
test: RacingService class 객체 생성 테스트 작성
tmdgh1592 Feb 8, 2023
d88ea80
feat: 고정 시드 랜덤 유틸 구현
tmdgh1592 Feb 8, 2023
7e42178
refactor: 랜덤 시작, 종료 범위, 이동 확률 상수화
tmdgh1592 Feb 8, 2023
0edf628
test: 최종 우승자 산출 테스트 코드 구현
tmdgh1592 Feb 9, 2023
1ca0cda
test: 최종 우승자 산출 테스트 코드 구현
tmdgh1592 Feb 9, 2023
4d5d28b
test: 자동차 생성 예외 테스트 코드 구현
tmdgh1592 Feb 9, 2023
89bfc95
test: 최종 우승자 산출 예외 테스트 코드 구현
tmdgh1592 Feb 9, 2023
fe11d89
test: 전체 기능 테스트 코드 구현
tmdgh1592 Feb 9, 2023
5d67e4e
feat: 공백 지우는 클래스 구현
tmdgh1592 Feb 9, 2023
3571323
refactor: 메서드명, 길이 10자 이내로 제한하도록 리팩토링
tmdgh1592 Feb 9, 2023
39f2cdd
test: validator 테스트 코드 매개변수 수정
tmdgh1592 Feb 9, 2023
3e46229
docs: .gitkeep 파일 제거
tmdgh1592 Feb 10, 2023
c34e4cc
docs: .editorconfig 파일 마지막에 개행 문자 추가
tmdgh1592 Feb 10, 2023
890bef6
refactor: createCars() 메서드 반환값 표기
tmdgh1592 Feb 10, 2023
8945701
refactor: ktlint에 맞춰 각 파일의 마지막 줄에 개행 문자 추가
tmdgh1592 Feb 10, 2023
3aa878a
refactor: Car의 toString() 메서드 재정의 제거하고 name 프로퍼티에 접근할 수 있도록 수정
tmdgh1592 Feb 10, 2023
74f7af6
refactor: Car 클래스의 getPositionAsDash() 메서드를 제거하고 position 프로퍼티에 접근할 수…
tmdgh1592 Feb 10, 2023
3ab052f
refactor: Random 유틸 클래스를 제거하고 Service에서 로직 구현
tmdgh1592 Feb 10, 2023
ce2e1bb
refactor: BlankRemover 유틸 클래스를 제거하고 Extensions 파일에서 처리하도록 수정
tmdgh1592 Feb 10, 2023
efd5d0c
fix: getRandomProbabilityInRange() 메서드의 Max bound 범위를 1 감소
tmdgh1592 Feb 10, 2023
9282f50
refactor: Dimens, Strings 파일에서 관리하던 상수를 필요한 클래스에서 관리하도록 수정
tmdgh1592 Feb 10, 2023
35dff55
test: testCarMovement() 메서드명을 testCarMovement()로 변경
tmdgh1592 Feb 10, 2023
e45ab6b
refactor: 불필요한 주석 및 코드 제거
tmdgh1592 Feb 10, 2023
4f9ba23
test: 자동차 객체 생성 테스트 코드 구현
tmdgh1592 Feb 10, 2023
07dcf8e
refactor: ApplicationKtTest 테스트 코드 분리하고 Given-When-Then 표기법으로 변경
tmdgh1592 Feb 10, 2023
983fd98
refactor: CarTest 네이밍을 Given-When-Then 표기법으로 변경
tmdgh1592 Feb 10, 2023
e735d17
refactor: RacingServiceTest 네이밍을 Given-When-Then 표기법으로 변경
tmdgh1592 Feb 10, 2023
8a24159
refactor: 자동차 이름의 길이를 Car 클래스 생성시 검증하도록 변경
tmdgh1592 Feb 10, 2023
d9c1cde
refactor: round 범위를 Round 래퍼 클래스에서 검증하도록 변경
tmdgh1592 Feb 10, 2023
3250ce8
refactor: Round 범위 입력값의 숫자 여부 검증을 InputView에서 하도록 변경하고 일반화
tmdgh1592 Feb 10, 2023
c41adbe
feat: CarRepository 클래스 구현
tmdgh1592 Feb 10, 2023
aaca844
feat: 자동차 중복 검증을 CarRepository에서 하도록 변경
tmdgh1592 Feb 10, 2023
385e9b7
feat: 우승자 산출시 Car의 compareTo() 메서드로 비교하던 부분을 각 position 프로퍼티와 비교하도록 변경
tmdgh1592 Feb 10, 2023
7012826
refactor: Dimens 파일에서 관리하던 상수를 필요한 클래스에서 관리하도록 수정
tmdgh1592 Feb 10, 2023
810050b
refactor: getWinners() 메서드 매개변수 제거
tmdgh1592 Feb 10, 2023
0924fe7
refactor: Round 객체 생성시 검증을 require 메서드를 사용하도록 변경
tmdgh1592 Feb 10, 2023
1f76b4e
test: 라운드 객체 생성 테스트 코드 구현
tmdgh1592 Feb 10, 2023
3783a31
fix: CarRepositry에서 car 객체 삽입시 검증을 위해 비교하는 기준을 이름으로 변경하여 에러 수정
tmdgh1592 Feb 10, 2023
f3d42d2
test: 자동차 moveCount 테스트에서 주어진 자동차 객체를 insert하도록 변경
tmdgh1592 Feb 10, 2023
a2441a2
refactor: 불필요한 상수 제거
tmdgh1592 Feb 10, 2023
3966720
refactor: getRandomProbabilityInRange() 메서드명 변경
tmdgh1592 Feb 10, 2023
f1d7a52
refactor: Car의 move() 메서드에 이동 조건값 추가
tmdgh1592 Feb 10, 2023
5a27b6d
test: Car 클래스의 move() 메서드 테스트 코드 구현
tmdgh1592 Feb 10, 2023
cbed4f1
fix: Car 클래스에서 이름 길이 검증시 throw를 두 번 발생시키는 버그 수정
tmdgh1592 Feb 11, 2023
919ba1c
refactor: 자동차 이름 프로퍼티를 CarName 클래스로 분리
tmdgh1592 Feb 11, 2023
7e22dea
refactor: Car 리스트를 Cars 클래스로 감싸서 RacingService에서 관리하도록 변경
tmdgh1592 Feb 11, 2023
322b011
refactor: CarRepository 클래스 제거
tmdgh1592 Feb 11, 2023
b96c5d1
refactor: RacingController 클래스에서 RacingService 생성을 메서드로 분리
tmdgh1592 Feb 11, 2023
3cd5d3b
refactor: removeBlank() 메서드에 반환 타입 표기
tmdgh1592 Feb 11, 2023
b354f94
feat: Winners 도메인 모델 구현
tmdgh1592 Feb 11, 2023
1b9aae3
refactor: 각 도메인 Model에 대해 DTO 구현
tmdgh1592 Feb 11, 2023
a2a3628
refactor: RacingService에서 도메인 Model과 DTO를 변환하고 입출력시 Model 대신 DTO를 의존하…
tmdgh1592 Feb 11, 2023
c1bbd0c
chore: kotlin("test") 라이브러리 제거
tmdgh1592 Feb 12, 2023
0e2a0d6
chore: Mockito 2.21.0 라이브러리 추가
tmdgh1592 Feb 12, 2023
330601f
refactor: Cars에서 randomGenerator를 주입받아 Car의 randomMove() 메서드의 인자로 이동할…
tmdgh1592 Feb 12, 2023
910225c
refactor: CarName 객체 생성시 전달받은 이름에 대해 양 옆 공백을 제거하여 관리하도록 수정
tmdgh1592 Feb 12, 2023
70e8c98
test: CarName 테스트 코드 구현
tmdgh1592 Feb 12, 2023
5f2d1f7
test: Cars 자동차 이름 중복 검증 테스트 구현
tmdgh1592 Feb 12, 2023
feb31e3
test: Cars getWinners() 테스트 코드 구현
tmdgh1592 Feb 12, 2023
2a702a1
refactor: CarTest, RoundTest 패키지 이동
tmdgh1592 Feb 12, 2023
9298caf
refactor: runAllRounds 메서드 인자로 RoundDto 추가
tmdgh1592 Feb 12, 2023
16de727
refactor: MovementProbabilityGenerator generate() 메서드 인자 제거
tmdgh1592 Feb 12, 2023
6320815
refactor: Round 클래스 count 프로퍼티 접근제한자 private 제거
tmdgh1592 Feb 12, 2023
14595f1
test: RacingService 클래스 테스트 코드 구현
tmdgh1592 Feb 12, 2023
249b12d
refactor: merge conflict 해결
tmdgh1592 Feb 12, 2023
9656256
refactor: 자동차 이동 확률 범위를 0에서 9로 변경
tmdgh1592 Feb 13, 2023
ee98952
refactor: Car model의 carName, position 프로퍼티를 var에서 val로 변경
tmdgh1592 Feb 13, 2023
4cf09d2
refactor: Car와 CarDto 변환을 mapper로 분리
tmdgh1592 Feb 13, 2023
ba98fd4
refactor: Cars와 CarsDto 변환을 mapper로 분리
tmdgh1592 Feb 13, 2023
a614450
refactor: Winners와 WinnersDto 클래스 분리
tmdgh1592 Feb 13, 2023
255a8bf
refactor: Round와 RoundDto 변환을 mapper로 분리
tmdgh1592 Feb 13, 2023
228132e
refactor: CarName에서 name 프로퍼티가 _name을 trim()하여 반환하도록 변경
tmdgh1592 Feb 13, 2023
4b82d73
refactor: CarName 클래스의 name 프로퍼티명을 value로 변경
tmdgh1592 Feb 13, 2023
782af39
refactor: RandomGenerator 인터페이스명을 NumberGenerator로 변경
tmdgh1592 Feb 13, 2023
6360209
chore: Mockito 라이브러리 제거
tmdgh1592 Feb 13, 2023
9c847c0
chore: Mockito의 Mock 대신 fake객체를 사용하도록 변경
tmdgh1592 Feb 13, 2023
8046843
refactor: MovementProbabilityGenerator 클래스를 제거하고 CarMoveCondition으로 변경
tmdgh1592 Feb 13, 2023
a39cc01
refactor: MoveStep 인터페이스를 sealed 클래스로 변경
tmdgh1592 Feb 13, 2023
3a09e61
refactor: CarMoveCondition 메서드를 operator invoke 메서드로 변경
tmdgh1592 Feb 13, 2023
78fe97b
refactor: MoveStep 이동 거리 상수화
tmdgh1592 Feb 13, 2023
24e8396
fix: 매 라운드마다 자동차 위치 출력 안 되는 버그 수정
tmdgh1592 Feb 13, 2023
b2919dd
refactor: Car move() 메서드 호출시 Step을 받도록 테스트 코드 변경
tmdgh1592 Feb 13, 2023
dc441fa
refactor: Car moveAll에서 이동 여부 로직을 isSatisfyCondition() 메서드로 분리
tmdgh1592 Feb 13, 2023
8268211
chore: CarRandomMoveCondtion Fake 클래스를 test 패키지로 이동
tmdgh1592 Feb 14, 2023
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
2 changes: 0 additions & 2 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ dependencies {
testImplementation("org.junit.jupiter", "junit-jupiter", "5.8.2")
testImplementation("org.assertj", "assertj-core", "3.22.0")
testImplementation("io.kotest", "kotest-runner-junit5", "5.2.3")

testImplementation(kotlin("test"))
}

tasks {
Expand Down
48 changes: 20 additions & 28 deletions src/main/kotlin/racingcar/controller/RacingController.kt
Original file line number Diff line number Diff line change
@@ -1,63 +1,55 @@
package racingcar.controller

import racingcar.model.Car
import racingcar.model.Round
import racingcar.dto.car.CarsDto
import racingcar.dto.car.WinnersDto
import racingcar.dto.round.RoundDto
import racingcar.service.RacingService
import racingcar.view.InputView
import racingcar.view.OutputView

class RacingController(
private val inputView: InputView = InputView(),
private val outputView: OutputView = OutputView(),
private val racingService: RacingService = RacingService(),
) {
fun runRacing() {
val cars = racingService.createCars(readCarNames())
racingService.insertCars(cars)
private lateinit var racingService: RacingService

fun runRacing() {
initRacingService()
val round = readRound()

runRounds(round.count, cars)
runRounds(round)

val winners = getWinners()
printWinners(winners)
}

private fun readCarNames(): List<String> {
private fun initRacingService() {
racingService = RacingService(readCarNames())
}

private fun readCarNames(): CarsDto {
outputView.printMessage(CAR_NAMES_REQUEST_MESSAGE)
return inputView.readCarNames()
}

private fun readRound(): Round {
private fun readRound(): RoundDto {
outputView.printMessage(ROUND_COUNT_REQUEST_MESSAGE)
return Round(inputView.readNumber())
return inputView.readRound()
}

private fun printRoundCountRequestMessage() = outputView.printMessage(ROUNDS_RESULT_NOTIFICATION_MESSAGE)

private fun printRoundResult(cars: List<Car>) = outputView.printRoundResult(cars)
private fun printRoundResult(cars: CarsDto) = outputView.printRoundResult(cars)

private fun printWinners(winners: List<Car>) = outputView.printWinners(winners)
private fun printWinners(winners: WinnersDto) = outputView.printWinners(winners)

private fun runRounds(roundCount: Int, cars: List<Car>) {
private fun runRounds(round: RoundDto) {
printRoundCountRequestMessage()
repeat(roundCount) {
runRound(cars)
}
}

private fun runRound(cars: List<Car>) {
moveCarsRandomly(cars)
printRoundResult(cars)
}

private fun moveCarsRandomly(cars: List<Car>) {
cars.forEach { car ->
racingService.moveRandomly(car)
racingService.runAllRounds(round) { eachRoundCars ->
printRoundResult(eachRoundCars)
}
}

private fun getWinners(): List<Car> = racingService.getWinners()
private fun getWinners(): WinnersDto = racingService.getWinners()

companion object {
private const val CAR_NAMES_REQUEST_MESSAGE = "경주할 자동차 이름을 입력하세요(이름은 쉼표(,)를 기준으로 구분)."
Expand Down
7 changes: 7 additions & 0 deletions src/main/kotlin/racingcar/dto/car/CarDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package racingcar.dto.car

import racingcar.model.car.CarName

class CarDto(_carName: String, val position: Int = 0) {
val carName: CarName = CarName(_carName.trim())
}
3 changes: 3 additions & 0 deletions src/main/kotlin/racingcar/dto/car/CarsDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package racingcar.dto.car

class CarsDto(_cars: List<CarDto>) : List<CarDto> by _cars
5 changes: 5 additions & 0 deletions src/main/kotlin/racingcar/dto/car/WinnersDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package racingcar.dto.car

import racingcar.model.car.Car

class WinnersDto(winners: List<Car>) : List<Car> by winners
3 changes: 3 additions & 0 deletions src/main/kotlin/racingcar/dto/round/RoundDto.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package racingcar.dto.round

class RoundDto(val count: Int)
27 changes: 0 additions & 27 deletions src/main/kotlin/racingcar/model/Car.kt

This file was deleted.

12 changes: 12 additions & 0 deletions src/main/kotlin/racingcar/model/car/Car.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package racingcar.model.car

import racingcar.model.car.move.step.MoveStep

class Car(name: String, private var _position: Int = 0) {

Choose a reason for hiding this comment

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

추가적인 내용이니 참고만해주셔도 좋습니다! (다음 미션들의 내용이니 참고만해주세요!)
_position이라는 가변 상태 변수의 존재는 Car의 상태를 관리해주어야하게 만듭니다!
객체의 불변성을 유지하여 불변객체로 관리해 보아도 좋을거 같아요!

val carName: CarName = CarName(name)
val position: Int get() = _position

fun move(moveStep: MoveStep) {
_position += moveStep.move()
}
}
19 changes: 19 additions & 0 deletions src/main/kotlin/racingcar/model/car/CarName.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package racingcar.model.car

class CarName(private var _value: String) {
val value: String get() = _value.trim()

init {
require(value.length in MIN_CAR_NAME_LENGTH..MAX_CAR_NAME_LENGTH) {
CAR_NAME_LENGTH_OVER_BOUNDARY_ERROR_MESSAGE
}
}

companion object {
private const val MIN_CAR_NAME_LENGTH = 1
private const val MAX_CAR_NAME_LENGTH = 5

private const val CAR_NAME_LENGTH_OVER_BOUNDARY_ERROR_MESSAGE =
"자동차 이름 길이의 범위는 $MIN_CAR_NAME_LENGTH 이상 $MAX_CAR_NAME_LENGTH 이하입니다."
}
}
41 changes: 41 additions & 0 deletions src/main/kotlin/racingcar/model/car/Cars.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package racingcar.model.car

import racingcar.model.car.move.condition.CarMoveCondition
import racingcar.model.car.move.step.OneStep
import racingcar.model.car.move.step.ZeroStep

class Cars(_cars: List<Car>) : List<Car> by _cars {
init {
validateExistDuplicatedCarName()
}

private fun validateExistDuplicatedCarName() {
val nonDuplicatedCarsForName = this.distinctBy { it.carName.value }

require(this.size == nonDuplicatedCarsForName.size) {
DUPLICATED_CAR_NAME_ERROR_MESSAGE
}
}

fun moveAll(carMoveCondition: CarMoveCondition): Cars = this.onEach { car ->
if (isSatisfyCondition(carMoveCondition)) {
car.move(OneStep)
} else {
car.move(ZeroStep)
}
}

private fun isSatisfyCondition(carMoveCondition: CarMoveCondition) =
carMoveCondition() >= MOVE_CONDITION

fun getWinners(): Winners {
val winnerStandard = this.maxBy { it.position }
return Winners(this.filter { it.position == winnerStandard.position })
}

companion object {
private const val DUPLICATED_CAR_NAME_ERROR_MESSAGE =
"중복된 자동차 이름이 존재합니다."
private const val MOVE_CONDITION = 4
}
}
7 changes: 7 additions & 0 deletions src/main/kotlin/racingcar/model/car/Winners.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package racingcar.model.car

import racingcar.dto.car.WinnersDto

class Winners(winners: List<Car>) : List<Car> by winners {
fun toDto(): WinnersDto = WinnersDto(this)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package racingcar.model.car.move.condition

interface CarMoveCondition {
operator fun invoke(): Int
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package racingcar.model.car.move.condition

class CarRandomMoveCondition : CarMoveCondition {
override operator fun invoke(): Int =
(START_RANDOM_MOVEMENT_PROBABILITY..END_RANDOM_MOVEMENT_PROBABILITY).random()

class FakeForSuccess : CarMoveCondition {
override operator fun invoke(): Int = SUCCESS_NUMBER
}

class FakeForFailed : CarMoveCondition {
override operator fun invoke(): Int = FAIL_NUMBER
}

Choose a reason for hiding this comment

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

Fake객체는 실제 코드에서는 사용되지않는코드입니다,
테스트 패키지로 관리하면 어떨까요?

Copy link
Member Author

Choose a reason for hiding this comment

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

Fake 관련 클래스를 어디에 구현해야 하는지 고민이었는데 답을 얻은 것 같습니다!
감사합니다 🙂

companion object {
private const val START_RANDOM_MOVEMENT_PROBABILITY = 0
private const val END_RANDOM_MOVEMENT_PROBABILITY = 9

private const val FAIL_NUMBER = 0
private const val SUCCESS_NUMBER = 9
}
}
17 changes: 17 additions & 0 deletions src/main/kotlin/racingcar/model/car/move/step/MoveStep.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package racingcar.model.car.move.step

sealed class MoveStep {
abstract fun move(): Int
}

object ZeroStep : MoveStep() {

Choose a reason for hiding this comment

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

sealed 클래스 👍
sealed 클래스와 enum의 차이는 무엇인지 고민해보셔도 좋을거 같아요!
바로 다음 로또 미션에 나오는 내용이니 참고만해주셔도 좋아요!

private const val ZERO_STEP = 0

override fun move(): Int = ZERO_STEP
}

object OneStep : MoveStep() {
private const val ONE_STEP = 1

override fun move(): Int = ONE_STEP
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package racingcar.model
package racingcar.model.round

class Round(val count: Int) {
init {
Expand Down
19 changes: 0 additions & 19 deletions src/main/kotlin/racingcar/repository/CarRepository.kt

This file was deleted.

6 changes: 0 additions & 6 deletions src/main/kotlin/racingcar/repository/Repository.kt

This file was deleted.

45 changes: 17 additions & 28 deletions src/main/kotlin/racingcar/service/RacingService.kt
Original file line number Diff line number Diff line change
@@ -1,38 +1,27 @@
package racingcar.service

import racingcar.model.Car
import racingcar.repository.CarRepository
import racingcar.repository.Repository
import racingcar.dto.car.CarsDto
import racingcar.dto.car.WinnersDto
import racingcar.dto.round.RoundDto
import racingcar.model.car.move.condition.CarMoveCondition
import racingcar.model.car.move.condition.CarRandomMoveCondition
import racingcar.utils.mapper.toDto
import racingcar.utils.mapper.toModel

class RacingService(
private val carRepository: Repository<Car> = CarRepository()
_cars: CarsDto,
private val carMoveCondition: CarMoveCondition = CarRandomMoveCondition()
) {
fun getAll(): List<Car> = carRepository.selectAll()
private val cars = _cars.toModel()

fun insertCars(cars: List<Car>) {
cars.forEach { insertCar(it) }
fun runAllRounds(round: RoundDto, doEachRoundResult: (CarsDto) -> Unit) {
repeat(round.toModel().count) {
doEachRoundResult(moveCars())
}
}

private fun insertCar(car: Car) = carRepository.insert(car)
private fun moveCars(): CarsDto =
cars.moveAll(carMoveCondition).toDto()

fun createCars(names: List<String>): List<Car> =
names.map { Car(it) }

fun moveRandomly(car: Car) {
car.move(getRandomProbability())
}

private fun getRandomProbability(): Int =
(START_RANDOM_MOVEMENT_PROBABILITY..END_RANDOM_MOVEMENT_PROBABILITY).random()

fun getWinners(): List<Car> {
val cars = getAll()
val winnerStandard = cars.maxBy { it.position }
return cars.filter { it.position == winnerStandard.position }
}

companion object {
private const val START_RANDOM_MOVEMENT_PROBABILITY = 1
private const val END_RANDOM_MOVEMENT_PROBABILITY = 10
}
fun getWinners(): WinnersDto = cars.getWinners().toDto()
}
3 changes: 2 additions & 1 deletion src/main/kotlin/racingcar/utils/Extensions.kt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
package racingcar.utils

fun List<String>.removeBlank() = map { it.trim() }
fun List<String>.removeBlank(): List<String> =
this.map { it.trim() }
8 changes: 8 additions & 0 deletions src/main/kotlin/racingcar/utils/mapper/CarMapper.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package racingcar.utils.mapper

import racingcar.dto.car.CarDto
import racingcar.model.car.Car

fun CarDto.toModel(): Car = Car(carName.value, position)

fun Car.toDto(): CarDto = CarDto(carName.value, position)
10 changes: 10 additions & 0 deletions src/main/kotlin/racingcar/utils/mapper/CarsMapper.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package racingcar.utils.mapper

import racingcar.dto.car.CarsDto
import racingcar.model.car.Cars

fun CarsDto.toModel(): Cars = Cars(this.map { it.toModel() })

fun Cars.toDto(): CarsDto = CarsDto(
this.map { car -> car.toDto() }
)
6 changes: 6 additions & 0 deletions src/main/kotlin/racingcar/utils/mapper/RoundMapper.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package racingcar.utils.mapper

import racingcar.dto.round.RoundDto
import racingcar.model.round.Round

fun RoundDto.toModel(): Round = Round(count)
Loading