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 all 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.outputNumber()
val tryNumber = inputNumber().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 inputNumber(): String {
var input = inputView.inputNumber()
while (input.isNullOrBlank() || input.contains("[ERROR]")) {
outputView.outputErrorMessage(input ?: Constants.INPUT_IS_NULL)
input = inputView.inputNumber()
}
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.

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

import generator.RandomGenerator

class Cars(private val cars: List<Car>) {
class Cars(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 getCar(index: Int): Car = cars[index]
fun getCarSize(): Int = cars.size
fun move(index: Int) {
cars[index].move(RandomGenerator().getRandomNumber())
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.

13 changes: 7 additions & 6 deletions src/main/kotlin/util/Constants.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ package util

object Constants {
const val INPUT_CAR_NAME = "경주할 자동차 이름을 입력하세요(이름은 쉼표(,)를 기준으로 구분)."
const val INPUT_TRY_NUMBER = "시도할 횟수는 몇 회인가요?"
const val INPUT_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 inputNumber(): String? {
var input = readlnOrNull()
runCatching {
Validator().checkTryNumber(input)
}.onFailure {
input = it.message
}
return input
}
}
12 changes: 6 additions & 6 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 @@ -9,8 +9,8 @@ class OutputView {
println(Constants.INPUT_CAR_NAME)
}

fun outputTryNumber() {
println(Constants.INPUT_TRY_NUMBER)
fun outputNumber() {
println(Constants.INPUT_NUMBER)
}

fun outputResults() {
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