Files
headfirstgo/chapter2/guess/guess.go
Archie Fox 2e7b8722ca Init commit
2025-01-30 12:04:39 +03:00

54 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// guess - игра про отгадывание числа
package main
import (
"fmt"
"math/rand"
// "time"
"bufio"
"log"
"os"
"strconv"
"strings"
)
func main() {
/* seconds := time.Now().Unix()
rand.Seed(seconds) */ // is deprecated
target := rand.Intn(100) + 1
fmt.Println("Я загадал число от 1 до 100. Отгадай его: ")
// fmt.Println(target)
reader := bufio.NewReader(os.Stdin) // новый буфер для чтения с клавы
success := false
for guesses := 0; guesses < 10; guesses++ {
fmt.Println("У вас есть", 10-guesses, "попыток.")
fmt.Print("Введите свое число: ")
input, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
input = strings.TrimSpace(input) // удаление новой строки
guess, err := strconv.Atoi(input) // конвертация в int
if err != nil {
log.Fatal(err)
}
if guess < target {
fmt.Println("Ваше число меньше загаданного")
} else if guess > target {
fmt.Println("Ваше число больше загаданного")
} else if guess == target {
success = true
fmt.Println("Вы угадали число!!!")
break
}
}
if !success {
fmt.Println("Вы проиграли! Загаданное число", target)
}
}