-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmymain.py
More file actions
259 lines (213 loc) · 10.1 KB
/
mymain.py
File metadata and controls
259 lines (213 loc) · 10.1 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
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
import json
import requests
import random
import string
import secrets
import time
import re
import collections
try:
from urllib.parse import parse_qs, urlencode, urlparse
except ImportError:
from urlparse import parse_qs, urlparse
from urllib import urlencode
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class HangmanAPI(object):
def __init__(self, access_token=None, session=None, timeout=None):
self.hangman_url = self.determine_hangman_url()
self.access_token = access_token
self.session = session or requests.Session()
self.timeout = timeout
self.guessed_letters = []
full_dictionary_location = "words_250000_train.txt"
self.full_dictionary = self.build_dictionary(full_dictionary_location)
self.full_dictionary_common_letter_sorted = collections.Counter("".join(self.full_dictionary)).most_common()
self.current_dictionary = []
@staticmethod
def determine_hangman_url():
links = ['https://trexsim.com']
data = {link: 0 for link in links}
for link in links:
requests.get(link)
for i in range(10):
s = time.time()
requests.get(link)
data[link] = time.time() - s
link = sorted(data.items(), key=lambda x: x[1])[0][0]
link += '/trexsim/hangman'
return link
def guess(self, word): # word input example: "_ p p _ e "
###############################################
# Replace with your own "guess" function here #
###############################################
# clean the word so that we strip away the space characters
# replace "_" with "." as "." indicates any character in regular expressions
clean_word = word[::2].replace("_",".")
# find length of passed word
len_word = len(clean_word)
# import pdb; pdb.set_trace()
# grab current dictionary of possible words from self object, initialize new possible words dictionary to empty
current_dictionary = self.current_dictionary
new_dictionary = []
# iterate through all of the words in the old plausible dictionary
for dict_word in current_dictionary:
# continue if the word is not of the appropriate length
if len(dict_word) != len_word:
continue
# if dictionary word is a possible match then add it to the current dictionary
if re.match(clean_word,dict_word):
new_dictionary.append(dict_word)
# overwrite old possible words dictionary with updated version
self.current_dictionary = new_dictionary
# count occurrence of all characters in possible word matches
full_dict_string = "".join(new_dictionary)
c = collections.Counter(full_dict_string)
sorted_letter_count = c.most_common()
guess_letter = '!'
# return most frequently occurring letter in all possible words that hasn't been guessed yet
for letter,instance_count in sorted_letter_count:
if letter not in self.guessed_letters:
guess_letter = letter
break
# if no word matches in training dictionary, default back to ordering of full dictionary
if guess_letter == '!':
sorted_letter_count = self.full_dictionary_common_letter_sorted
for letter,instance_count in sorted_letter_count:
if letter not in self.guessed_letters:
guess_letter = letter
break
return guess_letter
##########################################################
# You'll likely not need to modify any of the code below #
##########################################################
def build_dictionary(self, dictionary_file_location):
text_file = open(dictionary_file_location,"r")
full_dictionary = text_file.read().splitlines()
text_file.close()
return full_dictionary
def start_game(self, practice=True, verbose=True):
# reset guessed letters to empty set and current plausible dictionary to the full dictionary
self.guessed_letters = []
self.current_dictionary = self.full_dictionary
response = self.request("/new_game", {"practice":practice})
if response.get('status')=="approved":
game_id = response.get('game_id')
word = response.get('word')
tries_remains = response.get('tries_remains')
if verbose:
print("Successfully start a new game! Game ID: {0}. # of tries remaining: {1}. Word: {2}.".format(game_id, tries_remains, word))
while tries_remains>0:
# get guessed letter from user code
guess_letter = self.guess(word)
# append guessed letter to guessed letters field in hangman object
self.guessed_letters.append(guess_letter)
if verbose:
print("Guessing letter: {0}".format(guess_letter))
try:
res = self.request("/guess_letter", {"request":"guess_letter", "game_id":game_id, "letter":guess_letter})
except HangmanAPIError:
print('HangmanAPIError exception caught on request.')
continue
except Exception as e:
print('Other exception caught on request.')
raise e
if verbose:
print("Sever response: {0}".format(res))
status = res.get('status')
tries_remains = res.get('tries_remains')
if status=="success":
if verbose:
print("Successfully finished game: {0}".format(game_id))
return True
elif status=="failed":
reason = res.get('reason', '# of tries exceeded!')
if verbose:
print("Failed game: {0}. Because of: {1}".format(game_id, reason))
return False
elif status=="ongoing":
word = res.get('word')
else:
if verbose:
print("Failed to start a new game")
return status=="success"
def my_status(self):
return self.request("/my_status", {})
def request(
self, path, args=None, post_args=None, method=None):
if args is None:
args = dict()
if post_args is not None:
method = "POST"
# Add `access_token` to post_args or args if it has not already been
# included.
if self.access_token:
# If post_args exists, we assume that args either does not exists
# or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
time.sleep(0.2)
num_retry, time_sleep = 50, 2
for it in range(num_retry):
try:
response = self.session.request(
method or "GET",
self.hangman_url + path,
timeout=self.timeout,
params=args,
data=post_args,
verify=False
)
break
except requests.HTTPError as e:
response = json.loads(e.read())
raise HangmanAPIError(response)
except requests.exceptions.SSLError as e:
if it + 1 == num_retry:
raise
time.sleep(time_sleep)
headers = response.headers
if 'json' in headers['content-type']:
result = response.json()
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise HangmanAPIError(response.json())
else:
raise HangmanAPIError('Maintype was not text, or querystring')
if result and isinstance(result, dict) and result.get("error"):
raise HangmanAPIError(result)
return result
class HangmanAPIError(Exception):
def __init__(self, result):
self.result = result
self.code = None
try:
self.type = result["error_code"]
except (KeyError, TypeError):
self.type = ""
try:
self.message = result["error_description"]
except (KeyError, TypeError):
try:
self.message = result["error"]["message"]
self.code = result["error"].get("code")
if not self.type:
self.type = result["error"].get("type", "")
except (KeyError, TypeError):
try:
self.message = result["error_msg"]
except (KeyError, TypeError):
self.message = result
Exception.__init__(self, self.message)
api = HangmanAPI(access_token="18965b3ab8184fc94104e4a7fb6c50", timeout=2000)
api.start_game(practice=1,verbose=True)
[total_practice_runs,total_recorded_runs,total_recorded_successes,total_practice_successes] = api.my_status() # Get my game stats: (# of tries, # of wins)
practice_success_rate = total_practice_successes / total_practice_runs
print('run %d practice games out of an allotted 100,000. practice success rate so far = %.3f' % (total_practice_runs, practice_success_rate))