forked from terrisbecker/codenames-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame_instance.py
298 lines (271 loc) · 12.1 KB
/
game_instance.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import random as rd
import os
import sys
import numpy as np
import pandas as pd
from prettytable.prettytable import NONE
import spacy as sp
import prettytable as pt
import matplotlib.pyplot as plt
import streamlit as st
# from utilities import R, G, Y, B, N, DARK_GREY, LIGHT_CYAN, HEADER
R = "\033[1;31m" # RED
G = '\033[1;32m' # GREEN
Y = "\033[1;33m" # Yellow
B = "\033[1;34m" # Blue
N = "\033[0m" # Reset
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
HEADER = '\033[95m'
DARK_GREY = '\033[1;30m'
LIGHT_CYAN = '\033[1;36m'
@st.cache(allow_output_mutation=True)
class Codenames:
def __init__(self, players_spymaster=True, turn_limit=30, max_hint_giver=3, debug=False):
self.turn_limit = turn_limit
self.debug = debug
self.board = []
self.words = []
self.word_list = [i[0].lower() for i in pd.read_csv('data/words.txt').values.tolist()]
self.blue_words = []
self.red_words = []
self.neutral_words = []
self.black_word = []
self.turn = 'red'
self.turn_count = 0
self.players_spymaster = players_spymaster
self.game_over = False
self.loser = None
self.current_guess = None
self.current_guess_count = 0
self.max_hint_giver = max_hint_giver
self.model = sp.load('en_core_web_lg')
self.load_board()
def load_board(self, words=None):
self.similarity_matrix = pd.read_csv('data/similarity_matrix.csv', index_col=0).drop_duplicates()
if words is None:
words = rd.sample(self.word_list, 25)
else:
words = rd.sample(words, 25)
self.similarity_matrix = self.similarity_matrix.loc[:, words]
# self.color_matrix = pd.DataFrame(np.zeros((25, 25)), index=self.similarity_matrix.index, columns=self.similarity_matrix.columns)
self.words = words
self.past_hints = []
self.hint_words = self.similarity_matrix.index.tolist()
self.blue_words = rd.sample(words, 10)
self.red_words = rd.sample([w for w in words if w not in self.blue_words], 10)
self.neutral_words = rd.sample([w for w in words if w not in self.blue_words and w not in self.red_words], 4)
self.black_word = rd.sample([w for w in words if w not in self.blue_words and w not in self.red_words and w not in self.neutral_words], 1)[0]
self.board = np.array(words).reshape(5,5)
self.color_board = np.array(['red' if i in self.red_words else 'blue' if i in self.blue_words else 'neutral' if i in self.neutral_words else 'black' if i in self.black_word else None for i in words]).reshape(5,5)
self.past_hints = []
def remove_word(self, word):
self.words.remove(word)
if word in self.blue_words:
self.blue_words.remove(word)
elif word in self.red_words:
self.red_words.remove(word)
elif word in self.neutral_words:
self.neutral_words.remove(word)
elif word == self.black_word:
self.black_word = None
else:
print('word not in board')
self.board = np.array([word if word in self.words else ' ' for word in self.board.flatten()]).reshape(5,5)
self.color_board = np.array([self.get_color(word) + word + N if word in self.color_board else ' ' for word in self.color_board.flatten()]).reshape(5,5)
def get_color(self, word):
if word in self.blue_words:
return B
elif word in self.red_words:
return R
elif word in self.neutral_words:
return DARK_GREY
elif word == self.black_word:
return LIGHT_CYAN
else:
return N
def print_board(self, show_color=True):
tab = pt.PrettyTable()
tab.field_names = [' ', 'A', 'B', 'C', 'D', 'E']
board_str = ''
for i in range(5):
if show_color:
tab.add_row([i+1, *[self.get_color(word) + word + N for word in self.board[i]]])
else:
tab.add_row([i+1, *self.board[i]])
print(tab)
# return tab
def take_turn(self):
# determine who the computers are and who the players are and then make the appropriate moves for the comp and ask for moves for the player
pass
def end_game(self, loser, print_it=False):
if print_it:
print(f'{loser} loses!')
self.game_over = True
self.loser = loser
# here starts the main functions
def guess(self, word, color):
if word in self.board.flatten():
if word in self.blue_words and color == 'blue':
return True, None
elif word in self.red_words and color == 'red':
return True, None
elif word in self.neutral_words:
return False, 'neu'
elif word == self.black_word:
self.end_game(color)
return False, 'black'
else:
return False, 'blue' if color == 'red' else 'red'
else:
return False, 'not in board'
def guesser(self, guess_word, number, game_words=None):
"""
this function is used to guess the words based on the hint and the number of words.
the function returns a list of words that are guessed.
"""
if game_words is None:
game_words = list(self.board.flatten())
try:
self.similarity_vector = np.argsort([self.model(str(word)).similarity(self.model(guess_word)) for word in game_words])[::-1]
return [game_words[w] for w in self.similarity_vector[:number]]
except Exception as e:
print(f'Something went wrong \n{e}')
return game_words[0]
def hint_giver(self, color='red'):
"""
this function is used to give the hint to the guesser.
the function looks through hint_words.csv, eliminates illegal words, and then finds the ones that are most similar to the guesser's guess.
"""
# lets just return a random word for now
best_score = 0
best_words = []
color = R if color == 'red' else B
for row in self.similarity_matrix.iterrows():
if (row[0] in self.past_hints) or (row[0] in self.board.flatten()):
continue
score = 0
srow = row[1].sort_values(ascending=False)
for w in srow.index:
if self.get_color(w) != color:
break
score += 1
score = min(score, self.max_hint_giver)
if score > best_score:
best_score = score
best_words = [row[0]]
elif score == best_score:
best_words += [row[0]]
if len(best_words) > 1:
bad_score = []
for word in best_words:
assasin_sim = self.similarity_matrix.loc[word, self.black_word]
other_sim = self.similarity_matrix.loc[word, self.red_words if color == 'blue' else self.blue_words].max()
our_sim = self.similarity_matrix.loc[word, self.red_words if color == 'red' else self.blue_words].sort_values(ascending=False)
our_sim = our_sim.iloc[:min(len(self.blue_words), self.max_hint_giver)].max() # only our recent ones
bad_score.append((len(self.red_words if color == 'blue' else self.blue_words)**.5)*assasin_sim + other_sim - our_sim)
best_words = [best_words[np.argmin(bad_score)]]
return best_words, int(best_score)
def human_guesser(self, color, guesses=1, show_color=False):
guess_words = []
while guesses > 0:
print('', end='\r')
guess = input(f'Guess a word, you have {guesses} left to guess: ').lower()
print ("\033[A \033[A")
if guess not in self.board.flatten():
print('not on board')
guesses += 1
else:
go_on = self.evaluate_single_guess(guess, color)
if not go_on:
break
guesses -= 1
return guess_words
def human_hint_giver(self, color='red'):
# Give hint to the guesser
hint = input('Give hint: ').lower()
if hint in self.board.flatten():
print('you cannot hint at words on the table')
return self.human_hint_giver()
number = input('How many words do you want to hint at?: ')
if not number.isdigit():
print('please enter a number')
return self.human_hint_giver()
return hint, int(number)
def evaluate_single_guess(self, word, color):
print(f'The guess {HEADER + word + N} was...')
col = self.guess(word, color)
self.remove_word(word)
if col[1] == 'not on board':
raise Exception(f'illegal word made it to evaluate_single_guess {R + word + N}')
if col[0]:
print(G + 'CORRECT!' + N)
return True
else:
if col[1] == 'black':
print(LIGHT_CYAN + 'THE ASSASIN!!' + N)
else:
print(R + 'WRONG!' + N)
# print(f'{HEADER + word + N} was {B if col[1] == "blue" else R} {col[1] + N}')
print(f'{HEADER + word + N} was {B if col[1] == "blue" else R if col[1] == "red" else DARK_GREY} {col[1] + N}')
return False
def evaluate_multiple_guess(self, guess, color):
for word in guess:
go_on = self.evaluate_single_guess(word, color)
if not go_on:
break
def play_turn(self):
# this function is used to play a turn for the computer
# first we have to decide who the computer is and who the player is
# then we have to make the computer guess
# then we have to evaluate the guess
# then we have to make the player guess
# then we have to evaluate the guess
# then we have to repeat the process
# if the game is over, we have to end the game which is done in the end_game function
# if the game is not over, we have to play the next turn denoted by a True return value
print(f"It is now {R if self.turn == 'red' else B} {self.turn + N}'s turn")
print(f'There are ' + R + f'{len(self.red_words)} red ' + N + 'words and ' + B + f'{len(self.blue_words)} blue ' + N + 'words left')
self.print_board(show_color=True if self.debug else self.players_spymaster)
if self.players_spymaster:
hint = self.human_hint_giver(color=self.turn)
self.evaluate_multiple_guess(self.guesser(hint[0], hint[1]), self.turn)
else:
hint, number = self.hint_giver(color=self.turn)
print(f'{self.turn} is giving a hint of ' + UNDERLINE + BOLD + f'{hint[0]}, {number}' + N)
self.human_guesser(self.turn, guesses=number, show_color=True if self.debug else False)
self.check_end_condition()
if self.game_over:
print(f'{self.loser} loses!')
return False
self.turn_count += 1 if self.turn == 'blue' else 0
self.turn = 'blue' if self.turn == 'red' else 'red'
return True
def check_end_condition(self):
if len(self.red_words) == 0:
self.game_over = True
self.loser = 'blue'
elif len(self.blue_words) == 0:
self.game_over = True
self.loser = 'red'
elif self.turn_count == self.turn_limit:
self.game_over = True
self.loser = 'draw'
def play_game(self):
while not self.game_over:
self.play_turn()
if __name__ == '__main__':
game = Codenames(players_spymaster=True, debug=False)
game.load_board()
# print(game.board)
# print(game.color_board)
# game.print_board()
# print(game.guess('lion', 'red'))
# print(game.guesser('army', 2))
# print(game.hint_giver())
# print(game.human_hint_giver())
# game.human_guesser('red', 3)
# game.evaluate_guess(game.guesser('army', 2), 'red')
game.play_game()
# neautral words are red colores
# silance empty waring