Advertisement
cwchen

[Go] guess number demo.

Sep 16th, 2017
856
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.30 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "bufio"
  5.     "fmt"
  6.     "math/rand"
  7.     "os"
  8.     "strconv"
  9.     "time"
  10. )
  11.  
  12. func main() {
  13.     const MIN int = 1
  14.     const MAX int = 100
  15.  
  16.     // Init a new rand object
  17.     r := rand.New(rand.NewSource(time.Now().UnixNano()))
  18.  
  19.     // Init the state of our program
  20.     answer := r.Intn(MAX) + MIN
  21.     guess := -1
  22.     min := MIN
  23.     max := MAX
  24.  
  25.     // Build a scanner object which receives data from standard input
  26.     scanner := bufio.NewScanner(os.Stdin)
  27.  
  28.     // Main game loop
  29. OUTER_LOOP:
  30.     for {
  31.         // Receive user input
  32.     INNER_LOOP:
  33.         for {
  34.             fmt.Print("Input a number between ", min, " and ", max, ": ")
  35.  
  36.             for scanner.Scan() {
  37.                 input := scanner.Text()
  38.  
  39.                 n, err := strconv.ParseInt(input, 10, 0) // n is int64
  40.  
  41.                 // Convert the number from int64 to int
  42.                 num := int(n)
  43.  
  44.                 if err != nil {
  45.                     fmt.Fprintf(os.Stderr, "Invalid number: %s\n", input)
  46.                     break
  47.                 } else if num < min || num > max {
  48.                     fmt.Fprintf(os.Stderr, "Number out of range: %d\n", num)
  49.                     break
  50.                 } else {
  51.                     guess = num
  52.                     break INNER_LOOP
  53.                 }
  54.             }
  55.         }
  56.  
  57.         // Check our guess is correct
  58.         if guess > answer {
  59.             fmt.Println("Too large")
  60.             max = guess
  61.         } else if guess < answer {
  62.             fmt.Println("Too small")
  63.             min = guess
  64.         } else {
  65.             fmt.Println("You guess right")
  66.             break OUTER_LOOP
  67.         }
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement