Skip to content

Instantly share code, notes, and snippets.

@sadbox
Created May 22, 2014 01:19
Show Gist options
  • Save sadbox/86e9f2fb9b8bbf35c82e to your computer and use it in GitHub Desktop.
Save sadbox/86e9f2fb9b8bbf35c82e to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"errors"
"fmt"
"log"
"math/rand"
"os"
"strings"
"time"
)
func compare(to, from string) (int, error) {
if len(to) != len(from) {
return 0, errors.New("words are of unequal lengths")
}
from = strings.ToUpper(from)
matching := 0
for i := 0; i < len(to); i++ {
if to[i] == from[i] {
matching++
}
}
return matching, nil
}
func readDictionary(filename string) (map[int][]string, error) {
wordmap := make(map[int][]string)
file, err := os.Open(filename)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(file)
var word string
var wordlen int
for scanner.Scan() {
word = scanner.Text()
wordlen = len(word)
if 5 <= wordlen && wordlen <= 16 {
wordmap[wordlen] = append(wordmap[wordlen], strings.ToUpper(word))
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return wordmap, nil
}
func newGame(wordmap map[int][]string) {
fmt.Print("Difficulty (1-5)? ")
var difficulty int
_, err := fmt.Scanf("%d", &difficulty)
if err != nil || (1 > difficulty || difficulty > 5) {
fmt.Println("invalid difficulty entered!")
return
}
difficulty = difficulty*rand.Intn(2) + 5
randomWords := rand.Perm(len(wordmap[difficulty]))[:10]
chosenWord := wordmap[difficulty][randomWords[rand.Intn(10)]]
for _, wordIndex := range randomWords {
fmt.Println(wordmap[difficulty][wordIndex])
}
for guess := 4; guess > 0; guess-- {
fmt.Printf("Guess (%d left)? ", guess)
var guessText string
_, err := fmt.Scanf("%s", &guessText)
if err != nil {
fmt.Println("invalid guess")
continue
}
result, err := compare(chosenWord, guessText)
if err != nil {
fmt.Println(err)
continue
}
fmt.Printf("%d/%d correct\n", result, difficulty)
if result == difficulty {
fmt.Println("You won!")
return
}
}
}
func main() {
rand.Seed(time.Now().UTC().UnixNano())
wordmap, err := readDictionary("enable1.txt")
if err != nil {
log.Fatal(err)
}
for {
fmt.Println("NEW GAME:")
newGame(wordmap)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment