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

[Lv_1 - Lv_6] 게임 시작 부분, 값 비교 등 구현 - 박채현 #21

Open
wants to merge 12 commits into
base: Chae-Hyun
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 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
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
Expand All @@ -258,6 +259,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
MACOSX_DEPLOYMENT_TARGET = 15.0;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
};
Expand Down
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>
186 changes: 186 additions & 0 deletions Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift
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) {
Copy link
Contributor

Choose a reason for hiding this comment

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

class 안에서 recordManager = RecordManager()와 같은 방식으로 작성했었어도 되었을 것 같은데, 외부에서 주입받으시는 이유가 궁금합니다~

self.recordManager = recordManager
self.printManager = printManager
}


// 게임 상태
private var gameStatus: GameStatus = .on {
willSet(newStatus) {
Copy link
Contributor

Choose a reason for hiding this comment

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

willset을 활용해 case마다 print가 실행되게 해 주셨군요!
제 개인적인 생각으로는 변수에 값을 할당했을 때 print가 수행되는 구조는 직관적이지 못할 수 있을 것 같아요.
만약 gameStatus 변수가 다른 파일로 분리되어 있고, 코드를 처음 보는 누군가가 startGame 메소드를 읽고 있다면, gameStatus = .on 코드에서 무엇가 출력되겠다는 예상을 하기 어려울 것 같습니다!

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
Copy link
Contributor

Choose a reason for hiding this comment

The 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 {
Copy link
Contributor

Choose a reason for hiding this comment

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

각각의 error를 catch해서 printManager에 전달하는 방법 보다 좋은 방법이 있을 수도 있을 것 같아요!
만약 에러가 늘어나거나 줄어드는 등 변경된다면 catch문도 계속해서 변경되어야 하는 문제가 예상됩니다..!

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] {
Copy link
Contributor

Choose a reason for hiding this comment

The 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] {
Copy link
Contributor

Choose a reason for hiding this comment

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

이것도 입력값에 대한 예외처리 체크라는 의도를 더 잘 나타낼 수 있는 이름이면 좋지 않을까 생각해 봅니다!


// 한 자씩 파악하기 위해 배열로 쪼개기
let inputAsStringArray = input.split(separator: "")

// 1. 입력 값 개수가 요구치와 다른지 체크
guard inputAsStringArray.count == GameConfig.numberOfAnswer else {
Copy link
Contributor

Choose a reason for hiding this comment

The 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! })

}

Copy link
Contributor

Choose a reason for hiding this comment

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

채현님 고수시니까 요 부분도 살짝 말씀드릴게요!

struct SomeStruct {
  func someFunction() {

  }
  <-- 요기 빈 줄이 있을 때도 있고 없을 때도 있는데요, 이러한 컨벤션도 일관적으로 지켜주시면 더욱 깔끔한 코드가 될 것 같아요!
}

}

This file was deleted.

21 changes: 0 additions & 21 deletions Week2-BaseballGame/Week2-BaseballGame/Lv_2(필수구현).swift

This file was deleted.

15 changes: 0 additions & 15 deletions Week2-BaseballGame/Week2-BaseballGame/Lv_3(도전구현).swift

This file was deleted.

24 changes: 0 additions & 24 deletions Week2-BaseballGame/Week2-BaseballGame/Lv_4(도전구현).swift

This file was deleted.

20 changes: 0 additions & 20 deletions Week2-BaseballGame/Week2-BaseballGame/Lv_5(도전구현).swift

This file was deleted.

26 changes: 0 additions & 26 deletions Week2-BaseballGame/Week2-BaseballGame/Lv_6(도전구현).swift

This file was deleted.

Loading