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

[자동차 경주] 이서현 미션 제출합니다. #231

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
41 changes: 41 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# 자동차 경주 게임

## 기능 목록
- [X] 5자 이하의 자동차 이름 n개를 쉼표(,)로 구분하여 입력받는다.
- [X] 시도할 횟수를 입력받는다.
- [X] 각 자동차마다 0에서 9 사이의 랜덤값을 구해 4 이상이면 전진시킨다.
- [X] 시도 횟수 동안 실행 결과(자동차 이름과 전진 상태)를 출력한다.
- [X] 게임 완료 후 최종 우승자를 한 명 이상 출력한다.

## 기능 요구 사항

- [X] 주어진 횟수 동안 n대의 자동차는 전진 또는 멈출 수 있다.
- [X] 전진하는 조건은 0에서 9 사이에서 무작위 값을 구한 후 무작위 값이 4 이상일 경우이다.
- [X] 각 자동차에 이름을 부여할 수 있다. 전진하는 자동차를 출력할 때 자동차 이름을 같이 출력한다.
- [X] 자동차 이름은 쉼표(,)를 기준으로 구분하며 이름은 5자 이하만 가능하다.
- [X] 사용자는 몇 번의 이동을 할 것인지를 입력할 수 있어야 한다.
- [X] 자동차 경주 게임을 완료한 후 누가 우승했는지를 알려준다. 우승자는 한 명 이상일 수 있다.
- [X] 우승자가 여러 명일 경우 쉼표(,)를 이용하여 구분한다.
- [X] 사용자가 잘못된 값을 입력할 경우 애플리케이션은 종료되어야 한다.

### 실행 결과 예시

```
경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)
pobi,woni,jun
시도할 횟수는 몇 회인가요?
5

실행 결과
pobi : -
woni :
jun : -

/* 3번의 라운드 */

pobi : -----
woni : ----
jun : -----

최종 우승자 : pobi, jun
```
99 changes: 98 additions & 1 deletion src/main/kotlin/racingcar/Application.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,102 @@
package racingcar

import camp.nextstep.edu.missionutils.Console
import camp.nextstep.edu.missionutils.Randoms

val MIN_VALUE: Int = 0
val MAX_VALUE: Int = 9

val START_MESSAGE: String = "경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)"
val TRIAL_MESSAGE: String = "시도할 횟수는 몇 회인가요?"
val RESULT_MESSAGE: String = "실행 결과"
val WINNER_MESSAGE: String = "최종 우승자 :"

val NOT_NUMBER_ERROR_MESSAGE: String = "숫자를 입력해주세요"
val LACK_OF_CARS_ERROR_MESSAGE: String = "경주할 자동차 이름을 두 대 이상 입력하세요"
val TOO_LONG_CAR_NAME_ERROR_MESSAGE: String = "자동차 이름은 5자 이하만 가능합니다"

fun main() {
// TODO: 프로그램 구현
startGame()
}

fun startGame() {

println(START_MESSAGE)
var CarNames: List<String> = getCarNames()
Copy link

Choose a reason for hiding this comment

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

대부분 변수마다 타입을 정의 하셨는데 코틀린은 타입 캐스팅이 되기 때문에 따로 안 적으셔도 됩니다!
그냥 보기 편하려고 의도하신거라면 그냥 지나가셔도 됩니다!

Copy link
Author

Choose a reason for hiding this comment

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

어디에 쓰고 어디에 뺄지 모르겠어서 안쓰다가도 채우게 되더라구요ㅜㅜ
어느새 까먹고 있던 부분이었는데 기준을 세워봐야겠습니다 감사합니다!!

println(TRIAL_MESSAGE)
val trialCount: Int? = Console.readLine().toIntOrNull()
Copy link

Choose a reason for hiding this comment

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

trialCount가 nulll일 때 처리를 해주는 게 좋을 거 같아요

Copy link
Author

Choose a reason for hiding this comment

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

71번 줄에 따로 해둔다고 해놨었는데 생각해보니 null로 가지고 있는 것보다는 받은 걸 나중에 확인하는 게 훨씬 나을 수도 있겠네요!! 감사합니다!!😃

require(isNumberTrialCountValidation(trialCount)){
NOT_NUMBER_ERROR_MESSAGE
}

println(RESULT_MESSAGE)
var moveResult: MutableList<String> = MutableList(CarNames.size) { "" }
repeat(trialCount!!){
moveResult = runOneRound(CarNames, moveResult)
printOneRound(CarNames, moveResult)
println("")
}

val winnerNames: String = getWinnerNames(CarNames, moveResult)
println("$WINNER_MESSAGE $winnerNames")
}

fun getCarNames(): List<String> {
val allRacingCarNames: String = Console.readLine().replace("\\s".toRegex(), "")
val result: List<String> = allRacingCarNames.split(",").distinct()

require(!isOnlyBlankValidation(allRacingCarNames) &&
!isOnlyOneValidation(result.toString())) {
LACK_OF_CARS_ERROR_MESSAGE
}
require(isNameLengthBelowFiveValidation(result)) {
TOO_LONG_CAR_NAME_ERROR_MESSAGE
}

return result
}

fun isOnlyBlankValidation(pureString: String): Boolean {
return pureString.isBlank()
}

fun isOnlyOneValidation(pureString: String): Boolean {
return pureString.split(",").size == 1
}

fun isNameLengthBelowFiveValidation(nameList: List<String>): Boolean {
return nameList.all{it.length<=5}
}

fun isNumberTrialCountValidation(trialCount: Int?) : Boolean {
return trialCount != null
}

fun runOneRound(CarNames: List<String>, moveResult: MutableList<String>): MutableList<String> {
for(index in CarNames.indices) {
val moveOrNot = Randoms.pickNumberInRange(MIN_VALUE, MAX_VALUE)
if(moveOrNot >= 4)
moveResult[index] += "-"
}
return moveResult
}

fun printOneRound(CarNames: List<String>, moveResult: MutableList<String>) {
for(index in CarNames.indices)
println("${CarNames[index]} : ${moveResult[index]}")
}


fun getWinnerNames(carNames: List<String>, moveResult: MutableList<String>): String {
val countOfMove = moveResult.map { it.length }
val maxMoveLength = countOfMove.maxOrNull()
val winnerList = mutableListOf<String>()

for ((index, length) in countOfMove.withIndex()) {
if (length == maxMoveLength) {
winnerList.add(carNames[index])
}
}

return winnerList.joinToString(", ")
}
8 changes: 8 additions & 0 deletions src/test/kotlin/study/StringTest.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package study

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import racingcar.isOnlyBlankValidation

class StringTest {
@Test
Expand Down Expand Up @@ -41,4 +43,10 @@ class StringTest {
input[5]
}
}

@Test
fun `isOnlyBlankValidation - non-blank input`() {
val input = "not blank"
assertEquals(false, isOnlyBlankValidation(input))
}
}