Skip to content
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

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Foundation

enum InputErrorLv7: Error {
case invalidLength
case notNumber
case duplicateNumbers

var errorMessage: String {
switch self {
case .invalidLength:
return Constants.invalidLengthMessage
case .notNumber:
return Constants.notNumberMessage
case .duplicateNumbers:
return Constants.duplicateNumbersMessage
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import Foundation

class BaseballGameLv7: BaseballGameProtocolLv7 {
var answer: [Int]
var strike: Int = 0
var ball: Int = 0
var gameRecords: [Int] = []
var gameAttempts: Int = 0

private var answerCreator: AnswerCreatorLv7

init(answerCreator: AnswerCreatorLv7) {
self.answerCreator = answerCreator
self.answer = AnswerCreatorLv7.create()
}

// 게임 시작을 안내하는 메서드
func startGame() {
while true {
print(Constants.welcomeMessage)
print(Constants.menuOptions)
print("ㄴ ", terminator: "")

guard let userInput = readLine(), let userIntInput = Int(userInput), (1...3).contains(userIntInput) else {
print("유효하지 않은 입력으로 1, 2, 3 중 하나를 선택하세요.")
continue
}

switch userIntInput {
case 1:
gameRecords.append(startBaseballGame())
case 2:
displayGameRecords()
case 3:
exitGame()
default:
continue
}
}
}

// 야구 게임의 핵심 로직
func startBaseballGame() -> Int {
resetGame()
print("야구 게임을 시작합니다!")

while true {
let userInput = getUserInput()

do {
let (strikeCount, ballCount) = try checkAnswer(userInput: userInput)
displayResult(strike: strikeCount, ball: ballCount)

if strikeCount == 3 {
print("정답입니다!\n")
return gameAttempts
}

} catch let error as InputErrorLv7 {
print(error.errorMessage)
} catch {
print("알 수 없는 오류가 발생했습니다.")
}
}
}

// 사용자 입력받기
private func getUserInput() -> String {
print("세 자리 숫자를 입력하세요: ", terminator: "")
guard let userInput = readLine() else { return "" }
return userInput
}

// 입력한 답을 확인하고 스트라이크와 볼을 계산
func checkAnswer(userInput: String) throws -> (strike: Int, ball: Int) {
guard let userNumber = Int(userInput), Constants.validNumberRange.contains(userNumber) else {
throw InputErrorLv7.invalidLength
}

let userAnswerArray = try parseUserAnswer(userInput)

guard Set(userAnswerArray).count == 3 else {
throw InputErrorLv7.duplicateNumbers
}

gameAttempts += 1
return evaluateBall(userAnswer: userAnswerArray, answer: answer)
}

private func parseUserAnswer(_ userInput: String) throws -> [Int] {
var userAnswerArray: [Int] = []
for char in userInput {
guard let userAnswerChar = Int(String(char)) else {
throw InputErrorLv7.notNumber
}
userAnswerArray.append(userAnswerChar)
}
return userAnswerArray
}

// 정답과 사용자의 입력 비교
func evaluateBall(userAnswer: [Int], answer: [Int]) -> (strike: Int, ball: Int) {
strike = 0
ball = 0
for index in userAnswer.indices {
if userAnswer[index] == answer[index] {
strike += 1
} else if answer.contains(userAnswer[index]) {
ball += 1
}
}
return (strike, ball)
}

private func displayResult(strike: Int, ball: Int) {
if strike == 0 && ball == 0 {
print("아웃!")
} else {
print("\(strike)스트라이크 \(ball)볼")
}
}

private func displayGameRecords() {
print("< 게임 기록 보기 >")
if gameRecords.isEmpty {
print("기록이 없습니다.")
} else {
for (index, attempts) in gameRecords.enumerated() {
print("\(index + 1)번째 게임: 시도 횟수 - \(attempts)")
}
}
print("")
}

private func resetGame() {
self.answer = AnswerCreatorLv7.create()
self.strike = 0
self.ball = 0
self.gameAttempts = 0
}

private func exitGame() {
print("숫자 야구 게임을 종료합니다.")
exit(0)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import Foundation

class GameHistory {
private var records: [Int] = []

func addRecord(_ attempts: Int) {
records.append(attempts)
}

func displayRecords() {
if records.isEmpty {
print("기록이 없습니다.")
} else {
for (index, attempts) in records.enumerated() {
print("\(index + 1)번째 게임: 시도 횟수 - \(attempts)")
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import Foundation

protocol BaseballGameProtocolLv7 {
var answer: [Int] { get set }
var strike: Int { get set }
var ball: Int { get set }
var gameRecords: [Int] { get set }
var gameAttempts: Int { get set }

func startGame()
func startBaseballGame() -> Int
func checkAnswer(userInput: String) throws -> (strike: Int, ball: Int)
func evaluateBall(userAnswer: [Int], answer: [Int]) -> (strike: Int, ball: Int)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Foundation

class AnswerCreatorLv7 {
static func create() -> [Int] {
var answerSet: Set<Int> = []
while answerSet.count < 3 {
let randomNum = Int.random(in: 0...9)
answerSet.insert(randomNum)
}
var answerArray = Array(answerSet)
if answerArray[0] == 0 {
answerArray.swapAt(0, Int.random(in: 1..<answerArray.count))
}
return answerArray
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Foundation

enum Constants {
static let validNumberRange = 100...999
static let invalidLengthMessage = "제한사항: 세 자리 숫자를 입력해주세요."
static let notNumberMessage = "제한사항: 아라비아 숫자만 입력해주세요."
static let duplicateNumbersMessage = "제한사항: 서로 다른 숫자를 입력해주세요."
static let welcomeMessage = "환영합니다! 원하시는 번호를 입력해주세요"
static let menuOptions = "1. 게임 시작하기 2. 게임 기록 보기 3. 종료하기"
}
8 changes: 6 additions & 2 deletions Week2-BaseballGame/Week2-BaseballGame/main.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation

func startGame() {
print("레벨을 선택하세요 (1, 2, 3, 4, 5, 6): ", terminator: "")
print("레벨을 선택하세요 (1, 2, 3, 4, 5, 7): ", terminator: "")
print("ㄴ")

if let input = readLine(), let level = Int(input) {
Expand All @@ -23,8 +23,12 @@ func startGame() {
case 6:
let game = BaseballGameLv6()
game.startGame()
case 7:
let answerCreator = AnswerCreatorLv7()
let game = BaseballGameLv7(answerCreator: answerCreator)
game.startGame()
default:
print("유효하지 않은 레벨입니다. 1~6까지를 선택해주세요.")
print("유효하지 않은 레벨입니다. 1~7까지를 선택해주세요.")
}
} else {
print("잘못된 입력입니다.")
Expand Down