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

[숫자 야구 게임] 박희원 미션 제출합니다. #212

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
22 changes: 22 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
## 구현할 기능 정리

1. 게임 시작 전
- 게임 시작 안내 문구 출력

2. 게임 시작
- 컴퓨터의 랜덤한 숫자 저장
- 유저가 입력한 숫자 저장
- 예외 처리
- 3자리의 숫자가 아닌 경우 `IllegalArgumentException` 발생
- 1 ~ 9까지의 숫자가 아닌경우 `IllegalArgumentException` 발생
- null인 경우 `IllegalArgumentException` 발생
- 컴퓨터의 수와 유저의 수 비교
- 자리와 수 모두 같으면 `스트라이크` 판정
- 숫자만 같으면 `볼` 판정
- 아무것도 일치하지 않으면 `낫싱`판정
- `3 스트라이크`달성 시 `게임 종료` 판정

3. 게임 종료
- 게임 종료 시 `1` 입력, `새로운 게임 시작`
- 게임 종료 시 `2` 입력, `완전히 게임 종료`

8 changes: 8 additions & 0 deletions local.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
## This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Wed Oct 25 20:43:21 KST 2023
sdk.dir=/Users/heewonparknm1pro/Library/Android/sdk
83 changes: 82 additions & 1 deletion src/main/kotlin/baseball/Application.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,86 @@
package baseball

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

fun main() {
TODO("프로그램 구현")
println("숫자 야구 게임을 시작합니다.")

playGame()

while (true) {
print("게임을 새로 시작하려면 1, 종료하려면 2을 입력하세요: ")
val input = Console.readLine()
if (input == "2") {
break
} else if (input == "1") {
playGame()
}
else {
throw IllegalArgumentException("잘못된 입력입니다.")
}
Comment on lines +14 to +21
Copy link

@stopkite stopkite Oct 25, 2023

Choose a reason for hiding this comment

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

이부분은 다음에 when 절로 표현해보는 것도 좋을 것 같아요!
when 절을 통해 else if문을 줄이고 더 간결하게 표현이 가능할 것 같아요!
또한, 추후에 만약 "3"이라는 조건이 추가된다면 불필요한 else if를 또 써야하는 상황이 올 수도 있으니까요!

when(input) {
    1 -> playGame()
    2 -> break
    else -> throw
} 

이런식으로요 :)

}

println("게임 종료!")
}

fun playGame() { // 게임 시작
val computerNumbers = generateComputerNumbers()

while (true) {
val userGuess = getUserInput()

val result = checkGuess(userGuess, computerNumbers)
println("결과: $result")

if (result == "3스트라이크") {

Choose a reason for hiding this comment

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

게임 종료 조건을 result == "3스트라이크"으로 설정하면 해당 문구를 변경시 해당 코드를 수정해야 한다는 문제가 발생할 수 있습니다.
별도의 변수로 선언하시거나 출력 문구를 만드는 함수를 별도로 작성하시면 좋을 것 같습니다.

println("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
break
}
}

println("게임 종료")
}


fun generateComputerNumbers(): List<Int> { // 컴퓨터 랜덤 변수 설정
val numbers = mutableListOf<Int>()
while (numbers.size < 3) {

Choose a reason for hiding this comment

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

3이 어떤 의미의 숫자인지 이해 할 수 있도록 별도의 상수로 만들어 사용하면 좋을 것 같습니다.

val randomNum = Randoms.pickNumberInRange(1, 9)
if (randomNum !in numbers) {
numbers.add(randomNum)
}
}
return numbers
}

fun getUserInput(): List<Int> { // 유저 입력값 받고 예외처리
print("숫자를 입력해주세요 : ")
val input = Console.readLine()

if (input == null || input.length != 3 || !input.all { it in '1'..'9' } || input.toSet().size != 3) {
throw IllegalArgumentException("잘못된 입력입니다. 서로 다른 3자리 숫자를 입력하세요.")
}
Comment on lines +61 to +63
Copy link

@stopkite stopkite Oct 25, 2023

Choose a reason for hiding this comment

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

이 조건들은 함수 또는 변수로 따로 빼볼 수도 있을 것 같아요!
변수로 한 번 예시를 들어보자면

val isEmptyOrNull = if(input == null)
val isNotThreeLength = if(input.length != 3)
val isInRange = if(!input.all {it in '1'..'9'}

로 해서
if(isEmptyOrNull || isNotThreeLength || isNotInRange) { ... }
이런식으로 가독성이 좋게 작성해볼수도 있을 것 같아요 :) !!


return input.map { it.toString().toInt() }
}

fun checkGuess(userGuess: List<Int>, computerNumbers: List<Int>): String { // 스트라이크/볼/낫싱 판정
var strikes = 0
var balls = 0

for (i in userGuess.indices) {
if (userGuess[i] == computerNumbers[i]) {
strikes++
} else if (userGuess[i] in computerNumbers) {
balls++
}
}

return when {
strikes == 3 -> "3스트라이크"
strikes > 0 || balls > 0 -> "${balls}볼 ${strikes}스트라이크"

Choose a reason for hiding this comment

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

strike가 0 이고 ball이 1인 경우 "1볼"이 아니라 "1볼 0스트라이크" 가 출력이 될 것 같은데
이렇게 작성해도 ball이나 strike가 0인 경우 1가지만 출력이 가능한가요?

else -> "낫싱"
}
}