-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwordle.py
219 lines (174 loc) · 6.85 KB
/
wordle.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import random
def loadWords():
answerSpace = []
allWords = []
# Load all possible solution words
with open("possiblewords.txt", "r", newline='') as wordFile:
for word in wordFile:
word = word.lower().strip()
if len(word) == 5 and word.isalpha():
answerSpace.append(word)
# Load all accepted words
with open("acceptedwords.txt", "r", newline='') as wordFile:
for word in wordFile:
word = word.lower().strip()
if len(word) == 5 and word.isalpha():
allWords.append(word)
return answerSpace, allWords
def pickWord(allWords, answerSpace, ignoreChars):
letterFrequency = {}
placementFrequency = [{}]*6
if len(answerSpace) <= 2:
return answerSpace[0]
#Build letter frequency, ignoring characters that we already know
for word in answerSpace:
ignoreCharsCopy = ignoreChars
placementIndex = 0
for letter in word:
if letter in ignoreCharsCopy:
ignoreCharsCopy = ignoreCharsCopy.replace(letter,'',1)
else:
if letter not in letterFrequency:
letterFrequency[letter] = 0
letterFrequency[letter] += 1
if letter not in placementFrequency[placementIndex]:
placementFrequency[placementIndex][letter] = 0
placementFrequency[placementIndex][letter] += 1
placementIndex += 1
bestWord = answerSpace[0]
maxFrequency = 0
maxPlacementScore = 0
# Score each word in full dictionary, ignoring letters we already know
for word in allWords:
currentFrequency = 0
picked = set()
ignoreCharsCopy = ignoreChars
for letter in word:
if letter in ignoreCharsCopy:
ignoreCharsCopy = ignoreCharsCopy.replace(letter,'',1)
else:
if letter in picked:
continue
picked.add(letter)
if letter in letterFrequency:
currentFrequency += letterFrequency[letter]
if currentFrequency > maxFrequency:
maxFrequency = currentFrequency
bestWord = word
placementScore = 0
for i in range(len(word)):
if word[i] in placementFrequency[i]:
placementScore += placementFrequency[i][word[i]]
maxPlacementScore = maxPlacementScore
elif currentFrequency == maxFrequency:
placementScore = 0
for i in range(len(word)):
if word[i] in placementFrequency[i]:
placementScore += placementFrequency[i][word[i]]
if placementScore > maxPlacementScore:
maxPlacementScore = placementScore
bestWord = word
return bestWord
# Filter remaining answer space based on last guess & guess results
# Also update characters to ignore if any new letters were identified as part of the solution
def filterWords(words, guessWord, guessResult, ignoreChars):
newIgnoreChars = ignoreChars
for i in range(len(guessResult)):
if guessResult[i] != 'x':
if guessWord[i] in ignoreChars:
ignoreChars = ignoreChars.replace(guessWord[i], '', 1)
else:
newIgnoreChars += guessWord[i]
return [word for word in words if matchesGuessResult(word, guessWord, guessResult)], newIgnoreChars
# Return True if word fits the same pattern as the guess & guess results
# Example input:
# Word: ROBOT
# GuessWord: STARS
# GuessResult: xyxyx
# Returns True
def matchesGuessResult(word, guessWord, guessResult):
for i in range(len(guessResult)):
if guessResult[i] == 'g' and word[i] != guessWord[i]:
return False
elif guessResult[i] == 'y':
if guessWord[i] == word[i]:
return False
elif guessWord[i] not in word:
return False
elif guessResult[i] == 'x':
if word[i] == guessWord[i]:
return False
wrongLetterInstancesGuess = findLetterIndexesInWord(guessWord, guessWord[i])
okCount = 0
for j in wrongLetterInstancesGuess:
if guessResult[j] != 'x':
okCount += 1
wrongLetterInstancesWord = findLetterIndexesInWord(word, guessWord[i])
if len(wrongLetterInstancesWord) > okCount:
return False
return True
def findLetterIndexesInWord(word, letter):
return [i for i, ltr in enumerate(word) if ltr == letter]
# Return guess results to automate the game
def evaluateGuessResults(correctWord, guess):
result = ""
for i in range(len(correctWord)):
if correctWord[i] == guess[i]:
result += 'g'
else:
if guess[i] in correctWord:
result += 'y'
else:
result += 'x'
return result
def play(ai=False, verbose=False, forceWord=''):
guessResults = ''
answerSpace, allWords = loadWords()
numGuesses = 0
correctWord = forceWord
ignoreChars = ''
if ai and forceWord == '':
correctWord = random.choice(answerSpace)
#print("Word is", correctWord)
while len(answerSpace) > 0:
if not ai or verbose:
print(len(answerSpace), "words remaining in dict.")
currentGuess = pickWord(allWords, answerSpace, ignoreChars)
if not ai or verbose:
print("Current guess:", currentGuess)
if not ai:
guessResults = input("Guess result: ")
else:
guessResults = evaluateGuessResults(correctWord, currentGuess)
if verbose:
print(guessResults)
numGuesses += 1
if guessResults == 'ggggg':
break
answerSpace, ignoreChars = filterWords(answerSpace, currentGuess, guessResults, ignoreChars)
if guessResults == 'ggggg':
#print("Guessed in", numGuesses, "guesses.")
pass
else:
print("Could not guess word:",correctWord)
return numGuesses
totalGuesses = 0
maxGuessCount = 0
numGames = 1
random.seed(1)
ai = False
if ai:
answerSpace, allWords = loadWords()
numGames = len(answerSpace)
for word in answerSpace:
currentGuessCount = play(True, False, word)
totalGuesses += currentGuessCount
if currentGuessCount > maxGuessCount:
maxGuessCount = currentGuessCount
else:
currentGuessCount = play()
totalGuesses += currentGuessCount
if currentGuessCount > maxGuessCount:
maxGuessCount = currentGuessCount
print("Avg guesses:",totalGuesses/numGames)
print("Worst case:",maxGuessCount,"guesses")