Go Channel Practice V - 祖安萝莉
idea 来自 https://www.zhihu.com/question/402635037/answer/1302122540
逻辑没有照抄,只是做 channel 使用方法练习。
package main import ( "bufio" "fmt" "math/rand" "os" "sync" "time" ) var universal = []string{ "你说你马呢?", "那没事了。", "真别逗我笑啊。", "那可真是有趣呢。", "就这?就这?", "你品,你细品。", "不会真有人觉得是这样的吧,不会吧不会吧?", "你在教我做事?", } var strong = []string{ "你急了急了急了?", "他急了,他急了!", } var question = []string{ "不会真有人还不知道吧?", "你都不知道,那你说你马呢?", "说你马呢?", } var questionMap = map[string]bool{ "不会真有人还不知道吧?": true, "你都不知道,那你说你马呢?": true, "说你马呢?": true, } var strongExpressionMap = map[string]bool{ "!": true, "???": true, "???": true, "气抖冷": true, } var expressionMap = map[string]bool{ "?": true, "怎么": true, "什么": true, "咋": true, "?": true, } func main() { scanner := bufio.NewScanner(os.Stdin) var wg sync.WaitGroup output := make(chan string, 40) quit := make(chan os.Signal) go collectOutput(output, quit) fmt.Print(">>>: ") for scanner.Scan() { input := scanner.Text() wg.Add(1) go func(input string) { defer wg.Done() parseInput(input, output) }(input) } wg.Wait() if scanner.Err() != nil { panic("scan error") } } func parseInput(input string, output chan string) { rand.Seed(time.Now().UnixNano()) if _, ok := questionMap[input]; ok { output <- universal[rand.Intn(len(universal))] return } if _, ok := expressionMap[input]; ok { output <- universal[rand.Intn(len(universal))] return } if _, ok := strongExpressionMap[input]; ok { output <- strong[rand.Intn(len(strong))] return } output <- universal[rand.Intn(len(universal))] } func collectOutput(output chan string, quit chan os.Signal) { for { select { case o := <-output: time.Sleep(time.Duration(rand.Intn(2)) * time.Second) fmt.Println("你马bot: ", o) fmt.Print(">>>: ") case <-quit: return } } }
Feb 22, 2022 05:14:44 PM
This is one of the best courses where there can be lots of great and nice activities that will be performed out here.