Skip to content

Instantly share code, notes, and snippets.

@amitk
Last active April 7, 2020 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amitk/a5e2b69d5fe26bc91ed2a36574b235c9 to your computer and use it in GitHub Desktop.
Save amitk/a5e2b69d5fe26bc91ed2a36574b235c9 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
func main() {
word := "elephant"
// lookup for entries made by the user.
// entries := make(map[string]bool)
// list of "_" corrosponding to the number of letters in the word. [ _ _ _ _ _ ]
placeholder := make([]string, len(word), len(word))
var guesses string
for i := range word {
placeholder[i] = "_"
}
chances := 8
for {
// evaluate a loss! If user guesses a wrong letter or the wrong word, they lose a chance.
// evaluate a win!
userInput := strings.Join(placeholder, "")
if chances == 0 && userInput != word {
fmt.Println("You are hanged!")
break
}
if userInput == word {
fmt.Println("You won!")
break
}
// Console display
fmt.Println("\n")
fmt.Println(placeholder) // render the placeholder
fmt.Printf("Chances Left: %v\n",chances) // render the chances left
fmt.Printf("Wrong Guesses: [%v]\n", guesses) // show the letters or words guessed till now.
fmt.Printf("Guess a word: ")
// take the input
str := ""
fmt.Scanln(&str)
// compare and update entries, placeholder and chances.
if strings.Contains(word, str) {
for i,v := range word {
if string(v) == str {
placeholder[i] = str //update placeholder array
}
}
} else {
if !strings.Contains(guesses, str){
chances -= 1 //decrement chances
guesses += str; //update gusses
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment