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
|
#!/usr/bin/python
import tornado.ioloop
import tornado.web
import random
import string
import os
root_dir = os.path.dirname(os.path.realpath(__file__))
with open(root_dir + '/german-5.dic', encoding='utf-8') as f:
dictionary = [ word.lower() for word in f.read().split('\n') ]
class BaseHandler(tornado.web.RequestHandler):
def get_current_riddle(self):
return self.get_secure_cookie('riddle')
class CreateHandler(BaseHandler):
def get(self):
self.set_header('Access-Control-Allow-Origin','*')
self.set_secure_cookie('riddle', random.SystemRandom().choice(dictionary).lower())
for redirection in self.get_arguments('next'):
self.redirect(redirection)
class TrialHandler(BaseHandler):
def is_solved(self):
return self.solution == self.trial
def is_in_dictionary(self):
return self.trial in dictionary
def letter_is_green(self, index):
if index >= len(self.solution):
return False
return self.solution[index] == self.trial[index]
def letter_is_green_or_yellow(self, zip_list, index):
char = self.trial[index]
return [ c[0] for c in zip_list ].count(char) >= [ c[1] for c in zip_list ][0:index+1].count(char)
def get_colors(self):
zip_list = [ c for c in zip(
self.solution + ''.join([' ' for i in range(len(self.trial))]),
self.trial + ''.join([' ' for i in range(len(self.solution))])
) if c[0] != c[1] ]
return [
2 if self.letter_is_green(index)
else 1 if self.letter_is_green_or_yellow(zip_list, index)
else 0
for index in range(len(self.trial))
]
def get(self, trial):
self.set_header('Access-Control-Allow-Origin','*')
if not self.get_current_riddle():
self.redirect('/create?next={}'.format(self.request.uri))
return
self.solution = self.get_current_riddle().decode('utf-8')
self.trial = trial.lower()
report = dict()
report['is_solved'] = self.is_solved()
report['is_in_dictionary'] = self.is_in_dictionary()
report['solution'] = self.solution
report['trial'] = self.trial
report['colors'] = self.get_colors()
self.write(report)
class ReadmeHandler(BaseHandler):
def get(self):
self.set_header('Access-Control-Allow-Origin','*')
f = open('{}/README'.format(root_dir), 'rb')
self.write(f.read())
f.close()
def make_app():
return tornado.web.Application([
(r'/', ReadmeHandler),
(r'/create', CreateHandler),
(r'/try/(.+)', TrialHandler),
],
cookie_secret = ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(64))
)
if __name__ == "__main__":
app = make_app()
app.listen(8889, address='127.0.0.1')
tornado.ioloop.IOLoop.current().start()
|