From 4eb1d43704a9526f36f6cc7683ed1fb79c201794 Mon Sep 17 00:00:00 2001 From: chhue Date: Tue, 5 Nov 2024 16:48:13 +0900 Subject: [PATCH 01/12] =?UTF-8?q?[Feat]=20=EA=B2=8C=EC=9E=84=20=EC=8B=9C?= =?UTF-8?q?=EC=9E=91=20=EA=B8=B0=EB=8A=A5=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - BaseballGame 클래스 내 게임 시작 메소드 구현 - 답 배열의 count가 일정 개수가 될 때까지 랜덤숫자 추출 반복, 동일한 수가 없을 때만 append - 게임 시작 메시지 출력 --- .../project.pbxproj | 2 + .../xcschemes/xcschememanagement.plist | 14 +++++++ .../Week2-BaseballGame/baseballGame.swift | 39 +++++++++++++++++++ .../Week2-BaseballGame/main.swift | 28 +------------ 4 files changed, 57 insertions(+), 26 deletions(-) create mode 100644 Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift diff --git a/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/project.pbxproj b/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/project.pbxproj index b5ea2cd..0695a57 100644 --- a/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/project.pbxproj +++ b/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/project.pbxproj @@ -249,6 +249,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; + MACOSX_DEPLOYMENT_TARGET = 15.0; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; }; @@ -258,6 +259,7 @@ isa = XCBuildConfiguration; buildSettings = { CODE_SIGN_STYLE = Automatic; + MACOSX_DEPLOYMENT_TARGET = 15.0; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_VERSION = 5.0; }; diff --git a/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcschemes/xcschememanagement.plist b/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..dfbd5af --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + Week2-BaseballGame.xcscheme_^#shared#^_ + + orderHint + 0 + + + + diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift new file mode 100644 index 0000000..81af61a --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -0,0 +1,39 @@ +// +// baseballGame.swift +// Week2-BaseballGame +// +// Created by CHYUN on 11/5/24. +// + + +class BaseballGame { + + enum GameMessage: String { + case start = "Game Start", + input = "please input your number", + end = "Game End", + strike = "Strike", + ball = "Ball", + out = "Out" + } + + + private var answer: [Int] = [] + private let numberOfAnsewer = 3 + + func startNewSet() { + + /** + * answer의 count가 numberOfAnswer가 될 때까지 0에서 9이내의 랜덤 Int 추출 반복 + * 동일한 수가 없을 때만 append + **/ + while answer.count < numberOfAnsewer { + let randomNumber = Int.random(in: 0...9) + if !answer.contains(randomNumber) { + answer.append(randomNumber) + } + } + print(GameMessage.start.rawValue) + print(answer) //test + } +} diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/main.swift index 36bba57..d0ab42e 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/main.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/main.swift @@ -1,29 +1,5 @@ import Foundation -func startGame() { - print("레벨을 선택하세요 (1, 2, 4, 5, 6):") - - if let input = readLine(), let level = Int(input) { - switch level { - case 1: - levelOne() - case 2: - levelTwo() - case 3: - levelThree() - case 4: - levelFour() - case 5: - levelFive() - case 6: - levelSix() - default: - print("유효하지 않은 레벨입니다. 1~6까지를 선택해주세요.") - } - } else { - print("잘못된 입력입니다.") - } -} - // 게임 시작 -startGame() +BaseballGame().startNewSet() + From 90ed646281d5e91881a127d2120f3a03458fd581 Mon Sep 17 00:00:00 2001 From: chhue Date: Tue, 5 Nov 2024 22:42:01 +0900 Subject: [PATCH 02/12] =?UTF-8?q?[Feat]=20=EC=9E=85=EB=A0=A5=EA=B0=92=20?= =?UTF-8?q?=EC=98=AC=EB=B0=94=EB=A5=B8=EC=A7=80=20=ED=99=95=EC=9D=B8?= =?UTF-8?q?=ED=9B=84=20=EC=8A=A4=ED=8A=B8=EB=9D=BC=EC=9D=B4=ED=81=AC=20/?= =?UTF-8?q?=20=EB=B3=BC=20=EA=B0=9C=EC=88=98=20=EC=B9=B4=EC=9A=B4=ED=8A=B8?= =?UTF-8?q?=ED=95=98=EC=97=AC=20=EC=B6=9C=EB=A0=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 입력값이 올바르지 않은 경우 Error로 정의 입력값을 guard문으로 나누어 Error 던져주는 메소드 정의 do문에서 해당 Error 받아 올바르게 작동되는 경우 Strike/Ball 개수 파악, catch문에서 Error에 따른 오류메시지 출력 --- .../xcdebugger/Breakpoints_v2.xcbkptlist | 6 + .../Week2-BaseballGame/baseballGame.swift | 149 ++++++++++++++++-- .../Week2-BaseballGame/main.swift | 7 +- 3 files changed, 145 insertions(+), 17 deletions(-) create mode 100644 Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist diff --git a/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 0000000..f5837ed --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame.xcodeproj/xcuserdata/chaehyunpark.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,6 @@ + + + diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index 81af61a..ac28a83 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -5,35 +5,152 @@ // Created by CHYUN on 11/5/24. // - class BaseballGame { enum GameMessage: String { - case start = "Game Start", - input = "please input your number", - end = "Game End", - strike = "Strike", - ball = "Ball", - out = "Out" + case gemeStartMessage = "Game Start", + requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter.", + gameEndMessage = "Game End", + strikeMessage = "Strike", + ballMessage = "Ball", + outMessage = "Out" + + static func printGuidanceMessage(message: GameMessage) { + print(message.rawValue) + } + } + + enum InputError: Error { + case inputCountError, + invalidInputError, + zeroInputError, + duplicateValueError, + unknownError + + static func printErrorMessage(error: InputError) { + + var message = "" + + switch error { + case inputCountError: + message = "The number of inputs is insufficient." + case invalidInputError: + message = "Invalid input." + case zeroInputError: + message = "Zero is not allowed." + case duplicateValueError: + message = "There are duplicate values." + case unknownError: + message = "There are unknown errors." + } + + print(message) + } } - private var answer: [Int] = [] - private let numberOfAnsewer = 3 + private let numberOfAnswer = 3 + private var playerInput: [Int?] = [] + private let rangeOfAnswer = 1...9 + func startNewSet() { - /** - * answer의 count가 numberOfAnswer가 될 때까지 0에서 9이내의 랜덤 Int 추출 반복 - * 동일한 수가 없을 때만 append - **/ - while answer.count < numberOfAnsewer { - let randomNumber = Int.random(in: 0...9) + var questionBoxes = "" + + while answer.count < numberOfAnswer { + let randomNumber = Int.random(in: rangeOfAnswer) if !answer.contains(randomNumber) { answer.append(randomNumber) + questionBoxes = questionBoxes + "[ ? ] " } } - print(GameMessage.start.rawValue) + + GameMessage.printGuidanceMessage(message: .gemeStartMessage) + print(questionBoxes) + print(answer) //test } + + func getPlayerInput() { + + GameMessage.printGuidanceMessage(message: .requireInputMessage) + + /** 값 비교 전 체크 필요 + * [ 해결 가능 - 제일 먼저 체크 ] + * 1. 공백 문자 삽입 여부 + * -------------> 공백 제외 후 비교 + * + * [ 입력 개수 파악 ] + * 2. 입력 값 개수가 numberOfAnswer보다 부족 (입력 값 없을 경우 포함) + * + * [ 올바르지 않은입력 값 파악 ] + * 3. Int 값 외 + * 4. 0 입력 + * 5. 중복 숫자 입력 + * -------------> 다시 입력 받기 + **/ + + var tempInput = readLine()! + tempInput.replace(" " , with: "") + + do { + // 이상 없이 정상 진행될 경우 + playerInput = try checkError(playerInput: tempInput) + + var strikeCount = 0 + var ballCount = 0 + for index in playerInput.startIndex...playerInput.count - 1 { + answer[index] == playerInput[index]! ? strikeCount += 1 : nil + answer.contains(playerInput[index]!) && answer[index] != playerInput[index]! ? ballCount += 1 : nil + } + + print("\(strikeCount) \(GameMessage.strikeMessage.rawValue) \(ballCount) \(GameMessage.ballMessage.rawValue)") + + + } catch InputError.inputCountError { + InputError.printErrorMessage(error: InputError.inputCountError) + + } catch InputError.invalidInputError { + InputError.printErrorMessage(error: InputError.invalidInputError) + + } catch InputError.zeroInputError { + InputError.printErrorMessage(error: InputError.zeroInputError) + + } catch InputError.duplicateValueError { + InputError.printErrorMessage(error: InputError.duplicateValueError) + + } catch { + InputError.printErrorMessage(error: InputError.unknownError) + } + + + } + + private func checkError(playerInput: String) throws -> [Int?] { + + let inputAsStringArray = playerInput.split(separator: "") + + guard inputAsStringArray.count == numberOfAnswer else { + throw InputError.inputCountError + } + + let inputAsIntArray = inputAsStringArray.map({ Int($0) }) + + guard !inputAsIntArray.contains(nil) else { + throw InputError.invalidInputError + } + + guard !inputAsIntArray.contains(0) else { + throw InputError.zeroInputError + } + + guard Set(inputAsIntArray).count == inputAsIntArray.count else { + throw InputError.duplicateValueError + } + + return inputAsIntArray + + } + } diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/main.swift index d0ab42e..463cc5c 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/main.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/main.swift @@ -1,5 +1,10 @@ import Foundation // 게임 시작 -BaseballGame().startNewSet() +//let test = [5,7,6,0,0] +//print(BaseballGame().isThereDuplicateValue(array: test)) +let baseballGame = BaseballGame() +baseballGame.startNewSet() +baseballGame.getPlayerInput() + From c56fdf548de31ce3560e2da3819431593c6bd0ae Mon Sep 17 00:00:00 2001 From: chhue Date: Tue, 5 Nov 2024 22:53:00 +0900 Subject: [PATCH 03/12] =?UTF-8?q?[Feat]=20=ED=8F=AC=ED=95=A8=EB=90=9C=20?= =?UTF-8?q?=EC=88=AB=EC=9E=90=20=EC=97=86=EC=9D=84=20=EA=B2=BD=EC=9A=B0=20?= =?UTF-8?q?=EC=95=84=EC=9B=83=EB=A9=94=EC=8B=9C=EC=A7=80=20=EC=B6=9C?= =?UTF-8?q?=EB=A0=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit outCount 변수를 만들고 입력값 체크하는 반복문에서 포함되지 않을 때마다 +1 outCount가 입력한 자리 수와 동일할 경우 (= 모든 자리가 일치하지 않을 경우) 아웃 메시지 출력 --- .../Week2-BaseballGame/baseballGame.swift | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index ac28a83..2329666 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -13,7 +13,7 @@ class BaseballGame { gameEndMessage = "Game End", strikeMessage = "Strike", ballMessage = "Ball", - outMessage = "Out" + outMessage = "Out!" static func printGuidanceMessage(message: GameMessage) { print(message.rawValue) @@ -100,12 +100,19 @@ class BaseballGame { var strikeCount = 0 var ballCount = 0 + var outCount = 0 for index in playerInput.startIndex...playerInput.count - 1 { answer[index] == playerInput[index]! ? strikeCount += 1 : nil answer.contains(playerInput[index]!) && answer[index] != playerInput[index]! ? ballCount += 1 : nil + !answer.contains(playerInput[index]!) ? outCount += 1 : nil + } + + if outCount == playerInput.count { + GameMessage.printGuidanceMessage(message: GameMessage.outMessage) + } else { + print("\(strikeCount) \(GameMessage.strikeMessage.rawValue) \(ballCount) \(GameMessage.ballMessage.rawValue)") } - print("\(strikeCount) \(GameMessage.strikeMessage.rawValue) \(ballCount) \(GameMessage.ballMessage.rawValue)") } catch InputError.inputCountError { From 825790562564527bf2aa59ebb8f647f991c22887 Mon Sep 17 00:00:00 2001 From: chhue Date: Tue, 5 Nov 2024 23:34:28 +0900 Subject: [PATCH 04/12] =?UTF-8?q?[Feat]=20=EB=A7=9E=EC=B6=9C=20=EA=B2=BD?= =?UTF-8?q?=EC=9A=B0=EC=97=90=EB=8A=94=20=EA=B2=8C=EC=9E=84=20=EC=A2=85?= =?UTF-8?q?=EB=A3=8C,=20=EC=95=84=EB=8B=90=20=EA=B2=BD=EC=9A=B0=20?= =?UTF-8?q?=EA=B3=84=EC=86=8D=20=EC=A7=84=ED=96=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - while문의 조건을 게임 상태가 on일 경우, 반복해서 값을 받고 답에 대한 스트라이크와 볼 개수 출력 - 자리와 숫자가 모두 맞는 strike 변수의 값이 총 입력 값과 동일할 경우 게임 상태를 종료로 변경 -> while문 종료 --- .../Week2-BaseballGame/baseballGame.swift | 99 ++++++++++++------- .../Week2-BaseballGame/main.swift | 2 +- 2 files changed, 62 insertions(+), 39 deletions(-) diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index 2329666..94e3f39 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -13,7 +13,8 @@ class BaseballGame { gameEndMessage = "Game End", strikeMessage = "Strike", ballMessage = "Ball", - outMessage = "Out!" + outMessage = "Out!", + hitMessage = "Hit!" static func printGuidanceMessage(message: GameMessage) { print(message.rawValue) @@ -48,14 +49,21 @@ class BaseballGame { } } + enum GameStatus: Int { + case on = 1, + off = 0 + } + private var answer: [Int] = [] private let numberOfAnswer = 3 - private var playerInput: [Int?] = [] private let rangeOfAnswer = 1...9 + private var gameStatus = GameStatus.off func startNewSet() { + gameStatus = .on + var questionBoxes = "" while answer.count < numberOfAnswer { @@ -72,9 +80,14 @@ class BaseballGame { print(answer) //test } - func getPlayerInput() { - + func getPlayerInput() -> String { GameMessage.printGuidanceMessage(message: .requireInputMessage) + var tempInput = readLine()! + tempInput.replace(" " , with: "") + return tempInput + } + + func playGame() { /** 값 비교 전 체크 필요 * [ 해결 가능 - 제일 먼저 체크 ] @@ -91,48 +104,58 @@ class BaseballGame { * -------------> 다시 입력 받기 **/ - var tempInput = readLine()! - tempInput.replace(" " , with: "") + var strikeCount = 0 + var ballCount = 0 + var outCount = 0 + - do { - // 이상 없이 정상 진행될 경우 - playerInput = try checkError(playerInput: tempInput) + gameLoop : while gameStatus == .on { + + let playerInput = getPlayerInput() - var strikeCount = 0 - var ballCount = 0 - var outCount = 0 - for index in playerInput.startIndex...playerInput.count - 1 { - answer[index] == playerInput[index]! ? strikeCount += 1 : nil - answer.contains(playerInput[index]!) && answer[index] != playerInput[index]! ? ballCount += 1 : nil - !answer.contains(playerInput[index]!) ? outCount += 1 : nil - } + do { + // 이상 없이 정상 진행될 경우 + let playerInputAsArray = try checkError(playerInput: playerInput) + + for index in playerInputAsArray.startIndex...playerInputAsArray.count - 1 { + answer[index] == playerInputAsArray[index]! ? strikeCount += 1 : nil + answer.contains(playerInputAsArray[index]!) && answer[index] != playerInputAsArray[index]! ? ballCount += 1 : nil + !answer.contains(playerInputAsArray[index]!) ? outCount += 1 : nil + } + + print("strikeCount : \(strikeCount), ballCount : \(ballCount), outCount : \(outCount)") - if outCount == playerInput.count { - GameMessage.printGuidanceMessage(message: GameMessage.outMessage) - } else { - print("\(strikeCount) \(GameMessage.strikeMessage.rawValue) \(ballCount) \(GameMessage.ballMessage.rawValue)") + if strikeCount == playerInput.count { + GameMessage.printGuidanceMessage(message: .hitMessage) + gameStatus = .off + } else if outCount == playerInput.count { + GameMessage.printGuidanceMessage(message: .outMessage) + } else { + print("\(strikeCount) \(GameMessage.strikeMessage.rawValue) \(ballCount) \(GameMessage.ballMessage.rawValue)") + + } + + + } catch InputError.inputCountError { + InputError.printErrorMessage(error: .inputCountError) + + } catch InputError.invalidInputError { + InputError.printErrorMessage(error: .invalidInputError) + + } catch InputError.zeroInputError { + InputError.printErrorMessage(error: .zeroInputError) + + } catch InputError.duplicateValueError { + InputError.printErrorMessage(error: .duplicateValueError) + + } catch { + InputError.printErrorMessage(error: .unknownError) } - - - } catch InputError.inputCountError { - InputError.printErrorMessage(error: InputError.inputCountError) - - } catch InputError.invalidInputError { - InputError.printErrorMessage(error: InputError.invalidInputError) - - } catch InputError.zeroInputError { - InputError.printErrorMessage(error: InputError.zeroInputError) - - } catch InputError.duplicateValueError { - InputError.printErrorMessage(error: InputError.duplicateValueError) - - } catch { - InputError.printErrorMessage(error: InputError.unknownError) } - } + private func checkError(playerInput: String) throws -> [Int?] { diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/main.swift index 463cc5c..c55f38d 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/main.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/main.swift @@ -5,6 +5,6 @@ import Foundation //print(BaseballGame().isThereDuplicateValue(array: test)) let baseballGame = BaseballGame() baseballGame.startNewSet() -baseballGame.getPlayerInput() +baseballGame.playGame() From 1aa0f804ce0b70a58ad5f33898541e3a203df5e1 Mon Sep 17 00:00:00 2001 From: chhue Date: Tue, 5 Nov 2024 23:36:27 +0900 Subject: [PATCH 05/12] =?UTF-8?q?[Test]=20=ED=85=8C=EC=8A=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=BD=94=EB=93=9C=20=EC=A3=BC=EC=84=9D=20=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 스트라이크, 볼, 아웃 카운트 출력 주석 처리 --- Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index 94e3f39..f36a5fa 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -123,7 +123,7 @@ class BaseballGame { !answer.contains(playerInputAsArray[index]!) ? outCount += 1 : nil } - print("strikeCount : \(strikeCount), ballCount : \(ballCount), outCount : \(outCount)") +// print("strikeCount : \(strikeCount), ballCount : \(ballCount), outCount : \(outCount)") // test if strikeCount == playerInput.count { GameMessage.printGuidanceMessage(message: .hitMessage) From 1ef9c4aea4f8889aeaa436e6e1c8bd246f6bfe38 Mon Sep 17 00:00:00 2001 From: chhue Date: Wed, 6 Nov 2024 00:12:14 +0900 Subject: [PATCH 06/12] =?UTF-8?q?[Refactor]=20enum=20=EB=82=B4=20=EC=83=81?= =?UTF-8?q?=EC=88=98=EA=B0=92=EC=9D=84=20case=20=EB=8C=80=EC=8B=A0=20stati?= =?UTF-8?q?c=20let=EC=9C=BC=EB=A1=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Week2-BaseballGame/baseballGame.swift | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index f36a5fa..a09630f 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -7,21 +7,21 @@ class BaseballGame { - enum GameMessage: String { - case gemeStartMessage = "Game Start", - requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter.", - gameEndMessage = "Game End", - strikeMessage = "Strike", - ballMessage = "Ball", - outMessage = "Out!", - hitMessage = "Hit!" - - static func printGuidanceMessage(message: GameMessage) { - print(message.rawValue) + private enum GameMessage { + static let gemeStartMessage = "Game Start" + static let requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter." + static let gameEndMessage = "Game End" + static let strikeMessage = "Strike" + static let ballMessage = "Ball" + static let outMessage = "Out!" + static let hitMessage = "Hit!" + + static func printGuidanceMessage(message: String) { + print(message) } } - enum InputError: Error { + private enum InputError: Error { case inputCountError, invalidInputError, zeroInputError, @@ -49,7 +49,7 @@ class BaseballGame { } } - enum GameStatus: Int { + private enum GameStatus: Int { case on = 1, off = 0 } @@ -74,14 +74,14 @@ class BaseballGame { } } - GameMessage.printGuidanceMessage(message: .gemeStartMessage) + GameMessage.printGuidanceMessage(message: GameMessage.gemeStartMessage) print(questionBoxes) print(answer) //test } - func getPlayerInput() -> String { - GameMessage.printGuidanceMessage(message: .requireInputMessage) + private func getPlayerInput() -> String { + GameMessage.printGuidanceMessage(message: GameMessage.requireInputMessage) var tempInput = readLine()! tempInput.replace(" " , with: "") return tempInput @@ -126,12 +126,12 @@ class BaseballGame { // print("strikeCount : \(strikeCount), ballCount : \(ballCount), outCount : \(outCount)") // test if strikeCount == playerInput.count { - GameMessage.printGuidanceMessage(message: .hitMessage) + GameMessage.printGuidanceMessage(message: GameMessage.hitMessage) gameStatus = .off } else if outCount == playerInput.count { - GameMessage.printGuidanceMessage(message: .outMessage) + GameMessage.printGuidanceMessage(message: GameMessage.outMessage) } else { - print("\(strikeCount) \(GameMessage.strikeMessage.rawValue) \(ballCount) \(GameMessage.ballMessage.rawValue)") + print("\(strikeCount) \(GameMessage.strikeMessage) \(ballCount) \(GameMessage.ballMessage)") } From e131d661dfcede9d75d9bc06c35cf867359ffbd4 Mon Sep 17 00:00:00 2001 From: chhue Date: Wed, 6 Nov 2024 00:45:54 +0900 Subject: [PATCH 07/12] =?UTF-8?q?[Feat]=20=EB=B2=94=EC=9C=84=200=EB=B6=80?= =?UTF-8?q?=ED=84=B0=20=EC=8B=9C=EC=9E=91,=20=EC=B2=AB=20=EB=B2=88?= =?UTF-8?q?=EC=A7=B8=20=EC=9E=90=EB=A6=AC=EC=97=90=EB=8A=94=200=EC=9D=B4?= =?UTF-8?q?=20=EC=98=AC=20=EC=88=98=20=EC=97=86=EB=8F=84=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 중복 값이 아닐 경우 배열에 붙이고 첫 번째 인덱스의 값이 0일 경우 제거 구현 했었으나 연속적으로 계속 0이 나올 경우 수없이 반복 - 처음에는 0을 제외한 범위로 랜덤을 돌린 후 값이 붙은 후에는 0을 포함한 범위를 주는 방법으로 구현 --- .../Week2-BaseballGame/baseballGame.swift | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index a09630f..76eef99 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -38,7 +38,7 @@ class BaseballGame { case invalidInputError: message = "Invalid input." case zeroInputError: - message = "Zero is not allowed." + message = "The first position cannot contain a zero." case duplicateValueError: message = "There are duplicate values." case unknownError: @@ -56,7 +56,7 @@ class BaseballGame { private var answer: [Int] = [] private let numberOfAnswer = 3 - private let rangeOfAnswer = 1...9 + private let rangeOfAnswer = 0...9 private var gameStatus = GameStatus.off @@ -67,11 +67,15 @@ class BaseballGame { var questionBoxes = "" while answer.count < numberOfAnswer { + let randomNumber = Int.random(in: rangeOfAnswer) if !answer.contains(randomNumber) { answer.append(randomNumber) questionBoxes = questionBoxes + "[ ? ] " } + if answer[0] == 0 { + answer.remove(at: 0) + } } GameMessage.printGuidanceMessage(message: GameMessage.gemeStartMessage) @@ -171,7 +175,7 @@ class BaseballGame { throw InputError.invalidInputError } - guard !inputAsIntArray.contains(0) else { + guard inputAsIntArray.first != 0 else { throw InputError.zeroInputError } From a46004ebd9767f07b9da32036f46fc40478cd5d3 Mon Sep 17 00:00:00 2001 From: chhue Date: Wed, 6 Nov 2024 01:52:14 +0900 Subject: [PATCH 08/12] =?UTF-8?q?[Feat]=20=EA=B2=8C=EC=9E=84=20=EC=8B=9C?= =?UTF-8?q?=EC=9E=91=EC=8B=9C=20=EC=8B=A4=ED=96=89=ED=95=A0=20=EB=82=B4?= =?UTF-8?q?=EC=9A=A9=20=EC=84=A0=ED=83=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 게임 시작 혹은 기록보기, 게임 종료 선택 가능 - 요구된 숫자 이외 다른 값 입력시 재입력 요구 --- .../Week2-BaseballGame/baseballGame.swift | 93 +++++++++++++------ .../Week2-BaseballGame/main.swift | 4 +- 2 files changed, 68 insertions(+), 29 deletions(-) diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift index 76eef99..5290a07 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift @@ -7,10 +7,17 @@ class BaseballGame { + private enum GameStatus: Int { + case on = 1, + off = 0 + } + private enum GameMessage { - static let gemeStartMessage = "Game Start" + static let welcomeMessage = "Welcome! Please enter the number to execute. \n 1. Game Start 2. History 3. Exit" + static let gemeStartMessage = "*** Game Start ***" static let requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter." - static let gameEndMessage = "Game End" + static let gameEndMessage = "***Game End***" + static let tryAgainMessage = "Try input again." static let strikeMessage = "Strike" static let ballMessage = "Ball" static let outMessage = "Out!" @@ -49,49 +56,78 @@ class BaseballGame { } } - private enum GameStatus: Int { - case on = 1, - off = 0 - } - + private var answer: [Int] = [] private let numberOfAnswer = 3 - private let rangeOfAnswer = 0...9 - private var gameStatus = GameStatus.off + private let rangeOfAnswerWithZero = 0...9 + private let rangeOfAnswerWithoutZero = 1...9 + private var gameStatus: GameStatus = .on { + willSet(newStatus) { + switch newStatus { + case .on : GameMessage.printGuidanceMessage(message: GameMessage.welcomeMessage) + case .off : GameMessage.printGuidanceMessage(message: GameMessage.gameEndMessage) + } + } + } + func startGame() { + gameStatus = .on - func startNewSet() { + commandLoop : while true { + let command = readLine()!.replacingOccurrences(of: " ", with: "") + + switch command { + case "1": + playGame() + break commandLoop + case "2": + lookHistory() + break commandLoop + case "3": + gameStatus = .off + break commandLoop + default : + InputError.printErrorMessage(error: .invalidInputError) + GameMessage.printGuidanceMessage(message: GameMessage.tryAgainMessage) + } + } + } + + private func lookHistory() { - gameStatus = .on + } + + private func getPlayerInput() -> String { + GameMessage.printGuidanceMessage(message: GameMessage.requireInputMessage) + var tempInput = readLine()! + tempInput.replace(" " , with: "") + return tempInput + } + + func playGame() { var questionBoxes = "" + var range = rangeOfAnswerWithoutZero while answer.count < numberOfAnswer { - let randomNumber = Int.random(in: rangeOfAnswer) + let randomNumber = Int.random(in: range) if !answer.contains(randomNumber) { answer.append(randomNumber) + range = rangeOfAnswerWithZero // 랜덤 범위 - 0을 포함한 범위로 변경 questionBoxes = questionBoxes + "[ ? ] " } - if answer[0] == 0 { - answer.remove(at: 0) - } + +// if answer[0] == 0 { +// answer.remove(at: 0) +// } } GameMessage.printGuidanceMessage(message: GameMessage.gemeStartMessage) print(questionBoxes) print(answer) //test - } - - private func getPlayerInput() -> String { - GameMessage.printGuidanceMessage(message: GameMessage.requireInputMessage) - var tempInput = readLine()! - tempInput.replace(" " , with: "") - return tempInput - } - - func playGame() { + /** 값 비교 전 체크 필요 * [ 해결 가능 - 제일 먼저 체크 ] @@ -113,7 +149,7 @@ class BaseballGame { var outCount = 0 - gameLoop : while gameStatus == .on { + while gameStatus == .on { let playerInput = getPlayerInput() @@ -136,8 +172,11 @@ class BaseballGame { GameMessage.printGuidanceMessage(message: GameMessage.outMessage) } else { print("\(strikeCount) \(GameMessage.strikeMessage) \(ballCount) \(GameMessage.ballMessage)") - } + + strikeCount = 0 + ballCount = 0 + outCount = 0 } catch InputError.inputCountError { diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/main.swift index c55f38d..e52d8f2 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/main.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/main.swift @@ -4,7 +4,7 @@ import Foundation //let test = [5,7,6,0,0] //print(BaseballGame().isThereDuplicateValue(array: test)) let baseballGame = BaseballGame() -baseballGame.startNewSet() -baseballGame.playGame() +baseballGame.startGame() +//baseballGame.playGame() From 9eb26638216ffa3c65e919b20a8238576b3238cd Mon Sep 17 00:00:00 2001 From: chhue Date: Wed, 6 Nov 2024 08:42:55 +0900 Subject: [PATCH 09/12] =?UTF-8?q?[Rename]=20=EC=8A=A4=EC=9C=84=ED=94=84?= =?UTF-8?q?=ED=8A=B8=20=ED=8C=8C=EC=9D=BC=EB=AA=85=20=EC=B2=AB=EA=B8=80?= =?UTF-8?q?=EC=9E=90=20=EB=8C=80=EB=AC=B8=EC=9E=90=EB=A1=9C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../{baseballGame.swift => BaseballGame.swift} | 2 +- .../Week2-BaseballGame/{main.swift => Main.swift} | 0 Week2-BaseballGame/Week2-BaseballGame/Model.swift | 7 +++++++ 3 files changed, 8 insertions(+), 1 deletion(-) rename Week2-BaseballGame/Week2-BaseballGame/{baseballGame.swift => BaseballGame.swift} (99%) rename Week2-BaseballGame/Week2-BaseballGame/{main.swift => Main.swift} (100%) create mode 100644 Week2-BaseballGame/Week2-BaseballGame/Model.swift diff --git a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift similarity index 99% rename from Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift rename to Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift index 5290a07..7813be8 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/baseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift @@ -1,5 +1,5 @@ // -// baseballGame.swift +// BaseballGame.swift // Week2-BaseballGame // // Created by CHYUN on 11/5/24. diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/Main.swift similarity index 100% rename from Week2-BaseballGame/Week2-BaseballGame/main.swift rename to Week2-BaseballGame/Week2-BaseballGame/Main.swift diff --git a/Week2-BaseballGame/Week2-BaseballGame/Model.swift b/Week2-BaseballGame/Week2-BaseballGame/Model.swift new file mode 100644 index 0000000..d6e8c8a --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame/Model.swift @@ -0,0 +1,7 @@ +// +// Model.swift +// Week2-BaseballGame +// +// Created by CHYUN on 11/6/24. +// + From e4f4c173e1b734711c6f0cd458c6629146e540a6 Mon Sep 17 00:00:00 2001 From: chhue Date: Wed, 6 Nov 2024 17:31:43 +0900 Subject: [PATCH 10/12] =?UTF-8?q?[Feat]=20=EC=A2=85=EB=A3=8C=20=EC=A0=84?= =?UTF-8?q?=EA=B9=8C=EC=A7=80=20=EA=B2=8C=EC=9E=84=20=EA=B3=84=EC=86=8D=20?= =?UTF-8?q?=EC=A7=84=ED=96=89,=20=ED=8C=8C=EC=9D=BC=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 기록을 관리하는 다른 클래스를 만들어 게임이 계속 진행되는 동안 회차와 시도 횟수를 저장 - Model 분리 --- .../Week2-BaseballGame/BaseballGame.swift | 215 +++++++----------- ...54\210\230\352\265\254\355\230\204).swift" | 9 - ...54\210\230\352\265\254\355\230\204).swift" | 21 -- ...54\240\204\352\265\254\355\230\204).swift" | 15 -- ...54\240\204\352\265\254\355\230\204).swift" | 24 -- ...54\240\204\352\265\254\355\230\204).swift" | 20 -- ...54\240\204\352\265\254\355\230\204).swift" | 26 --- .../Week2-BaseballGame/Main.swift | 10 - .../Week2-BaseballGame/Model.swift | 72 ++++++ .../Week2-BaseballGame/RecordManager.swift | 33 +++ .../Week2-BaseballGame/main.swift | 6 + 11 files changed, 196 insertions(+), 255 deletions(-) delete mode 100644 "Week2-BaseballGame/Week2-BaseballGame/Lv_1(\355\225\204\354\210\230\352\265\254\355\230\204).swift" delete mode 100644 "Week2-BaseballGame/Week2-BaseballGame/Lv_2(\355\225\204\354\210\230\352\265\254\355\230\204).swift" delete mode 100644 "Week2-BaseballGame/Week2-BaseballGame/Lv_3(\353\217\204\354\240\204\352\265\254\355\230\204).swift" delete mode 100644 "Week2-BaseballGame/Week2-BaseballGame/Lv_4(\353\217\204\354\240\204\352\265\254\355\230\204).swift" delete mode 100644 "Week2-BaseballGame/Week2-BaseballGame/Lv_5(\353\217\204\354\240\204\352\265\254\355\230\204).swift" delete mode 100644 "Week2-BaseballGame/Week2-BaseballGame/Lv_6(\353\217\204\354\240\204\352\265\254\355\230\204).swift" delete mode 100644 Week2-BaseballGame/Week2-BaseballGame/Main.swift create mode 100644 Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift create mode 100644 Week2-BaseballGame/Week2-BaseballGame/main.swift diff --git a/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift index 7813be8..2f52153 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift @@ -1,66 +1,24 @@ // -// BaseballGame.swift +// baseballGame.swift // Week2-BaseballGame // // Created by CHYUN on 11/5/24. // + class BaseballGame { - private enum GameStatus: Int { - case on = 1, - off = 0 - } - - private enum GameMessage { - static let welcomeMessage = "Welcome! Please enter the number to execute. \n 1. Game Start 2. History 3. Exit" - static let gemeStartMessage = "*** Game Start ***" - static let requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter." - static let gameEndMessage = "***Game End***" - static let tryAgainMessage = "Try input again." - static let strikeMessage = "Strike" - static let ballMessage = "Ball" - static let outMessage = "Out!" - static let hitMessage = "Hit!" - - static func printGuidanceMessage(message: String) { - print(message) - } - } - - private enum InputError: Error { - case inputCountError, - invalidInputError, - zeroInputError, - duplicateValueError, - unknownError - - static func printErrorMessage(error: InputError) { - - var message = "" - - switch error { - case inputCountError: - message = "The number of inputs is insufficient." - case invalidInputError: - message = "Invalid input." - case zeroInputError: - message = "The first position cannot contain a zero." - case duplicateValueError: - message = "There are duplicate values." - case unknownError: - message = "There are unknown errors." - } - - print(message) - } + // 기록 매니저 + private var recordManager: RecordManager + init(recordManager: RecordManager) { + self.recordManager = recordManager } - - - private var answer: [Int] = [] + // 정답 개수 private let numberOfAnswer = 3 + // 정답 범위 private let rangeOfAnswerWithZero = 0...9 private let rangeOfAnswerWithoutZero = 1...9 + // 게임 상태 private var gameStatus: GameStatus = .on { willSet(newStatus) { switch newStatus { @@ -70,114 +28,72 @@ class BaseballGame { } } + // 게임 시작 func startGame() { + gameStatus = .on - commandLoop : while true { let command = readLine()!.replacingOccurrences(of: " ", with: "") - + switch command { case "1": playGame() break commandLoop case "2": - lookHistory() - break commandLoop + recordManager.showRecord() + GameMessage.printGuidanceMessage(message: GameMessage.inputAgainMessage) + case "3": gameStatus = .off break commandLoop default : InputError.printErrorMessage(error: .invalidInputError) - GameMessage.printGuidanceMessage(message: GameMessage.tryAgainMessage) + GameMessage.printGuidanceMessage(message: GameMessage.inputAgainMessage) } } } - private func lookHistory() { - - } - - private func getPlayerInput() -> String { - GameMessage.printGuidanceMessage(message: GameMessage.requireInputMessage) - var tempInput = readLine()! - tempInput.replace(" " , with: "") - return tempInput - } - - func playGame() { - - var questionBoxes = "" - var range = rangeOfAnswerWithoutZero - - while answer.count < numberOfAnswer { - - let randomNumber = Int.random(in: range) - if !answer.contains(randomNumber) { - answer.append(randomNumber) - range = rangeOfAnswerWithZero // 랜덤 범위 - 0을 포함한 범위로 변경 - questionBoxes = questionBoxes + "[ ? ] " - } -// if answer[0] == 0 { -// answer.remove(at: 0) -// } - } - - GameMessage.printGuidanceMessage(message: GameMessage.gemeStartMessage) - print(questionBoxes) - - print(answer) //test + func playGame() { + // 랜덤 값 받아오기 + let answer = newGame() + var score = Score() + var tryCount = 0 - /** 값 비교 전 체크 필요 - * [ 해결 가능 - 제일 먼저 체크 ] - * 1. 공백 문자 삽입 여부 - * -------------> 공백 제외 후 비교 - * - * [ 입력 개수 파악 ] - * 2. 입력 값 개수가 numberOfAnswer보다 부족 (입력 값 없을 경우 포함) - * - * [ 올바르지 않은입력 값 파악 ] - * 3. Int 값 외 - * 4. 0 입력 - * 5. 중복 숫자 입력 - * -------------> 다시 입력 받기 - **/ - - var strikeCount = 0 - var ballCount = 0 - var outCount = 0 - while gameStatus == .on { - + let playerInput = getPlayerInput() do { - // 이상 없이 정상 진행될 경우 - let playerInputAsArray = try checkError(playerInput: playerInput) + // 예외 상황 처리, 예외 없을 경우 배열로 값 받아오기 + let playerInputAsArray = try checkError(input: playerInput) - for index in playerInputAsArray.startIndex...playerInputAsArray.count - 1 { - answer[index] == playerInputAsArray[index]! ? strikeCount += 1 : nil - answer.contains(playerInputAsArray[index]!) && answer[index] != playerInputAsArray[index]! ? ballCount += 1 : nil - !answer.contains(playerInputAsArray[index]!) ? outCount += 1 : nil + for index in playerInputAsArray[0]...playerInputAsArray.count - 1 { + let number = playerInputAsArray[index] + let matchedAnswer = answer[index] + + // 1. + matchedAnswer == number ? score.strikeCount += 1 : nil + answer.contains(playerInputAsArray[index]) && answer[index] != playerInputAsArray[index] ? score.ballCount += 1 : nil + !answer.contains(playerInputAsArray[index]) ? score.outCount += 1 : nil } -// print("strikeCount : \(strikeCount), ballCount : \(ballCount), outCount : \(outCount)") // test - - if strikeCount == playerInput.count { + if score.strikeCount == numberOfAnswer { GameMessage.printGuidanceMessage(message: GameMessage.hitMessage) - gameStatus = .off - } else if outCount == playerInput.count { + recordManager.recordSet(tryCount: tryCount + 1) + startGame() + + } else if score.outCount == numberOfAnswer { GameMessage.printGuidanceMessage(message: GameMessage.outMessage) } else { - print("\(strikeCount) \(GameMessage.strikeMessage) \(ballCount) \(GameMessage.ballMessage)") + print("\(score.strikeCount) \(GameMessage.strikeMessage) \(score.ballCount) \(GameMessage.ballMessage)") } - strikeCount = 0 - ballCount = 0 - outCount = 0 - + score = Score() + tryCount += 1 + } catch InputError.inputCountError { InputError.printErrorMessage(error: .inputCountError) @@ -194,35 +110,74 @@ class BaseballGame { } catch { InputError.printErrorMessage(error: .unknownError) } + } + + } + + + // 랜덤 값 추출 + private func newGame() -> [Int] { + var answer: [Int] = [] + var questionBoxes = "" + var range = rangeOfAnswerWithoutZero + + while answer.count < numberOfAnswer { + let randomNumber = Int.random(in: range) + if !answer.contains(randomNumber) { + answer.append(randomNumber) + range = rangeOfAnswerWithZero // 랜덤 범위 - 0을 포함한 범위로 변경 + questionBoxes.append("[ ? ] ") + } } + GameMessage.printGuidanceMessage(message: GameMessage.gemeStartMessage) + print(questionBoxes) + + print(answer) //test + return answer } - - private func checkError(playerInput: String) throws -> [Int?] { + // 입력 값 받아와서 필요한 처리 후 리턴 + private func getPlayerInput() -> String { + GameMessage.printGuidanceMessage(message: GameMessage.requireInputMessage) + var tempInput = readLine()! + tempInput.replace(" " , with: "") + return tempInput + } + + + // 예외 상황 체크 + private func checkError(input: String) throws -> [Int] { - let inputAsStringArray = playerInput.split(separator: "") + // 한 자씩 파악하기 위해 배열로 쪼개기 + let inputAsStringArray = input.split(separator: "") + // 1. 입력 값 개수가 요구치와 다른지 체크 guard inputAsStringArray.count == numberOfAnswer else { throw InputError.inputCountError } - let inputAsIntArray = inputAsStringArray.map({ Int($0) }) + // String 배열 -> Int 배열 + var 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 } - return inputAsIntArray + // 모든 예외 상황이 아닐 경우 값비 교를 위한 배열 리턴, 위에서 nil 체크 완료 + return inputAsIntArray.map({ $0! }) } diff --git "a/Week2-BaseballGame/Week2-BaseballGame/Lv_1(\355\225\204\354\210\230\352\265\254\355\230\204).swift" "b/Week2-BaseballGame/Week2-BaseballGame/Lv_1(\355\225\204\354\210\230\352\265\254\355\230\204).swift" deleted file mode 100644 index afd8aba..0000000 --- "a/Week2-BaseballGame/Week2-BaseballGame/Lv_1(\355\225\204\354\210\230\352\265\254\355\230\204).swift" +++ /dev/null @@ -1,9 +0,0 @@ -// Lv 1 (11/04 까지) -// 1에서 9까지의 서로 다른 임의의 수 3개를 정하고 맞추는 게임입니다 -// 정답은 랜덤으로 만듭니다.(1에서 9까지의 서로 다른 임의의 수 3자리) - -import Foundation - -func levelOne() { - -} diff --git "a/Week2-BaseballGame/Week2-BaseballGame/Lv_2(\355\225\204\354\210\230\352\265\254\355\230\204).swift" "b/Week2-BaseballGame/Week2-BaseballGame/Lv_2(\355\225\204\354\210\230\352\265\254\355\230\204).swift" deleted file mode 100644 index 6930839..0000000 --- "a/Week2-BaseballGame/Week2-BaseballGame/Lv_2(\355\225\204\354\210\230\352\265\254\355\230\204).swift" +++ /dev/null @@ -1,21 +0,0 @@ -// Lv 2 (11/06 까지) - -/* -- 정답을 맞추기 위해 3자리수를 입력하고 힌트를 받습니다 - - 힌트는 야구용어인 **볼**과 **스트라이크**입니다. - - 같은 자리에 같은 숫자가 있는 경우 **스트라이크**, 다른 자리에 숫자가 있는 경우 **볼**입니다 - - ex) 정답 : 456 인 경우 - - 435를 입력한 경우 → 1스트라이크 1볼 - - 357를 입력한 경우 → 1스트라이크 - - 678를 입력한 경우 → 1볼 - - 123를 입력한 경우 → Nothing - - 만약 올바르지 않은 입력값에 대해서는 오류 문구를 보여주세요 -- 3자리 숫자가 정답과 같은 경우 게임이 종료됩니다 -- 실행 예시(정답 : 456)13123213 -*/ - -import Foundation - -func levelTwo() { - -} diff --git "a/Week2-BaseballGame/Week2-BaseballGame/Lv_3(\353\217\204\354\240\204\352\265\254\355\230\204).swift" "b/Week2-BaseballGame/Week2-BaseballGame/Lv_3(\353\217\204\354\240\204\352\265\254\355\230\204).swift" deleted file mode 100644 index d5df17e..0000000 --- "a/Week2-BaseballGame/Week2-BaseballGame/Lv_3(\353\217\204\354\240\204\352\265\254\355\230\204).swift" +++ /dev/null @@ -1,15 +0,0 @@ -// Lv 3 (11/06 까지) - -/* - - 정답이 되는 숫자를 0에서 9까지의 서로 다른 3자리의 숫자로 바꿔주세요 - - 맨 앞자리에 0이 오는 것은 불가능합니다 - - 092 → 불가능 - - 870 → 가능 - - 300 → 불가능 - */ - -import Foundation - -func levelThree() { - -} diff --git "a/Week2-BaseballGame/Week2-BaseballGame/Lv_4(\353\217\204\354\240\204\352\265\254\355\230\204).swift" "b/Week2-BaseballGame/Week2-BaseballGame/Lv_4(\353\217\204\354\240\204\352\265\254\355\230\204).swift" deleted file mode 100644 index f529e37..0000000 --- "a/Week2-BaseballGame/Week2-BaseballGame/Lv_4(\353\217\204\354\240\204\352\265\254\355\230\204).swift" +++ /dev/null @@ -1,24 +0,0 @@ -// Lv 4 (11/07 까지) - -/* - 프로그램을 시작할 때 안내문구를 보여주세요 - // 예시 - 환영합니다! 원하시는 번호를 입력해주세요 - 1. 게임 시작하기 2. 게임 기록 보기 3. 종료하기 - ​ - 1번 게임 시작하기의 경우 “필수 구현 기능” 의 예시처럼 게임이 진행됩니다 - 정답을 맞혀 게임이 종료된 경우 위 안내문구를 다시 보여주세요 - // 예시 - 환영합니다! 원하시는 번호를 입력해주세요 - 1. 게임 시작하기 2. 게임 기록 보기 3. 종료하기 - 1 // 1번 게임 시작하기 입력 - - < 게임을 시작합니다 > - 숫자를 입력하세요 - */ - -import Foundation - -func levelFour() { - -} diff --git "a/Week2-BaseballGame/Week2-BaseballGame/Lv_5(\353\217\204\354\240\204\352\265\254\355\230\204).swift" "b/Week2-BaseballGame/Week2-BaseballGame/Lv_5(\353\217\204\354\240\204\352\265\254\355\230\204).swift" deleted file mode 100644 index f9e0d17..0000000 --- "a/Week2-BaseballGame/Week2-BaseballGame/Lv_5(\353\217\204\354\240\204\352\265\254\355\230\204).swift" +++ /dev/null @@ -1,20 +0,0 @@ -// Lv 5 (11/07 까지) - -/* - 2번 게임 기록 보기의 경우 완료한 게임들에 대해 시도 횟수를 보여줍니다 - // 예시 - 환영합니다! 원하시는 번호를 입력해주세요 - 1. 게임 시작하기 2. 게임 기록 보기 3. 종료하기 - 2 // 2번 게임 기록 보기 입력 - - < 게임 기록 보기 > - 1번째 게임 : 시도 횟수 - 14 - 2번째 게임 : 시도 횟수 - 9 - 3번째 게임 : 시도 횟수 - 12 -*/ - -import Foundation - -func levelFive() { - -} diff --git "a/Week2-BaseballGame/Week2-BaseballGame/Lv_6(\353\217\204\354\240\204\352\265\254\355\230\204).swift" "b/Week2-BaseballGame/Week2-BaseballGame/Lv_6(\353\217\204\354\240\204\352\265\254\355\230\204).swift" deleted file mode 100644 index 848f2d1..0000000 --- "a/Week2-BaseballGame/Week2-BaseballGame/Lv_6(\353\217\204\354\240\204\352\265\254\355\230\204).swift" +++ /dev/null @@ -1,26 +0,0 @@ -// Lv 6 (11/07 까지) - -/* - 3번 종료하기의 경우 프로그램이 종료됩니다 - 이전의 게임 기록들도 초기화됩니다 - // 예시 - 환영합니다! 원하시는 번호를 입력해주세요 - 1. 게임 시작하기 2. 게임 기록 보기 3. 종료하기 - 3 // 3번 종료하기 입력 - - < 숫자 야구 게임을 종료합니다 > - ​ - 1, 2, 3 이외의 입력값에 대해서는 오류 메시지를 보여주세요 - // 예시 - 환영합니다! 원하시는 번호를 입력해주세요 - 1. 게임 시작하기 2. 게임 기록 보기 3. 종료하기 - 4 - - 올바른 숫자를 입력해주세요! -*/ - -import Foundation - -func levelSix() { - -} diff --git a/Week2-BaseballGame/Week2-BaseballGame/Main.swift b/Week2-BaseballGame/Week2-BaseballGame/Main.swift deleted file mode 100644 index e52d8f2..0000000 --- a/Week2-BaseballGame/Week2-BaseballGame/Main.swift +++ /dev/null @@ -1,10 +0,0 @@ -import Foundation - -// 게임 시작 -//let test = [5,7,6,0,0] -//print(BaseballGame().isThereDuplicateValue(array: test)) -let baseballGame = BaseballGame() -baseballGame.startGame() -//baseballGame.playGame() - - diff --git a/Week2-BaseballGame/Week2-BaseballGame/Model.swift b/Week2-BaseballGame/Week2-BaseballGame/Model.swift index d6e8c8a..326b709 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/Model.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/Model.swift @@ -5,3 +5,75 @@ // Created by CHYUN on 11/6/24. // +enum GameStatus: Int { + case on = 1, + off = 0 +} + + +enum GameMessage { + static let welcomeMessage = "Welcome! Please enter the number to execute. \n 1. Game Start 2. Record 3. Exit" + static let gemeStartMessage = "*** Game Start ***" + static let requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter." + static let gameEndMessage = "***Game End***" + static let noRecordMessage = "No Record" + static let inputAgainMessage = "Input the number to execute again." + static let strikeMessage = "Strike" + static let ballMessage = "Ball" + static let outMessage = "Out!" + static let hitMessage = "Hit!" + + static func printGuidanceMessage(message: String) { + print(message) + } +} + +/** 값 비교 전 체크 필요 + * [ 해결 가능 - 제일 먼저 체크 ] + * 1. 공백 문자 삽입 여부 + * -------------> 공백 제외 후 비교 + * + * [ 입력 개수 파악 ] + * 2. 입력 값 개수가 numberOfAnswer보다 부족 (입력 값 없을 경우 포함) + * + * [ 올바르지 않은입력 값 파악 ] + * 3. Int 값 외 + * 4. 0 입력 + * 5. 중복 숫자 입력 + * -------------> 다시 입력 받기 + **/ + +enum InputError: Error { + case inputCountError, + invalidInputError, + zeroInputError, + duplicateValueError, + unknownError + + static func printErrorMessage(error: InputError) { + + var message = "" + + switch error { + case inputCountError: + message = "The number of inputs is insufficient." + case invalidInputError: + message = "Invalid input." + case zeroInputError: + message = "The first position cannot contain a zero." + case duplicateValueError: + message = "There are duplicate values." + case unknownError: + message = "There are unknown errors." + } + + print(message) + } +} + + +struct Score { + var strikeCount = 0 + var ballCount = 0 + var outCount = 0 +} diff --git a/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift b/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift new file mode 100644 index 0000000..d6ca6de --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift @@ -0,0 +1,33 @@ +// +// RecordManager.swift +// Week2-BaseballGame +// +// Created by CHYUN on 11/6/24. +// + +class RecordManager { + + private var record: [(Int, Int)] = [] + + func recordSet(tryCount: Int) { + record.append((record.count + 1, tryCount)) + } + + func showRecord() { + + var stringBuffer = "" + + if !record.isEmpty { + for index in 0...record.count - 1 { + let setCount = record[index].0 + let tryCount = record[index].1 + stringBuffer.append(contentsOf: "\(setCount) Round : Try - \(tryCount)\n") + } + + } else { + + stringBuffer = GameMessage.noRecordMessage + } + print(stringBuffer) + } +} diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/main.swift new file mode 100644 index 0000000..1f5cef5 --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame/main.swift @@ -0,0 +1,6 @@ +import Foundation + +let recordManager = RecordManager() +let baseballGame = BaseballGame(recordManager: recordManager) +baseballGame.startGame() + From 56f780f4a2d56d2e35cfd87500e9f43adeab325c Mon Sep 17 00:00:00 2001 From: chhue Date: Thu, 7 Nov 2024 15:09:32 +0900 Subject: [PATCH 11/12] =?UTF-8?q?[Refactor]=20=ED=8C=8C=EC=9D=BC=20?= =?UTF-8?q?=EB=B6=84=EB=A6=AC=20=EB=B0=8F=20=EA=B8=B0=EB=8A=A5=20=EB=B6=84?= =?UTF-8?q?=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 정답 개수, 범위 등의 enum 상수 값으로 분리 - 역할이 많은 메소드 -> 기능 별도 메소드로 분리 - 기록 매니저 튜플 값에 레이블 추가 - 출력 메소드 복잡, 각 enum에서 메시지 출력 메소드로 인해 기능 과다 -> 출력 매니저 구조체 선언 --- .../Week2-BaseballGame/BaseballGame.swift | 98 ++++++++++--------- .../Week2-BaseballGame/Model.swift | 47 +++------ .../Week2-BaseballGame/PrintManager.swift | 62 ++++++++++++ .../Week2-BaseballGame/RecordManager.swift | 30 +++--- .../Week2-BaseballGame/main.swift | 3 +- 5 files changed, 139 insertions(+), 101 deletions(-) create mode 100644 Week2-BaseballGame/Week2-BaseballGame/PrintManager.swift diff --git a/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift b/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift index 2f52153..2f5347f 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/BaseballGame.swift @@ -10,20 +10,19 @@ class BaseballGame { // 기록 매니저 private var recordManager: RecordManager - init(recordManager: RecordManager) { + private var printManager: PrintManager + init(recordManager: RecordManager, printManager: PrintManager) { self.recordManager = recordManager + self.printManager = printManager } - // 정답 개수 - private let numberOfAnswer = 3 - // 정답 범위 - private let rangeOfAnswerWithZero = 0...9 - private let rangeOfAnswerWithoutZero = 1...9 + + // 게임 상태 private var gameStatus: GameStatus = .on { willSet(newStatus) { switch newStatus { - case .on : GameMessage.printGuidanceMessage(message: GameMessage.welcomeMessage) - case .off : GameMessage.printGuidanceMessage(message: GameMessage.gameEndMessage) + case .on : printManager.printGuideance(guide: Guidance.welcome) + case .off : printManager.printGuideance(guide: Guidance.gameEnd) } } } @@ -41,97 +40,102 @@ class BaseballGame { break commandLoop case "2": recordManager.showRecord() - GameMessage.printGuidanceMessage(message: GameMessage.inputAgainMessage) + printManager.printGuideance(guide: Guidance.inputAgain) case "3": gameStatus = .off break commandLoop default : - InputError.printErrorMessage(error: .invalidInputError) - GameMessage.printGuidanceMessage(message: GameMessage.inputAgainMessage) + printManager.printError(error: InputError.invalidInputError) + printManager.printGuideance(guide: Guidance.inputAgain) } } } func playGame() { - - // 랜덤 값 받아오기 - let answer = newGame() + + let answer = newGame() // 랜덤 값 받아오기 var score = Score() var tryCount = 0 while gameStatus == .on { + // 플레이어에게 값 받기 let playerInput = getPlayerInput() do { - // 예외 상황 처리, 예외 없을 경우 배열로 값 받아오기 + // 예외 없을 경우 let playerInputAsArray = try checkError(input: playerInput) - for index in playerInputAsArray[0]...playerInputAsArray.count - 1 { - let number = playerInputAsArray[index] - let matchedAnswer = answer[index] - - // 1. - matchedAnswer == number ? score.strikeCount += 1 : nil - answer.contains(playerInputAsArray[index]) && answer[index] != playerInputAsArray[index] ? score.ballCount += 1 : nil - !answer.contains(playerInputAsArray[index]) ? score.outCount += 1 : nil - } + score = calculateScore(playerInput: playerInputAsArray, answer: answer) - if score.strikeCount == numberOfAnswer { - GameMessage.printGuidanceMessage(message: GameMessage.hitMessage) - recordManager.recordSet(tryCount: tryCount + 1) + if score.strikeCount == GameConfig.numberOfAnswer { + printManager.printGuideance(guide: Guidance.hit) + recordManager.recordSet(tries: tryCount + 1) startGame() - - } else if score.outCount == numberOfAnswer { - GameMessage.printGuidanceMessage(message: GameMessage.outMessage) + } else if score.outCount == GameConfig.numberOfAnswer { + printManager.printGuideance(guide: Guidance.out) } else { - print("\(score.strikeCount) \(GameMessage.strikeMessage) \(score.ballCount) \(GameMessage.ballMessage)") + print("\(score.strikeCount) \(Guidance.strike) \(score.ballCount) \(Guidance.ball)") } score = Score() tryCount += 1 - + // 예외 경우 } catch InputError.inputCountError { - InputError.printErrorMessage(error: .inputCountError) + printManager.printError(error: InputError.inputCountError) } catch InputError.invalidInputError { - InputError.printErrorMessage(error: .invalidInputError) + printManager.printError(error: InputError.invalidInputError) } catch InputError.zeroInputError { - InputError.printErrorMessage(error: .zeroInputError) + printManager.printError(error: InputError.zeroInputError) } catch InputError.duplicateValueError { - InputError.printErrorMessage(error: .duplicateValueError) - + printManager.printError(error: InputError.duplicateValueError) } catch { - InputError.printErrorMessage(error: .unknownError) + 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] { var answer: [Int] = [] var questionBoxes = "" - var range = rangeOfAnswerWithoutZero + var range = GameConfig.rangeOfAnswerWithoutZero - while answer.count < numberOfAnswer { + while answer.count < GameConfig.numberOfAnswer { let randomNumber = Int.random(in: range) if !answer.contains(randomNumber) { answer.append(randomNumber) - range = rangeOfAnswerWithZero // 랜덤 범위 - 0을 포함한 범위로 변경 + range = GameConfig.rangeOfAnswerWithZero // 랜덤 범위 - 0을 포함한 범위로 변경 questionBoxes.append("[ ? ] ") } } - GameMessage.printGuidanceMessage(message: GameMessage.gemeStartMessage) + printManager.printGuideance(guide: Guidance.gameStart) print(questionBoxes) print(answer) //test @@ -140,10 +144,8 @@ class BaseballGame { // 입력 값 받아와서 필요한 처리 후 리턴 private func getPlayerInput() -> String { - GameMessage.printGuidanceMessage(message: GameMessage.requireInputMessage) - var tempInput = readLine()! - tempInput.replace(" " , with: "") - return tempInput + printManager.printGuideance(guide: Guidance.requireInput) + return readLine()?.trimmingCharacters(in: .whitespaces) ?? "" } @@ -154,12 +156,12 @@ class BaseballGame { let inputAsStringArray = input.split(separator: "") // 1. 입력 값 개수가 요구치와 다른지 체크 - guard inputAsStringArray.count == numberOfAnswer else { + guard inputAsStringArray.count == GameConfig.numberOfAnswer else { throw InputError.inputCountError } // String 배열 -> Int 배열 - var inputAsIntArray = inputAsStringArray.map({ Int($0) }) + let inputAsIntArray = inputAsStringArray.map({ Int($0) }) // 2. String값 Int로 바꿀경우 nil, 숫자 아닌 값 입력되었는지 체크 guard !inputAsIntArray.contains(nil) else { diff --git a/Week2-BaseballGame/Week2-BaseballGame/Model.swift b/Week2-BaseballGame/Week2-BaseballGame/Model.swift index 326b709..9d03bfc 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/Model.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/Model.swift @@ -10,22 +10,19 @@ enum GameStatus: Int { off = 0 } +enum GameConfig { + static let numberOfAnswer = 3 + static let rangeOfAnswerWithZero = 0...9 + static let rangeOfAnswerWithoutZero = 1...9 +} + -enum GameMessage { - static let welcomeMessage = "Welcome! Please enter the number to execute. \n 1. Game Start 2. Record 3. Exit" - static let gemeStartMessage = "*** Game Start ***" - static let requireInputMessage = "Please enter the numbers for each question mark in order, then press Enter." - static let gameEndMessage = "***Game End***" - static let noRecordMessage = "No Record" - static let inputAgainMessage = "Input the number to execute again." - static let strikeMessage = "Strike" - static let ballMessage = "Ball" - static let outMessage = "Out!" - static let hitMessage = "Hit!" - - static func printGuidanceMessage(message: String) { - print(message) - } +enum Guidance { + case welcome, + gameStart, gameEnd, + requireInput, inputAgain, + noRecord, + strike, ball, out, hit } /** 값 비교 전 체크 필요 @@ -49,26 +46,6 @@ enum InputError: Error { zeroInputError, duplicateValueError, unknownError - - static func printErrorMessage(error: InputError) { - - var message = "" - - switch error { - case inputCountError: - message = "The number of inputs is insufficient." - case invalidInputError: - message = "Invalid input." - case zeroInputError: - message = "The first position cannot contain a zero." - case duplicateValueError: - message = "There are duplicate values." - case unknownError: - message = "There are unknown errors." - } - - print(message) - } } diff --git a/Week2-BaseballGame/Week2-BaseballGame/PrintManager.swift b/Week2-BaseballGame/Week2-BaseballGame/PrintManager.swift new file mode 100644 index 0000000..f6fa799 --- /dev/null +++ b/Week2-BaseballGame/Week2-BaseballGame/PrintManager.swift @@ -0,0 +1,62 @@ +// +// PrintManager.swift +// Week2-BaseballGame +// +// Created by CHYUN on 11/7/24. +// + +protocol PrintMessage { + func printError(error: InputError) + func printGuideance(guide: Guidance) +} + +struct PrintManager: PrintMessage { + + func printError(error: InputError) { + + let message = switch error { + case InputError.inputCountError: + "The number of inputs is insufficient." + case InputError.invalidInputError: + "Invalid input." + case InputError.zeroInputError: + "The first position cannot contain a zero." + case InputError.duplicateValueError: + "There are duplicate values." + case InputError.unknownError: + "There are unknown errors." + } + + print(message) + } + + func printGuideance(guide: Guidance) { + + let message = switch guide { + case Guidance.welcome : + "Welcome! Please enter the number to execute. \n 1. Game Start 2. Record 3. Exit" + case Guidance.gameStart : + "*** Game Start ***" + case Guidance.gameEnd : + "***Game End***" + case Guidance.requireInput : + "Please enter the numbers for each question mark in order, then press Enter." + case Guidance.inputAgain : + "Input the number to execute again." + case Guidance.noRecord : + "No Record" + case Guidance.strike : + "Stike" + case Guidance.ball : + "Ball" + case Guidance.hit : + "Congratulation! HIT!!" + case Guidance.out : + "OUT!" + } + print(message) + } + +} + + diff --git a/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift b/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift index d6ca6de..1a0c37e 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/RecordManager.swift @@ -5,29 +5,25 @@ // Created by CHYUN on 11/6/24. // -class RecordManager { +struct RecordManager { - private var record: [(Int, Int)] = [] + private var record: [(round: Int, tries: Int)] = [] - func recordSet(tryCount: Int) { - record.append((record.count + 1, tryCount)) + mutating func recordSet(tries: Int) { + record.append((record.count + 1, tries)) } func showRecord() { - var stringBuffer = "" - - if !record.isEmpty { - for index in 0...record.count - 1 { - let setCount = record[index].0 - let tryCount = record[index].1 - stringBuffer.append(contentsOf: "\(setCount) Round : Try - \(tryCount)\n") - } - - } else { - - stringBuffer = GameMessage.noRecordMessage + guard !record.isEmpty else { + print(Guidance.noRecord) + return } - print(stringBuffer) + + let recordString = record.map { round, tries in + "\(round) Round : Try - \(tries)" + }.joined(separator: "\n") + + print(recordString) } } diff --git a/Week2-BaseballGame/Week2-BaseballGame/main.swift b/Week2-BaseballGame/Week2-BaseballGame/main.swift index 1f5cef5..e236d88 100644 --- a/Week2-BaseballGame/Week2-BaseballGame/main.swift +++ b/Week2-BaseballGame/Week2-BaseballGame/main.swift @@ -1,6 +1,7 @@ import Foundation let recordManager = RecordManager() -let baseballGame = BaseballGame(recordManager: recordManager) +let printManager = PrintManager() +let baseballGame = BaseballGame(recordManager: recordManager, printManager: printManager) baseballGame.startGame() From 133d4ec0a8e4c6bfe42640f9910a66d4e1edcdd5 Mon Sep 17 00:00:00 2001 From: "Chae-Hyun, Park" Date: Thu, 7 Nov 2024 20:44:40 +0900 Subject: [PATCH 12/12] =?UTF-8?q?[Docs]=20README=20=EC=9E=91=EC=84=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 93 ++++++++++++++----------------------------------------- 1 file changed, 23 insertions(+), 70 deletions(-) diff --git a/README.md b/README.md index 025aece..5a2a69e 100644 --- a/README.md +++ b/README.md @@ -1,77 +1,30 @@ -# 숫자 야구 게임 과제 (Week 2) -숫자 야구 게임은 1에서 9까지의 서로 다른 3개의 숫자를 맞추는 게임입니다.
-각 레벨마다 기능이 확장되며, 팀원들이 협업하여 매주 주어진 과제를 해결해 나갑니다. +# ⚾️ 숫자 야구 게임 -# 📝 협업 규칙 +--- +### 🏟️ 개요 +숫자 야구 게임은 랜덤으로 생성된 서로 다른 숫자를 맞추는 게임입니다.
+각 레벨마다 확장된 기능 업데이트가 요구되었습니다. -### 풀 리퀘스트 작성 규칙 -**1** 형식: `[레벨] 작업 내용 - 팀원 이름` - - 예시: `[Lv_1] 야구 로직 구현 - 김상민`
-**2** 작업 세부 사항: 해당 레벨에서 구현한 주요 기능을 요약하여 추가 설명으로 작성합니다. +|개발 기간|인원|개발 언어|개발 환경| +|------|--|------|------| +|24.11.05 - 07|1인|Swift|OS: macOS 15.0.1, IDE: Xcode 16.1| -### 레포지토리 설정 및 브랜치 관리 -**1** **Fork로 가져오기**: 각 팀원은 레포지토리를 Fork하여 자신의 개인 레포지토리로 가져옵니다.
-**2** **브랜치 생성**: Fork한 개인 레포지토리에서 각자의 이름을 딴 브랜치를 생성합니다.
-**3** **Pull Request**: 과제를 마친 후, 각자의 브랜치로 Pull Request를 생성하여 코드 리뷰를 요청합니다. 모든 팀원이 Pull Request에 코멘트를 달고 피드백을 제공합니다.
-**4** **수정 및 Merge**: 피드백을 반영하여 수정하고, 팀원들의 동의를 얻은 후 merge를 진행합니다.
+--- -이 과정을 통해 서로의 코드에 대해 이해를 높이고, “왜 이렇게 작성했는지”에 대한 질문과 답변을 주고받으며 과제를 진행합니다. -# 📂 코드 파일 구조 -* main.swift: 게임의 메인 진입점으로, 레벨을 선택하고 시작할 수 있도록 구성되어 있습니다. startGame() 함수가 게임의 시작을 담당합니다. -* Lv_1.swift ~ Lv_6.swift: 각 레벨별 요구사항에 맞게 구현된 파일입니다. 각 파일에는 해당 레벨의 기능을 구현하는 함수가 포함되어 있습니다. +### 📂 코드 파일 구조 +* main.swift: 인스턴스들이 생성되고 호출되는 곳입니다. +* BaseballGame : 게임이 진행되는 곳입니다. +* Model : 게임 진행을 위해 필요한 데이터 클래스 혹은 구조체 등이 모여 있는 곳입니다. +* PrintManager : 게임 메시지 출력을 도와주는 구조체입니다. +* RecordManager : 게임 기록을 도와주는 구조체입니다. -⠀📜 구현 가이드 +--- -### main.swift -Command Line Tool 프로젝트에서는 하나의 `main.swift` 파일에서만 프로그램을 시작할 수 있습니다. 따라서 각 레벨별 기능을 별도의 파일로 구현한 후, `main.swift` 파일에서 해당 레벨의 함수를 호출하여 실행하도록 구성합니다. +### 💬 PR +* [게임 시작 구현](https://github.com/SpartaCoding-iOS5/Week2-BaseballGame/pull/7) +* [게임 구현 마무리](https://github.com/SpartaCoding-iOS5/Week2-BaseballGame/pull/21) + +--- -```swift -import Foundation - -func startGame() { - print("레벨을 선택하세요 (1, 2, 3, 4, 5, 6):") - - if let input = readLine(), let level = Int(input) { - switch level { - case 1: - levelOne() - case 2: - levelTwo() - case 3: - levelThree() - case 4: - levelFour() - case 5: - levelFive() - case 6: - levelSix() - default: - print("유효하지 않은 레벨입니다. 1~6까지를 선택해주세요.") - } - } else { - print("잘못된 입력입니다.") - } -} - -// 게임 시작 -startGame() -``` -* startGame() 함수에서 게임의 레벨을 선택하여 시작할 수 있도록 구성합니다. -* 사용자가 입력한 레벨 번호에 따라 해당 레벨의 함수를 호출하여 게임을 진행합니다. - - -### 각 레벨 파일 (Lv_1.swift ~ Lv_6.swift) - 구현 파일 - -**Lv_1.swift** - -```swift -import Foundation - -func levelOne() { - // 1. 정답을 생성하는 로직을 추가합니다. - // 2. 유저가 정답을 맞출 때까지 반복해서 입력을 받습니다. - // 3. 입력값이 유효한지 검사하고 힌트를 제공하는 기능을 구현합니다. -} -``` - -각 레벨별로 구현하시면 됩니다. +### 🐞 트러블 슈팅 +* [문자열 enum 내 상수값으로 저장하기](https://chhue96.tistory.com/124)