Golang에서 타이핑 속도 테스트 CLI 애플리케이션 작성

Susan Sarandon
풀어 주다: 2024-10-18 10:31:03
원래의
567명이 탐색했습니다.

Writing a Typing Speed Test CLI Application in Golang

그 제목에 대해 오랫동안 고민해야 했나요?... ​​이제 그 문제를 해결했으니 멋진 코드를 작성해 보겠습니다. :)

펌프 브레이크 ? 삐걱삐걱.... 오늘 우리가 만들려고 하는 것에 대해 약간 소개하겠습니다. 제목이 명확하지 않은 경우 golang에서 타이핑 속도를 계산하는 CLI 애플리케이션을 구축할 것입니다. 물론 선택한 프로그래밍 언어에서 동일한 기술을 사용하여 문자 그대로 동일한 애플리케이션을 구축할 수도 있습니다.

이제 코딩해볼까요?

package main

import (
    "bufio"
    "fmt"
    "log"
    "math/rand"
    "os"
    "strings"
    "time"
)

var sentences = []string{
    "There are 60 minutes in an hour, 24 hours in a day and 7 days in a week",
    "Nelson Mandela is one of the most renowned freedom fighters Africa has ever produced",
    "Nigeria is the most populous black nation in the world",
    "Peter Jackson's Lord of the rings is the greatest film of all time",
}

로그인 후 복사

main.go 파일에서 로직을 작성하는 데 필요한 패키지를 가져옵니다. 우리는 또한 문장 조각을 만듭니다. 더 많이 추가해 보세요.

// A generic helper function that randomly selects an item from a slice
func Choice[T any](ts []T) T {
    return ts[rand.Intn(len(ts))]
}

// Prompts and collects user input from the terminal
func Input(prompt string) (string, error) {
    fmt.Print(prompt)
    r := bufio.NewReader(os.Stdin)

    line, err := r.ReadString('\n')
    if err != nil {
        return "", err
    }

    return strings.Trim(line, "\n\r\t"), nil
}

// Compares two strings and keeps track of the characters  
// that match and those that don't
func CompareChars(target, source string) (int, int) {
    var valid, invalid int

    // typed some of the words
        // resize target to length of source
    if len(target) > len(source) {
        diff := len(target) - len(source)
        invalid += diff
        target = target[:len(source)]
    }

    // typed more words than required
        // resize source to length of target
    if len(target) < len(source) {
        invalid++
        source = source[:len(target)]
    }

    for i := 0; i < len(target); i++ {
        if target[i] == source[i] {
            valid++
        }
        if target[i] != source[i] {
            invalid++
        }
    }

    return valid, invalid
}

// Calculates the degree of correctness
func precision(pos, fal int) int {
    return pos / (pos + fal) * 100
}

// Self explanatory - don't stress me ?
func timeElapsed(start, end time.Time) float64 {
    return end.Sub(start).Seconds()
}

// Refer to the last comment
func accuracy(correct, total int) int {
    return (correct / total) * 100
}

// ?
func Speed(chars int, secs float64) float64 {
    return (float64(chars) / secs) * 12
}


로그인 후 복사

그런 다음 애플리케이션 로직을 작성할 때 유용하게 사용할 몇 가지 함수를 만듭니다.

func main() {
    fmt.Println("Welcome to Go-Speed")
    fmt.Println("-------------------")

    for {
        fmt.Printf("\nWould you like to continue? (y/N)\n\n")
        choice, err := Input(">> ")
        if err != nil {
            log.Fatalf("could not read value: %v", err)
        }

        if choice == "y" {
            fmt.Println("Starting Game...")
            timer := time.NewTimer(time.Second)
            fmt.Print("\nBEGIN TYPING NOW!!!\n\n")
            _ = <-timer.C

            sentence := Choice(sentences)
            fmt.Printf("%s\n", sentence)

            start := time.Now()
            response, err := Input(">> ")
            if err != nil {
                log.Fatalf("could not read value: %v", err)
            }

            elasped := timeElapsed(start, time.Now())
            valid, invalid := CompareChars(sentence, response)
            fmt.Print("\nResult!\n")
            fmt.Println("-------")
            fmt.Printf("Correct Characters: %d\nIncorrect Characters: %d\n", valid, invalid)
            fmt.Printf("Accuracy: %d%%\n", accuracy(valid, len(sentence)))
            fmt.Printf("Precision: %d%%\n", precision(valid, invalid))
            fmt.Printf("Speed: %.1fwpm\n", Speed(len(sentence), elasped))
            fmt.Printf("Time Elasped: %.2fsec\n", elasped)
        }

        if choice == "N" {
            fmt.Println("Quiting Game...")
            break
        }

        if choice != "N" && choice != "y" {
            fmt.Println("Invalid Option")
        }
    }
}
로그인 후 복사

주 함수에서는 터미널에 환영 메시지를 쓰고 무한 루프를 만들어 프로그램을 실행합니다. 그런 다음 프로그램을 종료하는 옵션과 함께 확인 메시지를 stdout(터미널)에 인쇄합니다. 계속하기를 선택하면 이전에 작성된 문장 조각에서 문장이 선택되어 시작 시간이 기록된 직후 터미널에 표시됩니다. 우리는 사용자 입력을 수집하고 시간, 속도, 정밀도 및 정확도를 계산한 다음 결과를 다시 터미널에 표시합니다. 무한 루프가 재설정되고 프로그램을 선택 해제할 때까지 애플리케이션이 다시 실행됩니다.

짜잔!!! 우리는 golang으로 첫 번째 프로그램을 작성했습니다.

위 내용은 Golang에서 타이핑 속도 테스트 CLI 애플리케이션 작성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!