golang实战小案例---我想你猜小游戏

简介: golang实战小案例---我想你猜小游戏

main.go

package main
import (
    "math/rand"
    "time"
)
func main() {
    // generate a random seed
    rand.Seed(time.Now().UnixNano())
    a := newAnswer()
    m := newMenu(a)
    m.run()
}

animal.go

package main
type animal struct {
    name         string
    hasScales    bool
    hasTail      bool
    hasLegs      bool
    livesInWater bool
}
func fish() animal {
    return animal{
        name:         "fish",
        hasScales:    true,
        hasTail:      true,
        hasLegs:      false,
        livesInWater: true,
    }
}
func lizard() animal {
    return animal{
        name:         "lizard",
        hasScales:    true,
        hasTail:      true,
        hasLegs:      true,
        livesInWater: false,
    }
}
func crab() animal {
    return animal{
        name:         "crab",
        hasScales:    false,
        hasTail:      false,
        hasLegs:      true,
        livesInWater: true,
    }
}

answer.go

package main
import (
    "math/rand"
)
type answer struct {
    chosen animal
    all    []animal
}
// newAnswer returns an answer
func newAnswer() answer {
    var a answer
    a.all = []animal{
        fish(),
        lizard(),
        crab(),
    }
    // generate a random integer based on the length of the slice
    randomInteger := rand.Intn(len(a.all) - 1)
    // assign the chosen animal
    a.chosen = a.all[randomInteger]
    return a
}
func (a answer) name() string {
    return a.chosen.name
}
func (a answer) hasScales() string {
    if a.chosen.hasScales == true {
        return "Yes, this animal has scales."
    }
    return "No, this animal does not have scales."
}
func (a answer) hasTail() string {
    if a.chosen.hasTail == true {
        return "Yes, this animal does have a tail."
    }
    return "No, this animal does not have a tail."
}
func (a answer) hasLegs() string {
    if a.chosen.hasLegs == true {
        return "Yes, this animal does have legs."
    }
    return "No, this animal does not have legs."
}
func (a answer) livesInWater() string {
    if a.chosen.livesInWater == true {
        return "Yes, this animal lives in the water."
    }
    return "No, this animal does not live in the water."
}

menu.go

package main
import (
    "bufio"
    "fmt"
    "log"
    "os"
    "strconv"
)
type menu struct {
    scanner *bufio.Scanner
    answer  answer
    player  string
}
func newMenu(a answer) menu {
    return menu{answer: a, scanner: bufio.NewScanner(os.Stdin)}
}
func (m menu) run() {
    fmt.Println("Hello, what is your name?")
    m.scanner.Scan()
    if err := m.scanner.Err(); err != nil {
        log.Println(err)
        os.Exit(1)
    }
    m.player = m.scanner.Text()
    fmt.Printf("\n\n")
    fmt.Println("Hello", m.player, "let's play a game!")
    fmt.Println("I will think of an animal and you will try to guess what it is.")
    fmt.Printf("The possible answers are: ")
    for i := range m.answer.all {
        fmt.Printf("%s ", m.answer.all[i].name)
    }
    fmt.Printf("\n")
    m.top()
}
func (m menu) top() {
    for {
        fmt.Printf("\n\n")
        fmt.Println("What would you like to do?")
        fmt.Println("1) Ask a question about the animal")
        fmt.Println("2) Guess the animal")
        fmt.Println("3) Quit the program")
        m.scanner.Scan()
        if err := m.scanner.Err(); err != nil {
            log.Println(err)
            os.Exit(1)
        }
        switch m.scanner.Text() {
        case "1":
            m.question()
            continue
        case "2":
            m.guess()
            continue
        case "3":
            fmt.Printf("Good bye %s, thanks for playing!\n", m.player)
            os.Exit(1)
        default:
            fmt.Println("I'm sorry, that isn't one of your choices. Please try again.")
        }
    }
}
func (m menu) question() {
    for {
        fmt.Printf("\n\n")
        fmt.Println("What would you like to ask?")
        fmt.Println("1) Does the animal have scales?")
        fmt.Println("2) Does the animal have a tail?")
        fmt.Println("3) Does the animal have legs?")
        fmt.Println("4) Does the animal live in the water?")
        m.scanner.Scan()
        if err := m.scanner.Err(); err != nil {
            log.Println(err)
            os.Exit(1)
        }
        switch m.scanner.Text() {
        case "1":
            fmt.Println(m.answer.hasScales())
            return
        case "2":
            fmt.Println(m.answer.hasTail())
            return
        case "3":
            fmt.Println(m.answer.hasLegs())
            return
        case "4":
            fmt.Println(m.answer.livesInWater())
            return
        default:
            fmt.Printf("\n\n")
            fmt.Println("I'm sorry, I didn't understand that answer. " +
                "Please enter a number that corresponds with your question.")
        }
    }
}
func (m menu) guess() {
    for {
        fmt.Printf("\n\n")
        fmt.Println("What animal am I thinking of?")
        for i := range m.answer.all {
            fmt.Printf("%v) %s\n", i+1, m.answer.all[i].name)
        }
        m.scanner.Scan()
        if err := m.scanner.Err(); err != nil {
            log.Println(err)
            os.Exit(1)
        }
        i, err := strconv.Atoi(m.scanner.Text())
        if err != nil || i > len(m.answer.all) || i < 1 {
            fmt.Println("I'm sorry, I didn't understand that answer. Please enter an answer by typing in a number.")
            continue
        }
        if m.answer.all[i-1].name == m.answer.chosen.name {
            fmt.Printf("\n\n")
            fmt.Printf("That's right %s! I was thinking of %s\n", m.player, m.answer.chosen.name)
            return
        }
        fmt.Printf("\n\n")
        fmt.Printf("Sorry %s, that wasn't the animal I was thinking of.\n", m.player)
        return
    }
}


目录
相关文章
Golang反射---结构体的操作案例大全
Golang反射---结构体的操作案例大全
82 0
|
3月前
|
Go
Golang生成随机数案例实战
关于如何使用Go语言生成随机数的三个案例教程。
206 91
Golang生成随机数案例实战
|
7月前
|
NoSQL 测试技术 Go
【Golang】国密SM2公钥私钥序列化到redis中并加密解密实战_sm2反编(1)
【Golang】国密SM2公钥私钥序列化到redis中并加密解密实战_sm2反编(1)
|
3月前
|
Go
Golang的time.NewTimer单次定时器使用案例
这篇文章介绍了Go语言中time包的多种定时器使用案例,包括单次定时器的创建、阻塞程序运行的Sleep函数、重置和停止定时器的方法,以及After和AfterFunc函数的使用。
66 5
Golang的time.NewTimer单次定时器使用案例
|
3月前
|
Prometheus Cloud Native Go
Golang语言之Prometheus的日志模块使用案例
这篇文章是关于如何在Golang语言项目中使用Prometheus的日志模块的案例,包括源代码编写、编译和测试步骤。
80 3
Golang语言之Prometheus的日志模块使用案例
|
3月前
|
Linux Go 开发工具
Golang各平台环境搭建实战
这篇文章详细介绍了如何在Windows、Linux和Mac平台上搭建Golang开发环境,包括下载和安装Go SDK、配置环境变量、安装开发工具如Visual Studio Code和Go扩展,以及如何编写和运行第一个Go程序。
136 3
|
3月前
|
Go
Golang语言基本数据类型默认值及字符串之间互相转换案例
这篇文章讲解了Golang语言中基本数据类型的默认值、类型转换的概述以及整型、浮点型、字符串之间的相互转换案例,包括如何将基本数据类型转换为字符串类型和字符串类型转换为基本数据类型,以及字符串与字节切片之间的转换。
35 2
|
3月前
|
Go
Golang的time.NewTicker周期性定时器使用案例
这篇文章介绍了Golang中time包的NewTicker函数如何创建周期性定时器,并通过两个示例展示了如何使用定时器以及如何停止定时器。
81 1
|
3月前
|
Go
Golang语言数据类型分类及进制转换案例
这篇文章详细介绍了Go语言中数据类型的分类、进制转换的概念和实例,以及数字字面量语法,还涉及了原码、反码和补码的相关知识。
27 0
Golang语言数据类型分类及进制转换案例
|
4月前
|
NoSQL Java 测试技术
Golang内存分析工具gctrace和pprof实战
文章详细介绍了Golang的两个内存分析工具gctrace和pprof的使用方法,通过实例分析展示了如何通过gctrace跟踪GC的不同阶段耗时与内存量对比,以及如何使用pprof进行内存分析和调优。
120 0
Golang内存分析工具gctrace和pprof实战