Created
April 4, 2020 05:55
-
-
Save gautamrege/1321ee1453d05dab7e813a7054590f54 to your computer and use it in GitHub Desktop.
Hangman Part-2 (get random word)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"strings" | |
) | |
const MAX_CHANCES int = 8 | |
func get_keys(entries map[string]bool) []string { | |
keys := []string{} | |
for k, _ := range entries { | |
keys = append(keys, k) | |
} | |
return keys | |
} | |
// get random word from https://random-word-api.herokuapp.com/word | |
func get_word() string { | |
// in case of any error, return "elephant" | |
} | |
func main() { | |
word := get_word() | |
entries := map[string]bool{} | |
placeholder := make([]string, len(word), len(word)) | |
// initialize to '_' | |
for i := range word { | |
placeholder[i] = "_" | |
} | |
for { | |
// evaluate a loss! | |
if len(entries) == MAX_CHANCES { | |
fmt.Println("Damn! You're hanged!!") | |
fmt.Println("Word was: ", word) | |
break | |
} | |
// evaluate a win! | |
if strings.Join(placeholder, "") == word { | |
fmt.Println("You win! You've saved yourself from a hanging") | |
break | |
} | |
fmt.Println("\n") | |
fmt.Println(placeholder) | |
fmt.Printf("Chances left: %d\n", MAX_CHANCES-len(entries)) | |
fmt.Printf("Guesses: %s\n", get_keys(entries)) | |
fmt.Printf("Guess a letter or the word: ") | |
str := "" | |
fmt.Scanln(&str) | |
str = strings.TrimSuffix(str, "\n") | |
if str == word { | |
fmt.Println("You're right - you win!") | |
break | |
} else if str == "" { | |
// someone pressed enter direclty! | |
continue | |
} else if len(str) > 1 { | |
fmt.Printf("Nope! %s is wrong. You lose a chance.\n", str) | |
entries[str] = true | |
continue | |
} | |
input := rune(str[0]) // take input and convert to rune (similar to char) | |
found := false | |
for i, e := range word { | |
if input == e { | |
placeholder[i] = string(input) | |
found = true | |
} | |
} | |
if !found { | |
entries[string(str)] = true | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment