gopher-the-number/lib.go

42 lines
877 B
Go
Raw Normal View History

2023-03-15 17:11:00 +01:00
package main
2023-03-15 17:09:26 +01:00
import (
"bufio"
"fmt"
"io"
"strconv"
)
2024-02-17 14:31:47 +01:00
// CheckGuess checks the guess against the random value and returns a status message alongside
// a win boolean.
2023-03-15 17:09:26 +01:00
func CheckGuess(guess, random int) (string, bool) {
if guess == random {
return "Good job!", true
}
if random > guess {
return "Try higher.", false
}
return "Nope, lower.", false
}
func LoopUntilFound(writer io.Writer, reader io.Reader, random int) {
scanner := bufio.NewScanner(reader)
win := false
count := 0
for !win {
fmt.Fprint(writer, "your guess: ")
scanner.Scan()
value := scanner.Text()
guess, _ := strconv.Atoi(value)
var msg string
msg, win = CheckGuess(guess, random)
fmt.Fprintf(writer, "\n%v\n", msg)
count++
}
if count == 1 {
fmt.Fprintln(writer, "You got it right in 1 try.")
} else {
fmt.Fprintf(writer, "You got it right in %d tries.\n", count)
}
}