game.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type Game struct {
  7. Words map[string]*Word
  8. Length int
  9. }
  10. func NewGame() *Game {
  11. return &Game{
  12. Words: make(map[string]*Word),
  13. }
  14. }
  15. func (g Game) scoreWordsByCommonLetterLocations() {
  16. letterIdxScores := make(map[int]map[string]int)
  17. var lastWord string
  18. for _, word := range g.Words {
  19. word.Score = 0
  20. lastWord = word.Word
  21. }
  22. for idx := range lastWord {
  23. letterIdxScores[idx] = make(map[string]int)
  24. }
  25. for _, word := range g.Words {
  26. for idx, letter := range word.Word {
  27. letterIdxScores[idx][string(letter)]++
  28. }
  29. }
  30. for _, word := range g.Words {
  31. for idx, letter := range word.Word {
  32. word.Score += letterIdxScores[idx][string(letter)]
  33. }
  34. }
  35. return
  36. }
  37. func (g Game) FilterWords(guess string, score int) {
  38. for _, word := range g.Words {
  39. if !word.MatchesGuess(guess, score) {
  40. delete(g.Words, word.Word)
  41. }
  42. }
  43. }
  44. func (g Game) getSortedScores() []string {
  45. var sortedWordScores []string
  46. for _, word := range g.Words {
  47. sortedWordScores = append(sortedWordScores, word.Word)
  48. }
  49. debugPrint("Sorted Word Scores: %v\n", sortedWordScores)
  50. // sort words by score
  51. sort.Slice(sortedWordScores, func(i, j int) bool {
  52. if g.Words[sortedWordScores[i]].Score != g.Words[sortedWordScores[j]].Score {
  53. return g.Words[sortedWordScores[i]].Score > g.Words[sortedWordScores[j]].Score
  54. }
  55. // sort by word if scores are equal - this is for consistent answers for unit testing
  56. return g.Words[sortedWordScores[i]].Word < g.Words[sortedWordScores[j]].Word
  57. })
  58. return sortedWordScores
  59. }
  60. func (g Game) getBestGuess() string {
  61. return g.getSortedScores()[0]
  62. }
  63. func (g Game) printSortedScores() []string {
  64. sortedWordScores := g.getSortedScores()
  65. fmt.Println("\n>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
  66. fmt.Print("Words sorted by Score:\n")
  67. for _, word := range sortedWordScores {
  68. fmt.Printf("%s: %d\n", word, g.Words[word].Score)
  69. }
  70. fmt.Println("")
  71. return sortedWordScores
  72. }