Skip to content
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,15 @@
# kotlin-racingcar-precourse

<img width="1086" height="768" alt="image" src="https://github.com/user-attachments/assets/9eebe52c-57e4-4ee3-ba96-e24cd1bbccfd" />

## 기능 목록
1. 자동차 이름을 입력한다. 이때 5자 이상일 경우 IlegalArgumentException이 발생된다.
2. 사용자가 이동할 횟수를 입력한다. 이때 숫자가 아닌 다른 값이 들어가면 IllecgalArgumentException이 발생된다.
3. 각 자동차 별 이동할 횟수를 정할 Map을 만든다.
4. 0 ~ 9사이의 램덤숫자를 골라서 0 ~ 3일 경우 멈춤, 4~9일경우 전진을 할 함수를 구현한다.
전진되는 숫자는 Map의 value값 + 1을 한다.
5. 위너를 뽑는 함수를 구현한다.
Map의 value중 최대값을 가져온다.
최대값이 포함된 키값을 가져온다(이를 통해 위너자동차를 정한다) ㅁ
6. 진행과정을 보여줄 함수를 구현한다.

72 changes: 72 additions & 0 deletions src/main/kotlin/racingcar/Application.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,77 @@
package racingcar

import camp.nextstep.edu.missionutils.Console.readLine
import camp.nextstep.edu.missionutils.Randoms
import net.bytebuddy.pool.TypePool.Resolution.Illegal

fun main() {
// TODO: 프로그램 구현
println("경주할 자동차 이름을 입력하세요.(이름은 쉼표(,) 기준으로 구분)")
val input = readLine()!!
val carList: MutableList<String> = input.split(",").map { it.trim() }.toMutableList()

//if(carList.filter{it.length > 5}.isNotEmpty()) throw IllegalArgumentException()
// any(조건)조건에 만족하는 요소 하나라도 있으면 true반환
if (carList.any { it.length > 5 }) throw IllegalArgumentException("자동차이름은 5자 이하여야 합니다.")

println("시도할 횟수는 몇 회인가요?")
val inputNum = readLine()!!
var count: Int = 0
try {
count = inputNum.toInt()
} catch (e: Exception) {
throw IllegalArgumentException("숫자를 입력해주세요")
}

val carPositions = mutableMapOf<String, Int>()
//자동차 멤버 초기화
for (name in carList) {
carPositions[name] = 0
}

repeat(count){
pickRandomNumberAndSetNumber(carList, carPositions)
printStatus(carList, carPositions)
}

printWinner(carList, carPositions)

}

fun pickRandomNumberAndSetNumber(carList: MutableList<String>, carPositions: MutableMap<String, Int>) {
for (name in carList) {
val result = Randoms.pickNumberInRange(0, 9)
if(result >= 4) {
carPositions[name] = (carPositions[name] ?: 0) + 1
}
}
}

fun printWinner(carList: MutableList<String>, carPositions: MutableMap<String, Int>) {
//최대값 가져오기
val max = carPositions.values.maxOrNull() ?: 0
//값으로 키값찾기
val winner = carPositions.filter { it.value == max }.keys
print("최종 우승자 : ${winner.joinToString(", ")}")

}


fun printStatus(carList: List<String>, carPositions: Map<String, Int>) {
for (name in carList) {
print("$name : ")

// 전진 횟수만큼 "-" 출력
val position = carPositions[name]!!
for (i in 0 until position) {
print("-")
}
println() // 줄바꿈
}
println() // 빈 줄
}





43 changes: 43 additions & 0 deletions src/test/kotlin/racingcar/ApplicationTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,49 @@ class ApplicationTest : NsTest() {
}
}

@Test
fun `예외 테스트 -시도 횟수에 문자열 입력 시`() {
assertSimpleTest {
assertThrows<IllegalArgumentException> {
runException("ka", "김")
}
}
}

@Test
fun `렌덤값이 4이상이면 자동차 전진한다`() {
assertRandomNumberInRangeTest(
{
run("pobi,woni", "1")
assertThat(output().contains("pobi : -"))
},
4
)
}

@Test
fun `단독우승자 있는 경우`(){
assertRandomNumberInRangeTest(
{
run("pobi,woni", "1")
assertThat(output().contains("최종우승자: pobi"))
},
MOVING_FORWARD, STOP
)
}

@Test
fun `공동 우승자 있는 경우`(){
assertRandomNumberInRangeTest(
{
run("pobi,woni", "1")
assertThat(output().contains("최종우승자: pobi, woni"))
},
MOVING_FORWARD, MOVING_FORWARD, STOP
)
}


override fun runMain() {
main()
}
Expand Down