diff --git a/lib.go b/lib.go index cd0737a..a941c4b 100644 --- a/lib.go +++ b/lib.go @@ -1,5 +1,12 @@ package main +import ( + "bufio" + "fmt" + "io" + "strconv" +) + func CheckGuess(guess, random int) (string, bool) { if guess == random { return "Good job!", true @@ -9,3 +16,24 @@ func CheckGuess(guess, random int) (string, bool) { } 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) + } +} diff --git a/lib_test.go b/lib_test.go index c71f25b..923d49c 100644 --- a/lib_test.go +++ b/lib_test.go @@ -1,6 +1,8 @@ package main import ( + "bytes" + "strings" "testing" ) @@ -49,3 +51,58 @@ func assertCheckGuess(t testing.TB, guess, random int, wantStatus string, wantWo t.Errorf("got %v want %v", won, wantWon) } } + +func TestLoopUntilFound(t *testing.T) { + t.Run("found on first try", func(t *testing.T) { + output := bytes.Buffer{} + input := strings.NewReader("37\n") + random := 37 + LoopUntilFound(&output, input, random) + + got := output.String() + want := "your guess: \nGood job!\nYou got it right in 1 try.\n" + + if got != want { + t.Errorf("got %q want %q", got, want) + } + }) + t.Run("found on second try", func(t *testing.T) { + output := bytes.Buffer{} + input := strings.NewReader("50\n37\n") + random := 37 + LoopUntilFound(&output, input, random) + + got := output.String() + want := "your guess: \nNope, lower.\nyour guess: \nGood job!\nYou got it right in 2 tries.\n" + + if got != want { + t.Errorf("got %q want %q", got, want) + } + }) + t.Run("found after many tries", func(t *testing.T) { + output := bytes.Buffer{} + inputs := []string{"50", "25", "32", "37", ""} + input := strings.NewReader(strings.Join(inputs, "\n")) + random := 37 + LoopUntilFound(&output, input, random) + + got := output.String() + wants := []string{ + "your guess: ", + "Nope, lower.", + "your guess: ", + "Try higher.", + "your guess: ", + "Try higher.", + "your guess: ", + "Good job!", + "You got it right in 4 tries.", + "", + } + want := strings.Join(wants, "\n") + + if got != want { + t.Errorf("got %q want %q", got, want) + } + }) +} diff --git a/main.go b/main.go index 06ab7d0..7182c0e 100644 --- a/main.go +++ b/main.go @@ -1 +1,11 @@ package main + +import ( + "math/rand" + "os" +) + +func main() { + random := rand.Intn(100) + LoopUntilFound(os.Stdout, os.Stdin, random) +}