猜數字遊戲(Go實現)
阿新 • • 發佈:2019-02-15
後面會使用Unity3D加上UI
package main
import (
"fmt"
"bufio"
"os"
"strconv"
"math/rand"
"time"
)
var RANGENUM int = 20
func CreateRangeNum(num int) int {
ret := rand.New(rand.NewSource(time.Now().UnixNano())) //使用時間種子來獲取不同的結果
//ret := rand.Intn(num)
return ret.Intn(num)
}
func main() {
i := CreateRangeNum(RANGENUM)
fmt.Println("Please enter a numble in the range:0 -",RANGENUM)
reader := bufio.NewReader(os.Stdin) //類比C中的標準化輸入
for {
data,_,_ := reader.ReadLine()
command,err := strconv.Atoi(string(data))
if err != nil {
fmt.Println("The format is wrong, please enter the number!!!" )
} else {
if command == i {
fmt.Println("Congratulations, you got it")
break
} else if command > i {
fmt.Println("The number you enter is greater than the generated number. Don't be discouraged!Again")
} else {
fmt.Println("The number you enter is less than the generated number. Don't be discouraged!Again")
}
}
}
}