24.06.12 Today I Learned

2024. 6. 13. 09:28·Today I Learned/2024

 Command Line Tool로 숫자 야구게임 만들기

 

Lv.1 시도

// main.swift

import Foundation

var game = BaseballGame()
game.start()
BaseballGame.swift

import Foundation

struct BaseballGame {
    func start() {
        let answer = makeAnswer()
        
        print("게임을 시작합니다")
        print("숫자를 입력해주세요")
        
        print(makeAnswer())
        
        let input = readLine()!
        
        let IntAnswer = String(input).map {Int(String($0))!}
        // 입력받은 String타입의 input을 [Int]로 변환
        
        print(IntAnswer)
    }
    
    func makeAnswer() -> [Int] {
        var ans = Array(1...9)
        var randomNumbers : [Int] = []
        
        while randomNumbers.count < 3 {
            let randomIndex = Int.random(in: 0..<ans.count)
            let randomNumber = ans[randomIndex]
            
            if !randomNumbers.contains(randomNumber) {
                randomNumbers.append(randomNumber)
            }
        }
        
        return randomNumbers
    }
}

 

// 출력값 :

// 게임을 시작합니다
// 숫자를 입력해주세요
// [3, 9, 5] < 랜덤숫자

 

BaseballGame.swift 파일을 따로 생성해서 프로젝트를 구성했다.

 

makeAnswer()는 while문을 사용하여 총 3자리의 랜덤한 정수가 들어가도록 만들었다. 내부에 if문으로 이미 입력된 값이 중복되지 않도록 만들었다.

 

map함수를 사용하여 String -> Int 타입으로 저장했다.

'Today I Learned > 2024' 카테고리의 다른 글

24.06.17 Today I Learned  (0) 2024.06.17
24.06.14 Today I Learned  (1) 2024.06.14
24.06.11 Today I Learned  (0) 2024.06.11
24.06.10 Today I Learned  (0) 2024.06.10
24.06.07 Today I Learned  (1) 2024.06.08
'Today I Learned/2024' 카테고리의 다른 글
  • 24.06.17 Today I Learned
  • 24.06.14 Today I Learned
  • 24.06.11 Today I Learned
  • 24.06.10 Today I Learned
이도서
이도서
  • 이도서
    도서의 코딩노트
    이도서
  • 전체
    오늘
    어제
    • 분류 전체보기 (209)
      • Today I Learned (79)
        • 2024 (78)
      • Swift (25)
        • Swift 문법 정리 (19)
        • RxSwift (5)
      • Swift Study (12)
        • Playground (2)
        • Storyboard (9)
        • UIKit (1)
      • Git (3)
      • 코딩테스트 (60)
      • Dart 언어 (16)
      • Flutter (11)
        • Flutter Study (11)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

    • 개발 공부 공유 링크
  • 인기 글

  • 태그

    객체지향
    계산기만들기
    storyboard
    Til
    코딩테스트Level.1
    widget
    구조체
    DART
    Xcode
    ios
    내일배움캠프
    ios앱개발자
    코딩테스트
    함수
    Swift
    코딩테스트 level.1
    Playground
    iOS앱개발
    코딩 테스트
    Flutter
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
이도서
24.06.12 Today I Learned
상단으로

티스토리툴바