首页  >  文章  >  后端开发  >  使用 Golang 编写打字速度测试 CLI 应用程序

使用 Golang 编写打字速度测试 CLI 应用程序

Susan Sarandon
Susan Sarandon原创
2024-10-18 10:31:03550浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn