首頁 > 後端開發 > Golang > 主體

使用 Golang 編寫打字速度測試 CLI 應用程式

Susan Sarandon
發布: 2024-10-18 10:31:03
原創
564 人瀏覽過

Writing a Typing Speed Test CLI Application in Golang

必須認真思考這個標題嗎? ……現在我們已經解決了這個問題,讓我們來寫一些該死的程式碼:)

幫浦煞車?尖叫……讓我們對今天要嘗試建立的內容做一些介紹。如果標題不明顯,我們將建立一個 CLI 應用程式來計算您在 golang 中的打字速度 - 儘管您可以使用您選擇的任何程式語言遵循相同的技術來建立相同的應用程式。

現在,我們來編碼吧?

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")
        }
    }
}
登入後複製

在我們的主函數中,我們向終端寫入一條歡迎訊息,並創建一個無限循環來運行我們的程式。然後,我們將確認訊息列印到標準輸出(終端),並提供退出程序的選項。如果您選擇繼續,則會從先前編寫的句子片段中選擇一個句子,並在記錄開始時間後立即顯示在終端中。我們收集使用者輸入並計算時間、速度、精確度和準確度,然後將結果顯示回終端。無限循環重置,應用程式再次運行,直到您選擇退出該程式。

瞧! ! !我們剛剛用 golang 寫了第一個程式。

以上是使用 Golang 編寫打字速度測試 CLI 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!