공부

F#으로 숫자 맞추기 게임하기

복제고양이 2025. 11. 19. 08:34
300x250

 

 최근에 다시 F#으로 프로젝트를 진행하게 되면서 

F#에 다시 익숙해져야하는 시간이 왔다.

빠른 진행을 위해 챗지피티에게 제일 단순한 프로젝트를 추천받았다.

 

 

F# 콘솔 프로젝트 (dotnet 8.0) 을 만들고 아래와 같이 Program.fs를 작성했다.

// For more information see https://aka.ms/fsharp-console-apps
printfn "Hello from F#"

open System

let rnd = Random()

let rec gameLoop target attempts = 
    printf "숫자를 입력하세요 1~100, q를 눌러 종료:"
    let input = Console.ReadLine()
    match input with
        |"q" | "Q" -> printfn "게임을 종료 정답은 %d" target

        | _ -> 
            let (success, guess) = Int32.TryParse(input)
            match success with
            | true ->
                if guess < target then
                    printfn "업"
                    gameLoop target (attempts + 1)
                elif guess > target then
                    printfn "다운"
                    gameLoop target (attempts + 1)
                else 
                    printfn "정답, %d번만에 맞췄어요" (attempts + 1)
            | false -> 
               printfn "숫자 또는 q를 입력하세요"
               gameLoop target attempts
   ()
    


[<EntryPoint>]
let main argv =
    printfn "=== F# 숫자 맞추기 게임 ==="
    printfn "1부터 100 사이의 숫자를 맞춰보세요!"
    // 1 이상 101 미만의 랜덤 숫자 생성 (즉, 1~100)
    let target = rnd.Next(1, 101)
    gameLoop target 0
    0 // 프로그램 종료 코드

 

 

 

 

그리고 개선점을 받았다.

 

 

 

이건 챗지피티가 리팩토링해준 코드다.

open System

let rnd = Random()

let rec gameLoop target attempts =
    printf "숫자를 입력하세요 (1~100, q = 종료): "
    let input = Console.ReadLine()

    match input with
    | "q" | "Q" ->
        printfn "게임을 종료합니다. 정답은 %d였습니다." target

    | _ ->
        match Int32.TryParse input with
        | true, guess ->
            if guess < target then
                printfn "업!"
                gameLoop target (attempts + 1)
            elif guess > target then
                printfn "다운!"
                gameLoop target (attempts + 1)
            else
                printfn "정답! %d번 만에 맞췄어요." (attempts + 1)
        | false, _ ->
            printfn "숫자를 입력하거나 q를 입력해 종료할 수 있어요."
            gameLoop target attempts

[<EntryPoint>]
let main argv =
    printfn "=== F# 숫자 맞추기 게임 ==="
    printfn "1부터 100 사이의 숫자를 맞춰보세요!"
    let target = rnd.Next(1, 101)
    gameLoop target 0
    0

 

 

 

아직 더 알아가야하지만 이정도면 쉽게 공부가 되는 것 같다.

반응형