mercredi 18 mai 2022

In Go, how do stay in a for loop, but print a different output if user guesses too high or too low

I'm trying to develop a guessing game in GO that gives the user three attempts to guess the random number correctly.

It mostly seems to work, I'm using a for loop to count the amount of lives left. If I guess the number correctly, it prints what I want:

"You guessed it!"

But the issue is, say for example, the random number is 5. If I guessed 4, it would print

"Too low"

which is correct, but in the second attempt if I was to guess 6, it would still say

"Too low"

Alternatively, if the random number was 5, and on the first attempt I guessed 6, it would print

"Too high"

If I was to guess 4 on the second attempt, it would still say

"Too high"

I think I'm getting caught in the for loop somewhere, but I don't know how to exit it without resetting the attempts count back to 3.

package main

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

func main() {
    secret := getRandomNumber()
    fmt.Println(secret)

    fmt.Println("Guess the number")

    _guess := guessRandomNumber()

    for i := 3; i > 0; i-- {

        if _guess < secret {
            fmt.Println("Too low")
            fmt.Println("You have", i, "guesses left.")
        } else if _guess < secret {
            fmt.Println("Too low")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        } else if _guess > secret {
            fmt.Println("Too high")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        }

        if _guess == secret {
            fmt.Println("You guessed it!")
            i = 0
        } else if _guess < secret {
            fmt.Println("Too low")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        } else if _guess > secret {
            fmt.Println("Too high")
            fmt.Println("You have", i, "guesses left.")

            guessRandomNumber()
        }
    }

}

func getRandomNumber() int {

    rand.Seed(time.Now().UnixNano())
    return rand.Int() % 11
}

func guessRandomNumber() int {
    var guess int
    //fmt.Println("Guess again:")
    fmt.Scanf("%d", &guess)
    return guess
}

Any help would be greatly appreciated. I'm really liking GO so far.




Aucun commentaire:

Enregistrer un commentaire