From 5e1c4315fcf22848c09782c61c52b8777e8a718a Mon Sep 17 00:00:00 2001 From: raul Date: Tue, 20 Feb 2024 08:26:01 +0000 Subject: [PATCH] Improved error handling for inputting lives Also added the ability to view the secret word after losing --- main.go | 58 +++++++++++++++++++++------------------------------------ 1 file changed, 21 insertions(+), 37 deletions(-) diff --git a/main.go b/main.go index 105bee5..ecec661 100644 --- a/main.go +++ b/main.go @@ -59,18 +59,23 @@ func main() { fillSecrets() for { - clear() + for { + clear() + fmt.Printf("Welcome to the hanged man game!\nMay I know your name?\nName: ") + player.name = scanLine() + fmt.Printf("How many lives would you like to have?\nLives: ") + stringLives := scanLine() - // TODO: Use type assertions to do error handling + intLives, err := strconv.Atoi(stringLives) + if catchErr(err) != true { + player.lives = int8(intLives) + break + } else { + fmt.Println("Please, input a valid number") + time.Sleep(time.Second) + } - fmt.Printf("Welcome to the hanged man game!\nMay I know your name?\nName: ") - player.name = scanLine() - fmt.Printf("How many lives would you like to have?\nLives: ") - stringLives := scanLine() - - intLives, err := strconv.Atoi(stringLives) - catchErr(err) - player.lives = int8(intLives) + } clear() @@ -119,6 +124,7 @@ func checkWin() { func checkLose() { if player.lives < 0 { fmt.Println("You lose!") + fmt.Printf("The word was %v!\n", revealedChars) os.Exit(0) } } @@ -191,38 +197,16 @@ func game() { time.Sleep(1 * time.Second) } } - - // if getLetter(guess) == true { - // if alreadyGuessed() == true { - // fmt.Printf("You've already guessed this letter") - // time.Sleep(1 * time.Second) - // } - // } - - // var isAlreadyWrong bool = false - // for _, v := range wrongChars { - // if v == guess { - // isAlreadyWrong = true - // } - // } - // if isAlreadyWrong == true { - // fmt.Printf("You've already guessed this letter") - // time.Sleep(1 * time.Second) - // } else { - // fmt.Printf("Wrong!") - // wrongChars = append(wrongChars, guess) - // player.lives-- - // time.Sleep(1 * time.Second) - // } - } } -func catchErr(err error) { +func catchErr(err error) (errHappened bool) { + errHappened = false if err != nil { - fmt.Println(err) - os.Exit(2) + //fmt.Println(err) + errHappened = true } + return errHappened } func getWord(path string) (word string) {