game.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "sort"
  7. )
  8. type Game struct {
  9. Words map[string]*Word
  10. Length int
  11. }
  12. func NewGame() *Game {
  13. return &Game{
  14. Words: make(map[string]*Word),
  15. }
  16. }
  17. func (g Game) scoreWordsByCommonLetterLocations() error {
  18. letterIdxScores := make(map[int]map[string]int)
  19. var lastWord string
  20. for _, word := range g.Words {
  21. word.Score = 0
  22. lastWord = word.Word
  23. }
  24. for idx := range lastWord {
  25. letterIdxScores[idx] = make(map[string]int)
  26. }
  27. for _, word := range g.Words {
  28. for idx, letter := range word.Word {
  29. letterIdxScores[idx][string(letter)]++
  30. }
  31. }
  32. for _, word := range g.Words {
  33. for idx, letter := range word.Word {
  34. word.Score += letterIdxScores[idx][string(letter)]
  35. }
  36. }
  37. return nil
  38. }
  39. func (g Game) FilterWords(guess string, score int) {
  40. for _, word := range g.Words {
  41. if !word.MatchesGuess(guess, score) {
  42. delete(g.Words, word.Word)
  43. }
  44. }
  45. }
  46. func (g Game) getSortedScores() []string {
  47. var sortedWordScores []string
  48. for _, word := range g.Words {
  49. sortedWordScores = append(sortedWordScores, word.Word)
  50. }
  51. // sort words by score
  52. sort.Slice(sortedWordScores, func(i, j int) bool {
  53. return g.Words[sortedWordScores[i]].Score > g.Words[sortedWordScores[j]].Score
  54. })
  55. return sortedWordScores
  56. }
  57. func (g Game) getBestGuess() (string, error) {
  58. return g.getSortedScores()[0], nil
  59. }
  60. func (g Game) printSortedScores() (string, error) {
  61. sortedWordScores := g.getSortedScores()
  62. fmt.Println("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
  63. fmt.Print("Words sorted by Score:\n")
  64. for _, word := range sortedWordScores {
  65. fmt.Printf("%s: %d\n", word, g.Words[word].Score)
  66. }
  67. fmt.Println("")
  68. return sortedWordScores[0], nil
  69. }
  70. func (g Game) getWordsFromStdin() error {
  71. fmt.Println("Enter Words, one per line. Enter a period to end input.")
  72. for {
  73. reader := bufio.NewReader(os.Stdin)
  74. word, _ := reader.ReadString('\n')
  75. word = word[:len(word)-1]
  76. if word == "." {
  77. fmt.Println("got Words!")
  78. break
  79. }
  80. if g.Length == 0 {
  81. g.Length = len(word)
  82. } else {
  83. if len(word) != g.Length {
  84. fmt.Printf("Error: All words must be the same length (%d), skipping: %s\n", g.Length, word)
  85. continue
  86. }
  87. }
  88. g.Words[word] = &Word{Word: word}
  89. }
  90. return nil
  91. }