-
Notifications
You must be signed in to change notification settings - Fork 6
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
[Lv_1 - Lv_6] 게임 시작 부분, 값 비교 등 구현 - 박채현 #21
base: Chae-Hyun
Are you sure you want to change the base?
Changes from 11 commits
4eb1d43
90ed646
c56fdf5
8257905
1aa0f80
1ef9c4a
e131d66
a46004e
9eb2663
e4f4c17
56f780f
133d4ec
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<Bucket | ||
uuid = "3C6C94EE-9FB9-455B-9754-A7CEB2007EA8" | ||
type = "1" | ||
version = "2.0"> | ||
</Bucket> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | ||
<plist version="1.0"> | ||
<dict> | ||
<key>SchemeUserState</key> | ||
<dict> | ||
<key>Week2-BaseballGame.xcscheme_^#shared#^_</key> | ||
<dict> | ||
<key>orderHint</key> | ||
<integer>0</integer> | ||
</dict> | ||
</dict> | ||
</dict> | ||
</plist> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,186 @@ | ||
// | ||
// baseballGame.swift | ||
// Week2-BaseballGame | ||
// | ||
// Created by CHYUN on 11/5/24. | ||
// | ||
|
||
|
||
class BaseballGame { | ||
|
||
// 기록 매니저 | ||
private var recordManager: RecordManager | ||
private var printManager: PrintManager | ||
init(recordManager: RecordManager, printManager: PrintManager) { | ||
self.recordManager = recordManager | ||
self.printManager = printManager | ||
} | ||
|
||
|
||
// 게임 상태 | ||
private var gameStatus: GameStatus = .on { | ||
willSet(newStatus) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. willset을 활용해 case마다 print가 실행되게 해 주셨군요! |
||
switch newStatus { | ||
case .on : printManager.printGuideance(guide: Guidance.welcome) | ||
case .off : printManager.printGuideance(guide: Guidance.gameEnd) | ||
} | ||
} | ||
} | ||
|
||
// 게임 시작 | ||
func startGame() { | ||
|
||
gameStatus = .on | ||
commandLoop : while true { | ||
let command = readLine()!.replacingOccurrences(of: " ", with: "") | ||
|
||
switch command { | ||
case "1": | ||
playGame() | ||
break commandLoop | ||
case "2": | ||
recordManager.showRecord() | ||
printManager.printGuideance(guide: Guidance.inputAgain) | ||
|
||
case "3": | ||
gameStatus = .off | ||
break commandLoop | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. switch case에서 반복문을 break하기 위한 문법 사용 좋습니다~ |
||
default : | ||
printManager.printError(error: InputError.invalidInputError) | ||
printManager.printGuideance(guide: Guidance.inputAgain) | ||
} | ||
} | ||
} | ||
|
||
|
||
func playGame() { | ||
|
||
let answer = newGame() // 랜덤 값 받아오기 | ||
var score = Score() | ||
var tryCount = 0 | ||
|
||
|
||
while gameStatus == .on { | ||
|
||
// 플레이어에게 값 받기 | ||
let playerInput = getPlayerInput() | ||
|
||
do { | ||
// 예외 없을 경우 | ||
let playerInputAsArray = try checkError(input: playerInput) | ||
|
||
score = calculateScore(playerInput: playerInputAsArray, answer: answer) | ||
|
||
if score.strikeCount == GameConfig.numberOfAnswer { | ||
printManager.printGuideance(guide: Guidance.hit) | ||
recordManager.recordSet(tries: tryCount + 1) | ||
startGame() | ||
} else if score.outCount == GameConfig.numberOfAnswer { | ||
printManager.printGuideance(guide: Guidance.out) | ||
} else { | ||
print("\(score.strikeCount) \(Guidance.strike) \(score.ballCount) \(Guidance.ball)") | ||
} | ||
|
||
score = Score() | ||
tryCount += 1 | ||
|
||
// 예외 경우 | ||
} catch InputError.inputCountError { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 각각의 error를 catch해서 printManager에 전달하는 방법 보다 좋은 방법이 있을 수도 있을 것 같아요! |
||
printManager.printError(error: InputError.inputCountError) | ||
|
||
} catch InputError.invalidInputError { | ||
printManager.printError(error: InputError.invalidInputError) | ||
|
||
} catch InputError.zeroInputError { | ||
printManager.printError(error: InputError.zeroInputError) | ||
|
||
} catch InputError.duplicateValueError { | ||
printManager.printError(error: InputError.duplicateValueError) | ||
} catch { | ||
printManager.printError(error: InputError.unknownError) | ||
} | ||
} | ||
|
||
} | ||
|
||
|
||
private func calculateScore(playerInput: [Int], answer: [Int]) -> Score { | ||
var score = Score() | ||
for (index, number) in playerInput.enumerated() { | ||
if answer [index] == number { | ||
score.strikeCount += 1 | ||
} else if answer.contains(number) { | ||
score.ballCount += 1 | ||
} else { | ||
score.outCount += 1 | ||
} | ||
} | ||
return score | ||
} | ||
|
||
|
||
// 랜덤 값 추출 | ||
private func newGame() -> [Int] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 랜덤 값을 추출하는 기능만을 가진다면, 함수명에 해당 기능을 더 잘 나타내는 이름을 붙이면 좋을 것 같아요! |
||
var answer: [Int] = [] | ||
var questionBoxes = "" | ||
var range = GameConfig.rangeOfAnswerWithoutZero | ||
|
||
while answer.count < GameConfig.numberOfAnswer { | ||
|
||
let randomNumber = Int.random(in: range) | ||
if !answer.contains(randomNumber) { | ||
answer.append(randomNumber) | ||
range = GameConfig.rangeOfAnswerWithZero // 랜덤 범위 - 0을 포함한 범위로 변경 | ||
questionBoxes.append("[ ? ] ") | ||
} | ||
} | ||
|
||
printManager.printGuideance(guide: Guidance.gameStart) | ||
print(questionBoxes) | ||
|
||
print(answer) //test | ||
return answer | ||
} | ||
|
||
// 입력 값 받아와서 필요한 처리 후 리턴 | ||
private func getPlayerInput() -> String { | ||
printManager.printGuideance(guide: Guidance.requireInput) | ||
return readLine()?.trimmingCharacters(in: .whitespaces) ?? "" | ||
} | ||
|
||
|
||
// 예외 상황 체크 | ||
private func checkError(input: String) throws -> [Int] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이것도 입력값에 대한 예외처리 체크라는 의도를 더 잘 나타낼 수 있는 이름이면 좋지 않을까 생각해 봅니다! |
||
|
||
// 한 자씩 파악하기 위해 배열로 쪼개기 | ||
let inputAsStringArray = input.split(separator: "") | ||
|
||
// 1. 입력 값 개수가 요구치와 다른지 체크 | ||
guard inputAsStringArray.count == GameConfig.numberOfAnswer else { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이미 알고 계시겠지만 String 값 자체에서도 count를 얻어올 수 있는 점 공유드립니다~! |
||
throw InputError.inputCountError | ||
} | ||
|
||
// String 배열 -> Int 배열 | ||
let inputAsIntArray = inputAsStringArray.map({ Int($0) }) | ||
|
||
// 2. String값 Int로 바꿀경우 nil, 숫자 아닌 값 입력되었는지 체크 | ||
guard !inputAsIntArray.contains(nil) else { | ||
throw InputError.invalidInputError | ||
} | ||
|
||
// 3. 0이 첫 자리에 입력되었는지 체크 | ||
guard inputAsIntArray.first != 0 else { | ||
throw InputError.zeroInputError | ||
} | ||
|
||
// 4. 중복 값 입력되었는지 체크 | ||
guard Set(inputAsIntArray).count == inputAsIntArray.count else { | ||
throw InputError.duplicateValueError | ||
} | ||
|
||
// 모든 예외 상황이 아닐 경우 값비 교를 위한 배열 리턴, 위에서 nil 체크 완료 | ||
return inputAsIntArray.map({ $0! }) | ||
|
||
} | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 채현님 고수시니까 요 부분도 살짝 말씀드릴게요! struct SomeStruct {
func someFunction() {
}
<-- 요기 빈 줄이 있을 때도 있고 없을 때도 있는데요, 이러한 컨벤션도 일관적으로 지켜주시면 더욱 깔끔한 코드가 될 것 같아요!
} |
||
} |
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
This file was deleted.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
class 안에서 recordManager = RecordManager()와 같은 방식으로 작성했었어도 되었을 것 같은데, 외부에서 주입받으시는 이유가 궁금합니다~