-
Notifications
You must be signed in to change notification settings - Fork 0
/
hangman.go
75 lines (62 loc) · 1.28 KB
/
hangman.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"bufio"
"fmt"
"log"
"math/rand"
"os"
"strings"
"time"
)
func checkErr(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
file, err := os.Open("words.txt")
checkErr(err)
scanner := bufio.NewScanner(file)
reader := bufio.NewReader(os.Stdin)
var choices []string
for scanner.Scan() {
choices = append(choices, scanner.Text())
}
secretWord := choices[rand.Intn(len(choices))]
curGuessed := make([]rune, len(secretWord))
for i := range curGuessed {
curGuessed[i] = '_'
}
numGuesses := 0
for true {
for _, char := range curGuessed {
fmt.Print(string(char), " ")
}
fmt.Println("\nGuess a word or character: ")
guessWord, err := reader.ReadString('\n')
checkErr(err)
guessWord = strings.Trim(guessWord, "\n")
if len(guessWord) != len(secretWord) && len(guessWord) != 1 {
fmt.Println("Wrong number of characters!")
continue
}
if guessWord == secretWord {
break
} else if len(guessWord) == 1 {
guessChar := []rune(guessWord)[0]
for i, char := range secretWord {
if char == guessChar {
curGuessed[i] = char
}
}
}
if string(curGuessed) == secretWord {
break
}
numGuesses++
}
fmt.Println("You win! It took you ", numGuesses, " guesses.")
}
func init() {
rand.Seed(time.Now().Unix())
}