Guess the number game in golang



Source--IYOCGwP, Chapter 4 - Guess the Number - http://bit.ly/STSh0p

In python source code...

# This is a guess the number game.
import random
guessesTaken = 0
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 20)
print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
while guessesTaken < 6:
    print('Take a guess.') # There are four spaces in front of print.
    guess = input()
    guess = int(guess)
    guessesTaken = guessesTaken + 1
    if guess < number:
        print('Your guess is too low.') # There are eight spaces in front of print.
    if guess > number:
        print('Your guess is too high.')
    if guess == number:
        break
if guess == number:
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
    number = str(number)
    print('Nope. The number I was thinking of was ' + number)

Same game, but this time, in Go source code...

// converting python games into golang
package main
import(
    "fmt"
    "math/rand"
    "time"
)

//this generates random number between given range
func xrand(min, max int) int {
    rand.Seed(time.Now().Unix())
    return rand.Intn(max - min) + min
}

func main() {
    var myname string
    myrand := xrand(1, 6)
    guessTaken := 0
    var guess int

    fmt.Println("Hello! What is your name?")
    fmt.Scanf("%s", &myname)
    fmt.Printf("Well, %s, I am thinking of a number between 1 and 6.\n", myname)
    
    //this is the while loop
    for guessTaken < 6 {
        fmt.Println("Take a guess...")
        fmt.Scanf("%d", &guess)
        guessTaken++
        if guess < myrand {
            fmt.Println("Your guess is too low.")
        }
        if guess > myrand {
            fmt.Println("Your guess is too high.")
        }
        if guess == myrand {
            break
        }
    }
    if guess == myrand {
        fmt.Printf("Good job %s! You guessed my number in %d tries\n", myname, guessTaken)
    } else {
        fmt.Printf("Nope. The number I had in mind was %d\n", myrand)
    }
}

*using else if...

if guess < myrand {
        fmt.Println("Your guess is too low.")
    } else if guess > myrand {
        fmt.Println("Your guess is too high.")
    } else {
        break
    }

2 comments:

  1. I just read the regularly one particular subject material. Beautiful blog or reviews, thank you to suit downloading and sharing an blog content with all of us. Matka || Satta Matka || Satta Matka Result || Kalyan Matka || Mumbai Matka

    ReplyDelete