-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.py
More file actions
43 lines (41 loc) · 2.46 KB
/
game.py
File metadata and controls
43 lines (41 loc) · 2.46 KB
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
# A Game is an object that contains a list of all the possible words for each turn of a game of Wordle.
# The game contains an id that is given when initialized and a method called 'guess' that gives the next guess.
class Game():
def __init__(self, id):
self.id = id
with open("words.txt", "r") as file:
self.words_list = [line.strip() for line in file]
# The guess method takes in two parameters. word - the previous word used as a guess. result - the number array
# that is the result of the previous guess as returned by the server.
def guess(self, word, result):
# If there have been no guesses, the game starts with the mathematically best starting Wordle word 'crane'
# as described in this video by 3Blue1Brown https://www.youtube.com/watch?v=v68zYyaEmEA
if ((word == 's') and (len(self.words_list) == 15918)):
return "crane"
# Checks the word and result both have 5 elements
if (len(word) != 5 | len(result) != 5):
print('Guess must be 5 characters.')
raise Exception
# Loops through each result and filters the global list variable of this game.
index = 0
for value in result:
letter = word[index]
# Letter does not appear in the secret word - remove all with the letter
if value == 0 and word.count(letter) == 1:
self.words_list = [w for w in self.words_list if letter not in w]
# If there are duplicates, remove only the words where the letter is in the specific position
elif value == 0:
self.words_list = [w for w in self.words_list if w[index] != letter]
# Letter appears in the secret word, but not in this position - remove all without the letter plus all with the letter
# in the specific position
elif value == 1:
self.words_list = [w for w in self.words_list if letter in w and w[index] != letter]
# Letter appears in the secret word in this position - remove all without the letter in that specific position
elif value == 2:
self.words_list = [w for w in self.words_list if w[index] == letter]
else:
print('Unexpected value in response string.')
raise Exception
index += 1
# Just returns the first word in the filtered list
return self.words_list[0]