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단계 자동차 경주 제출합니다. #68

Merged
merged 12 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
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
64 changes: 25 additions & 39 deletions src/main/kotlin/controller/RaceGame.kt
Original file line number Diff line number Diff line change
@@ -1,63 +1,49 @@
package controller

import generator.RandomGenerator
import model.Cars
import util.CarsHelper
import util.Validator
import util.Constants
import util.WinnersFinder
import view.InputView
import view.OutputView

class RaceGame(private val outputView: OutputView, private val inputView: InputView) {

fun run() {
val cars = executeInputCarNames()
val tryNumber = executeInputTryNumber()
outputView.outputCarNames()
val cars = Cars(inputCarNames())
outputView.outputTryNumber()
val tryNumber = inputTryNumber().toInt()
outputView.outputResults()
repeat(tryNumber) {
tryMove(cars)
}
outputView.outputWinners(CarsHelper.findWinners(cars))
outputView.outputWinners(WinnersFinder.findWinners(cars))
}

private fun tryMove(cars: Cars) {
repeat(cars.getCarSize()) {
cars.move(it)
outputView.outputResult(cars.getCarInfo(it))
cars.move(it, RandomGenerator().getRandomNumber())
outputView.outputResult(cars.getCar(it))
}
outputView.outputNextLine()
}

private fun executeInputTryNumber(): Int {
var result: Int?
do {
outputView.outputTryNumber()
result = getInputTryNumber(inputView.inputTryNumber())
} while (result == null)
return result
}

private fun getInputTryNumber(number: String): Int? {
return runCatching {
Validator().checkTryNumber(number)
number.toInt()
}.onFailure {
outputView.outputErrorMessage(it.message ?: "에러가 발생했습니다.")
}.getOrNull()
}

private fun executeInputCarNames(): Cars {
var result: Cars?
do {
outputView.outputCarNames()
result = getInputCarNames(inputView.inputCarNames())
} while (result == null)
return result
private fun inputCarNames(): String {
var input = inputView.inputCarNames()
while (input.isNullOrBlank() || input.contains("[ERROR]")) {
outputView.outputErrorMessage(input ?: Constants.INPUT_IS_NULL)
input = inputView.inputCarNames()
}
return input
}
Comment on lines +32 to 39

Choose a reason for hiding this comment

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

컨트롤러에서 유효한 입력값을 받을때까지 계속해서 호출하도록 잘 개선해주셨네요. 👍
참고로, 프로그래밍 요구사항에는 유효한 입력값을 받을때까지 계속해서 호출하는 항목은 없습니다. 😅


private fun getInputCarNames(cars: String): Cars? {
return runCatching {
Validator().checkNames(cars)
Cars(cars)
}.onFailure {
outputView.outputErrorMessage(it.message ?: "에러가 발생했습니다.")
}.getOrNull()
private fun inputTryNumber(): String {

Choose a reason for hiding this comment

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

함수는 행위 혹은 행동을 의미하기 때문에, 동사구로 작성하곤 합니다.
하지만 이 함수에는 동사가 2개가 존재합니다. (input, try)
함수에는 하나의 동사만 포함시켜보면 어떨까요? (이하 관련 내용 동일)

var input = inputView.inputTryNumber()
while (input.isNullOrBlank() || input.contains("[ERROR]")) {
outputView.outputErrorMessage(input ?: Constants.INPUT_IS_NULL)
input = inputView.inputTryNumber()
}
return input
}
}
9 changes: 5 additions & 4 deletions src/main/kotlin/model/Car.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ package model

import util.Validator

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

private var _position: Int = position
val position: Int get() = _position

init {
Validator().checkName(name)
}

fun getInfo(): CarInfo = CarInfo(name, position)

fun move(condition: Int) {
if (condition >= MOVING_POINT) position++
if (condition >= MOVING_POINT) _position++
}

companion object {
Expand Down
3 changes: 0 additions & 3 deletions src/main/kotlin/model/CarInfo.kt

This file was deleted.

21 changes: 7 additions & 14 deletions src/main/kotlin/model/Cars.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,14 @@
package model

import generator.RandomGenerator
class Cars(cars: List<Car>) {
private val _cars: List<Car> = cars
val cars: List<Car> get() = _cars

Choose a reason for hiding this comment

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

Suggested change
class Cars(cars: List<Car>) {
private val _cars: List<Car> = cars
val cars: List<Car> get() = _cars
class Cars(val cars: List<Car>) {

Cars 클래스에는 add를 하는 로직이 없습니다.
그렇다면 굳이 backing property 구조로 작성할 필요가 없어 보이네요.


class Cars(private val cars: List<Car>) {
constructor(input: String) : this(input.split(",").mapIndexed { _, name -> Car(name.trim()) })

fun getCarInfos(): List<CarInfo> {
val carInfos = mutableListOf<CarInfo>()
repeat(cars.size) {
carInfos.add(cars[it].getInfo())
}
return carInfos
}

fun getCarInfo(index: Int): CarInfo = cars[index].getInfo()
fun getCarSize(): Int = cars.size
fun move(index: Int) {
cars[index].move(RandomGenerator().getRandomNumber())
fun getCar(index: Int): Car = _cars[index]
fun getCarSize(): Int = _cars.size
fun move(index: Int, condition: Int) {
_cars[index].move(condition)
}
}
13 changes: 0 additions & 13 deletions src/main/kotlin/util/CarsHelper.kt

This file was deleted.

11 changes: 6 additions & 5 deletions src/main/kotlin/util/Constants.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@ object Constants {
const val INPUT_TRY_NUMBER = "시도할 횟수는 몇 회인가요?"
const val OUTPUT_RESULT = "실행 결과"
const val OUTPUT_WINNER = "최종 우승자: "
const val INPUT_NAME_SIZE_ERROR_MESSAGE = "자동차 이름의 길이가 5를 초괴합니다."
const val INPUT_NAME_NULL_ERROR_MESSAGE = "자동차 이름이 입력되지 않았습니다."
const val INPUT_TRY_NUMBER_NULL_ERROR_MESSAGE = "시도할 횟수가 입력되지 않았습니다."
const val INPUT_TRY_NUMBER_RIGHT_ERROR_MESSAGE = "시도할 횟수가 올바르게 입력되지 않았습니다."
const val INPUT_NAME_RIGHT_ERROR_MESSAGE = "자동차 이름은 한글과 영어만 가능합니다."
const val INPUT_NAME_SIZE_ERROR_MESSAGE = "[ERROR] 자동차 이름의 길이가 5를 초괴합니다."
const val INPUT_NAME_NULL_ERROR_MESSAGE = "[ERROR] 자동차 이름이 입력되지 않았습니다."
const val INPUT_TRY_NUMBER_NULL_ERROR_MESSAGE = "[ERROR] 시도할 횟수가 입력되지 않았습니다."
const val INPUT_TRY_NUMBER_RIGHT_ERROR_MESSAGE = "[ERROR] 시도할 횟수가 올바르게 입력되지 않았습니다."
const val INPUT_NAME_RIGHT_ERROR_MESSAGE = "[ERROR] 자동차 이름은 한글과 영어만 가능합니다."
const val INPUT_IS_NULL = "[ERROR] 입력 값이 널입니다."
}
10 changes: 3 additions & 7 deletions src/main/kotlin/util/Validator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Validator {

fun checkTryNumber(name: String?) {
checkTryNumberNull(name)
checkTryNumberIsRight(name)
checkTryNumberIsRight(name ?: "")
}

private fun checkNameNull(name: String?) {
Expand All @@ -41,11 +41,7 @@ class Validator {
require(number != null) { Constants.INPUT_TRY_NUMBER_NULL_ERROR_MESSAGE }
}

private fun checkTryNumberIsRight(number: String?) {
try {
number!!.toInt()
} catch (e: NumberFormatException) {
throw IllegalArgumentException(Constants.INPUT_TRY_NUMBER_RIGHT_ERROR_MESSAGE)
}
private fun checkTryNumberIsRight(number: String) {
require(number.isNotEmpty() && number.chars().allMatch { Character.isDigit(it) }) { Constants.INPUT_TRY_NUMBER_RIGHT_ERROR_MESSAGE }
}
}
10 changes: 10 additions & 0 deletions src/main/kotlin/util/WinnersFinder.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package util

import model.Cars

object WinnersFinder {
fun findWinners(cars: Cars): List<String> {
val equalCars = cars.cars.groupBy({ it.position }, { it.name })
return equalCars[equalCars.keys.max()]?.toList() ?: emptyList()
}
}
22 changes: 18 additions & 4 deletions src/main/kotlin/view/InputView.kt
Original file line number Diff line number Diff line change
@@ -1,11 +1,25 @@
package view

import util.Validator

class InputView {
fun inputCarNames(): String {
return readLine() ?: ""
fun inputCarNames(): String? {
var input = readlnOrNull()
runCatching {
Validator().checkNames(input)
}.onFailure {
input = it.message
}
return input
}

fun inputTryNumber(): String {
return readLine() ?: ""
fun inputTryNumber(): String? {
var input = readlnOrNull()
runCatching {
Validator().checkTryNumber(input)
}.onFailure {
input = it.message
}
return input
}
}
8 changes: 4 additions & 4 deletions src/main/kotlin/view/OutputView.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package view

import model.CarInfo
import model.Car
import util.Constants

class OutputView {
Expand All @@ -26,9 +26,9 @@ class OutputView {
println(error)
}

fun outputResult(info: CarInfo) {
print(info.name + " : ")
repeat(info.position) {
fun outputResult(car: Car) {
print(car.name + " : ")
repeat(car.position) {
print("-")
}
println()
Expand Down
10 changes: 5 additions & 5 deletions src/test/kotlin/CarTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import org.junit.jupiter.api.assertThrows
class CarTest {

@Test
fun getInfoTest() {
fun checkCarCreateTest() {
val car = Car("dool")
assertThat(car.getInfo().name).isEqualTo("dool")
assertThat(car.getInfo().position).isEqualTo(0)
assertThat(car.name).isEqualTo("dool")
assertThat(car.position).isEqualTo(0)
}

@Test
Expand All @@ -23,13 +23,13 @@ class CarTest {
fun moveTest() {
val car = Car("dool")
car.move(3)
assertThat(car.getInfo().position).isEqualTo(0)
assertThat(car.position).isEqualTo(0)
}

@Test
fun dontMoveTest() {
val car = Car("dool")
car.move(4)
assertThat(car.getInfo().position).isEqualTo(1)
assertThat(car.position).isEqualTo(1)
}
}
2 changes: 1 addition & 1 deletion src/test/kotlin/CarsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ class CarsTest {
fun mappingCarsTest() {
val carNames = listOf("pobi", "dool", "woni")
repeat(cars.getCarSize()) {
assertThat(cars.getCarInfo(it).name).isEqualTo(carNames[it])
assertThat(cars.getCar(it).name).isEqualTo(carNames[it])
}
}

Expand Down