스파르타코딩 클럽/사전 캠프

10. 스파르타 코딩클럽 [사전캠프 - 가위바위보 게임 만들기]

UDDT 2025. 2. 7. 17:39


실습

가위바위보 게임 만들기

가위바위보 게임 조건
1. 사용자가 "가위", "바위", "보" 중 하나를 입력하면 컴퓨터가 무작위 선택을 한다.
2. 조건문을 사용하여 승패를 판별하고 결과를 출력한다.
3. 사용자가 "그만"을 입력할 때까지 반복적으로 게임을 진행한다.
4. 사용자의 입력이 올바르지 않으면 다시 입력하도록 처리한다.

 

  1. 컴퓨터가 무작위로 선택하는 함수 만들기

func computerChoice() -> String {
    let option = ["가위", "바위", "보"]
    return option.randomElement()!
}

 

  2. 승패를 판별하는 함수 만들기

func computerChoice() -> String {
    let option = ["가위", "바위", "보"]
    return option.randomElement()!
}

func findWinner(userInput: String, computerChoice: String) -> String {
    if userInput == computerChoice {
        return "비겼습니다"
    } else if userInput == "가위" && computerChoice == "보" {
        return "이겼습니다"
    } else if userInput == "가위" && computerChoice == "바위" {
        return "졌습니다."
    } else if userInput == "바위" && computerChoice == "보" {
        return "졌습니다."
    } else if userInput == "바위" && computerChoice == "가위" {
        return "이겼습니다."
    } else if userInput == "보" && computerChoice == "바위" {
        return "이겼습니다."
    } else if userInput == "보" && computerChoice == "가위" {
        return "졌습니다."
    } else {
        return "잘못된 입력입니다. 다시 입력해주세요"
    }
}

 

  함수는 졌습니다 / 이겼습니다 두 그룹으로 나뉜다.

그룹을 묶어서 코드를 단순화 한다면,

func findWinner(userInput: String, computerChoice: String) -> String {
    if userInput == computerChoice {
        return "비겼습니다"
    } else if (userInput == "가위" && computerChoice == "보") ||
                (userInput == "바위" && computerChoice == "가위") ||
                (userInput == "보" && computerChoice == "바위") {
        return "이겼습니다"
    } else {
        return "졌습니다"
    }
}

다음과 같이 단순화할 수 있다.

 

  현재까지 작성된 코드를 playGround에서 테스트하려면 아래의 코드로 테스트할 수 있다.

let userInput = "바위"
let auto = computerChoice()
let result = findWinner(userInput: userInput, computerChoice: auto)
print(result)

/*
userInput을 정해주고,
상수에 computerChoice()의 값을 저장
parameter의 각각의 요소를 넣어주고 result에 저장한 다음,
result 값을 출력
*/

 

  3. 사용자 입력을 받아 게임을 반복하기

사용자가 "그만"을 입력할 때까지 반복해서 실행
var isPlaying = true

while isPlaying {
    print("가위, 바위, 보 중 하나를 입력하세요: (그만을 입력하면 종료됩니다.)")
    if let userInput = readLine()?.trimmingCharacters(in: .whitespaces),
    ["가위", "바위", "보", "그만"].contains(userInput) {

        if userInput == "그만" {
            isPlaying = false
            print("게임을 종료합니다")
            break
        }

        let computerChoice = computerChoice()
        let result = findWinner(userInput: userInput, computerChoice: computerChoice)

        print("사용자: \(userInput), 컴퓨터: \(computerChoice)")
        print(result)
    } else {
        print("잘못된 입력입니다. 다시 입력해주세요.")
    }

}

func computerChoice() -> String {
    let option = ["가위", "바위", "보"]
    return option.randomElement()!
}

func findWinner(userInput: String, computerChoice: String) -> String {
    if userInput == computerChoice {
        return "비겼습니다"
    } else if (userInput == "가위" && computerChoice == "보") ||
                (userInput == "바위" && computerChoice == "가위") ||
                (userInput == "보" && computerChoice == "바위") {
        return "이겼습니다"
    } else {
        return "졌습니다"
    }
}

 

너무 어려워서 코드는 뜯어봐야겠다..


 코드 뜯어보기

 

  1. 컴퓨터가 무작위로 선택하는 함수 만들기

func computerChoice() -> String {
    let option = ["가위", "바위", "보"]
    return option.randomElement()!
}

 

   1) 함수를 만든 뒤, option 상수를 선언하여 배열로 값을 담는다.

   2) .randomElement()를 통해 랜덤 값을 optional 값으로 리턴받는다.

 

  2. 승패를 판별하는 함수 만들기

func determineWinner(userChoice: String, computerChoice: String) -> String {
    if userChoice == computerChoice {
        return "무승부입니다!"
    } else if (userChoice == "가위" && computerChoice == "보") ||
                (userChoice == "바위" && computerChoice == "가위") ||
                (userChoice == "보" && computerChoice == "바위") {
        return "이겼습니다!"
    } else {
        return "졌습니다! 다시 도전하세요"
    }
}

   1) 승패를 판별하기 위해 userChoice과 computerChoice를 파라미터로 받는 함수를 만든다.

   2) 함수 안에서 if문으로 조건을 통해 각각의 조건을 판별한다.

   3) userChoice와 computerChoice를 비교할 때는 비교 연산자(||)가 우선하기 때문에 괄호를 통해 대상의 우선순위를 정해준다.

 

  3. 사용자 입력을 받아 게임을 반복하기

var isPlaying = true

while isPlaying {
    print("가위, 바위, 보 중 하나를 입력하세요. (그만 입력 시 종료): ", terminator: "")
    if let userChoice = readLine()?.trimmingCharacters(in: .whitespaces), ["가위", "바위", "보", "그만"].contains(userChoice) {

        if userChoice == "그만" {
            isPlaying = false
            print("게임을 종료합니다")
            break
        }

        let computerChoice = getComputerChoice()
        let result = determineWinner(userChoice: userChoice, computerChoice: computerChoice)

        print("사용자 선택: \(userChoice), 컴퓨터 선택: \(computerChoice)")
        print(result)
    } else {
        print("잘못된 입력입니다. 다시 입력하세요")
    }
}

   1) while문은 조건이 true일 때만 반복하므로, isPlaying이라는 변수를 Boolean Type으로 만들고 true로 설정한다.

   2) print(~, terminator: "")을 통해 사용자의 입력을 받는다.

   3) 옵셔널 체이닝(?.)과 .trimmingCharacters를 통해, 사용자의 입력이 있을 때 공백을 지우고, 없으면 nil을 리턴하도록 설정한다.

   4) userChoice가 '그만'이면, isPlaying을 false로 처리해 반복을 종료한다.

   5) getComputerChoice() 함수를 호출하여 나온 값을 computerChoice에 담는다.

   6) determineWinner() 함수를 호출하여 나온 값을 result에 담는다

 

+ randomElement()

func randomElement() -> Self.Element?

 

 randomElement()는 Optional 값을 return하므로, 값을 추출해줘야 함.

 위와 같은 예시처럼, 선택해야할 값이 명확히 정해져 있는 경우 강제추출 연산자(!)를 사용할 수 있음.

 

 + trimmingCharacters()

func trimmingCharacters(in set: CharacterSet) -> String

 trimmingCharacters()는 주어진 String에 포함된 문자(CharacterSet)의 양쪽 끝에서 문자를 제거하고, 그 결과를 새 문자열로 반환

이를 활용하면 양쪽에 있는 공백 뿐만 아니라 문자열도 제거할 수 있음.

let dirtyString = "***Hello, Starter!***"
let cleanString = dirtyString.trimmingCharacters(in: CharacterSet(charactersIn: "*"))
print(cleanString)  // "Hello, Starter!"

 + Optional Channing(?.)

 옵셔널 값이 nil이 아닐 때만 해당 속성이나 메서드에 접근하도록 하는 기능

 따라서 Optional Binding처럼, Optional 값을 안전하게 사용할 때 쓰는 방법

if let userChoice = readLine()?.trimmingCharacters(in: .whitespaces)

  만약 사용자 입력이 없으면, .trimmingCharacters를 실행하지 않고 그대로 nil을 Return.

  사용자 입력이 있으면, .trimmingCharacters를 실행하고 새롭게 적용된 값을 Return.