Bootstrap

golang 猜单词

package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"
)


func printMsg(dynWord []byte){
	for _, c := range dynWord {
		fmt.Print(string(c))
	}
	fmt.Println()
}

func main() {
	rand.Seed(time.Now().UnixNano())
	words := []string{"hello", "example", "struct"}
	nIndex := rand.Intn(len(words))
	selectWord := words[nIndex]
	dynWord := []byte{}
	for i := 0; i < len(selectWord); i++ {
		dynWord = append(dynWord, '-')
	}

	printMsg(dynWord)

	guessTimes := 3
	for {
		bFind := false
		input := ""
		fmt.Scan(&input)

		for idx, c := range selectWord {
			if byte(c) == input[0] {
				dynWord[idx] = byte(c)
				bFind = true
			}
		}

		printMsg(dynWord)

		if !strings.Contains(string(dynWord), string('-')){
			break
		}
		if bFind == false{
			guessTimes--
			msg := "you have "+ strconv.Itoa(guessTimes) +" left"
			fmt.Println(msg)
		}
		if guessTimes <= 0{
			break
		}

	}
	if guessTimes <= 0 {
		fmt.Println("you lose")
	} else {
		fmt.Println("you win")
	}
}

;