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
    }
}


目录
相关文章
|
8月前
|
Go
Golang反射---结构体的操作案例大全
Golang反射---结构体的操作案例大全
50 0
|
9月前
|
Go 数据库
Golang 语言编写 gRPC 实战项目
Golang 语言编写 gRPC 实战项目
85 0
|
2月前
|
NoSQL 测试技术 Go
【Golang】国密SM2公钥私钥序列化到redis中并加密解密实战_sm2反编(1)
【Golang】国密SM2公钥私钥序列化到redis中并加密解密实战_sm2反编(1)
|
2月前
|
JSON JavaScript 前端开发
Golang深入浅出之-Go语言JSON处理:编码与解码实战
【4月更文挑战第26天】本文探讨了Go语言中处理JSON的常见问题及解决策略。通过`json.Marshal`和`json.Unmarshal`进行编码和解码,同时指出结构体标签、时间处理、omitempty使用及数组/切片区别等易错点。建议正确使用结构体标签,自定义处理`time.Time`,明智选择omitempty,并理解数组与切片差异。文中提供基础示例及时间类型处理的实战代码,帮助读者掌握JSON操作。
35 1
Golang深入浅出之-Go语言JSON处理:编码与解码实战
|
2月前
|
存储 测试技术 Go
Golang框架实战-KisFlow流式计算框架(2)-项目构建/基础模块-(上)
KisFlow项目源码位于&lt;https://github.com/aceld/kis-flow,初始阶段涉及项目构建和基础模块定义。首先在GitHub创建仓库,克隆到本地。项目目录包括`common/`, `example/`, `function/`, `conn/`, `config/`, `flow/`, 和 `kis/`。`go.mod`用于包管理,`KisLogger`接口定义了日志功能,提供不同级别的日志方法。默认日志对象`kisDefaultLogger`打印到标准输出。
631 1
Golang框架实战-KisFlow流式计算框架(2)-项目构建/基础模块-(上)
|
2月前
|
JSON 监控 安全
Golang深入浅出之-Go语言中的反射(reflect):原理与实战应用
【5月更文挑战第1天】Go语言的反射允许运行时检查和修改结构,主要通过`reflect`包的`Type`和`Value`实现。然而,滥用反射可能导致代码复杂和性能下降。要安全使用,应注意避免过度使用,始终进行类型检查,并尊重封装。反射的应用包括动态接口实现、JSON序列化和元编程。理解反射原理并谨慎使用是关键,应尽量保持代码静态类型。
40 2
|
2月前
|
存储 监控 Go
Golang框架实战-KisFlow流式计算框架(1)-概述
KisFlow是针对缺乏数仓平台但又有实时计算需求的企业的解决方案,它提供分布式批量消费、有状态流式计算、数据流监控和分布式任务调度等功能。通过KisFunction实现业务逻辑复用,减轻对业务数据库的压力。系统包括流式计算层和任务调度层,支持多种数据源和中间件集成。KisConfig用于配置管理,KisFunction是基本计算单元。设计目标是使业务工程师能轻松进行流式计算。项目源码可在GitHub查看:https://github.com/aceld/kis-flow。
75 0
Golang框架实战-KisFlow流式计算框架(1)-概述
|
2月前
|
缓存 Cloud Native 测试技术
Golang 乐观锁实战:Gorm 乐观锁的优雅使用
在现代软件开发中,数据一致性是一个永恒的话题。随着系统规模的扩大和并发操作的增加,如何有效地处理并发冲突,确保数据的完整性,成为了开发者必须面对的挑战。本文将带你深入了解 Golang 中 Gorm ORM 库的乐观锁机制,并通过实际示例,展示如何在项目中优雅地使用乐观锁。
|
2月前
|
监控 数据可视化 数据挖掘
Golang性能分析神器:pprof与火焰图实战揭秘
在软件开发的世界里,性能分析如同一把锋利的剑,它能帮助开发者洞悉程序的运行状态,发现并解决那些隐藏在代码深处的性能瓶颈。而在Go语言的生态系统中,pprof无疑是这把剑中的佼佼者。本文将带你深入了解pprof的使用方法,并通过火焰图这一直观的工具,让你对性能分析有一个全新的认识。
|
7月前
|
数据采集 监控 Go
构建企业上网监控软件的基础设施:Golang实战
企业面临着不断增长的网络威胁,为了保障网络安全,上网监控成为不可或缺的一环。本文将介绍如何使用Golang实战构建企业上网监控软件的基础设施,通过简洁高效的代码示例,演示监控数据的收集和处理过程。
221 0