Improved error handling for inputting lives

Also added the ability to view the secret word after losing
This commit is contained in:
raul 2024-02-20 08:26:01 +00:00
parent 75d3b08974
commit 5e1c4315fc
1 changed files with 21 additions and 37 deletions

58
main.go
View File

@ -59,18 +59,23 @@ func main() {
fillSecrets() fillSecrets()
for { 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() clear()
@ -119,6 +124,7 @@ func checkWin() {
func checkLose() { func checkLose() {
if player.lives < 0 { if player.lives < 0 {
fmt.Println("You lose!") fmt.Println("You lose!")
fmt.Printf("The word was %v!\n", revealedChars)
os.Exit(0) os.Exit(0)
} }
} }
@ -191,38 +197,16 @@ func game() {
time.Sleep(1 * time.Second) 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 { if err != nil {
fmt.Println(err) //fmt.Println(err)
os.Exit(2) errHappened = true
} }
return errHappened
} }
func getWord(path string) (word string) { func getWord(path string) (word string) {