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

[숫자 야구 게임] 김세연 미션 제출합니다. #218

Open
wants to merge 8 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
9 changes: 9 additions & 0 deletions docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# 기능 목록

- [x] 기본 입력 및 변수 설정
- [x] 잘못된 입력 시 IllegalArgumentException 발생 및 종료
- [x] 0 입력도 예외 처리
- [x] 컴퓨터 랜덤 3자리의 숫자 발생
- [x] 볼/스트라이크 판단
- [x] 출력 결과 확인
- [x] 테스트 케이스 실행
58 changes: 57 additions & 1 deletion src/main/kotlin/baseball/Application.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,61 @@
package baseball

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

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

while (true) {
val comArr = getComputerNum()
while (true) {
print("숫자를 입력해주세요 : ")
val userNum = Console.readLine()
val userArr = mutableListOf<Int>()

if (userNum?.length != 3) throw IllegalArgumentException()
for (i in userNum) {
if (!i.isDigit() || userArr.contains(i.digitToInt()) || i == '0') throw IllegalArgumentException()
userArr.add(i.digitToInt())
}

val result = playGame(userArr, comArr)
println(result)
if (result == "3스트라이크") break
}
println("3개의 숫자를 모두 맞히셨습니다! 게임 종료")
println("게임을 새로 시작하려면 1, 종료하려면 2를 입력하세요.")
val again = Console.readLine()
if (again == "1") continue
else if (again == "2") break
else throw IllegalArgumentException()
}

Console.close()
}

fun getComputerNum(): MutableList<Int> {
val com = mutableListOf<Int>()
while (com.size < 3) {
val rand = Randoms.pickNumberInRange(1, 9)
if (!com.contains(rand)) com.add(rand)
}
return com
}

fun playGame(user: List<Int>, com: List<Int>): String {
var ball = 0
var strike = 0
for (i in 0..2) {
if (com.contains(user[i])) {
if (com[i] == user[i]) strike++
else ball++
}
}
var result = ""
if (ball > 0) result += "${ball}볼"
if (ball > 0 && strike > 0) result += " "
if (strike > 0) result += "${strike}스트라이크"
if (ball == 0 && strike == 0) result = "낫싱"
return result
}