-
Notifications
You must be signed in to change notification settings - Fork 0
/
emo.py
252 lines (192 loc) · 11 KB
/
emo.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
from tornado import web, websocket, ioloop, httpclient
import random, string, json
#Let us know we've restarted:
print('Restarted!')
def id_generator(size=6, chars=string.ascii_uppercase + string.digits): #Generates a random ID
return ''.join(random.choice(chars) for _ in range(size))
#Food Categories:
foodtypes = [{"n":"American","id":"american"},{"n":"Asian","id":"asian"},{"n":"French","id":"french"},{"n":"Indian","id":"indian"},{"n":"Italian","id":"italian"},{"n":"Mexican","id":"mexican"}]
foodlist = ['american', 'asian', 'french', 'indian', 'italian', 'mexican']
#Games Data:
games = {}
class IndexHandler(web.RequestHandler):
def get(self):
self.render('views/home.html', title="Emo Ice Cream Deluxe")
class PlayHandler(web.RequestHandler):
def get(self):
username = self.get_cookie("username","Guest")
self.render('views/play.html', title = "Pick Category", foods = foodtypes, username = username )
class GameHandler(web.RequestHandler):
def get(self):
cat = self.get_argument('c', None, True)
if cat == None or cat not in foodlist:
self.write('Oops! Invalid Category')
self.finish()
return
if cat not in games:
client = httpclient.HTTPClient()
data = client.fetch('https://api.pearson.com/kitchen-manager/v1/recipes?limit=100&cuisine='+cat)
print(data.body)
myjson = json.loads(data.body.decode())
print('myjson',myjson)
games[cat] = {"rooms":[], "recipes": myjson['results']}
print(games)
username = self.get_cookie("username","Guest")
self.render('views/game.html', title = "Play Game", cid = cat, username = username)
class SocketHandler(websocket.WebSocketHandler):
def makeRound(self):
details=self.get_argument("c") #Get Card ID
rec = games[details]['recipes']
print('rec!',rec, len(rec))
print(games)
trep = random.randrange(0, len(rec) - 1)
totaling = []
totaling.extend(rec[trep]['ingredients'])
ing2 = rec[random.randint(0, len(rec) - 1)]['ingredients']
#ing3 = rec[random.randint(0, len(rec) - 1)]['ingredients']
for i in ing2:
if i not in totaling:
totaling.append(i)
random.shuffle(totaling)
#ToDo: Extract only needed info out of recipe
return {'recipe':rec[trep], 'inglist':totaling}
def open(self):
details=self.get_argument("c") #Get Card ID
print("open",details)
joined = False
i = 0
for game in games[details]["rooms"]:
if "player1" not in game['players']:
print('here 1')
game['players']["player1"] = {"socket": self, "score": 0, "right": [], "wrong": []}
self.write_message('{"event":"youjoin", "data":{"playernum": 1, "gamenum": '+str(i)+'}}')
joined = True
elif "player2" not in game['players']:
print('here 2')
game['players']["player2"] = {"socket": self, "score": 0, "right": [], "wrong": []}
self.write_message('{"event":"youjoin", "data":{"playernum": 2, "gamenum": '+str(i)+'}}')
joined = True
else:
print('here 3')
i = i + 1
if joined:
break
print(games[details]["rooms"])
if joined == False or i == 0: #Create the first game or a new game.
print('here 4')
games[details]["rooms"].append({"players":{"player1":{"socket": self, "score": 0, "right":[], "wrong": []}}, "finished":[]})
self.write_message('{"event":"youjoin", "data":{"playernum": 1, "gamenum": '+str(i)+'}}')
def on_message(self, message):
print('GOT MESSAGE', message)
details=self.get_argument("c")
msgjson = json.loads(message)
if msgjson['event'] == 'userinfo':
playerinfo = games[details]['rooms'][msgjson['gamenum']]['players']["player"+str(msgjson['playernum'])]
playerinfo['username'] = msgjson['data']['username']
game = games[details]['rooms'][msgjson['gamenum']]
if msgjson['playernum'] == 1:
#Start Game
if "player2" in game['players']:
oppinfo = game['players']["player2"]
else:
return
else:
if "player1" in game['players']:
oppinfo = game['players']["player1"]
else:
return
self.write_message('{"event":"oppinfo", "data":{"username": "'+oppinfo['username']+'" }}')
oppinfo['socket'].write_message('{"event":"oppinfo", "data":{"username": "'+playerinfo['username']+'" }}')
print('Sent!')
round = self.makeRound()
game['currentround'] = round
self.write_message('{"event":"startgame", "data" : {"roundnum": 0, "set": '+json.dumps(round)+'}}')
oppinfo['socket'].write_message('{"event":"startgame", "data" : {"roundnum": 0, "set": '+json.dumps(round)+'}}')
elif msgjson['event'] == 'sendfalse':
game = games[details]['rooms'][msgjson['gamenum']]
me = game['players']['player'+str(msgjson['playernum'])]
print(msgjson['text'], game['currentround']['recipe']['ingredients'])
if msgjson['text'] not in game['currentround']['recipe']['ingredients']:
print('right!')
me['score'] += 5
me['right'].append(msgjson['text'])
self.write_message('{"event":"youanswer", "correct":true, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
if msgjson['playernum'] == 1:
game['players']['player2']['socket'].write_message('{"event":"oppanswer", "correct":true, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
else:
game['players']['player1']['socket'].write_message('{"event":"oppanswer", "correct":true, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
else:
print('wrong')
me['score'] -= 5
me['wrong'].append(msgjson['text'])
self.write_message('{"event":"youanswer", "correct":false, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
if msgjson['playernum'] == 1:
game['players']['player2']['socket'].write_message('{"event":"oppanswer", "correct":false, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
else:
game['players']['player1']['socket'].write_message('{"event":"oppanswer", "correct":false, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
elif msgjson['event'] == 'sendtrue':
game = games[details]['rooms'][msgjson['gamenum']]
me = game['players']['player'+str(msgjson['playernum'])]
print(msgjson['text'], game['currentround']['recipe']['ingredients'])
if msgjson['text'] in game['currentround']['recipe']['ingredients']:
print('right!')
me['score'] += 5
me['right'].append(msgjson['text'])
self.write_message('{"event":"youanswer", "correct":true, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
if msgjson['playernum'] == 1:
game['players']['player2']['socket'].write_message('{"event":"oppanswer", "correct":true, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
else:
game['players']['player1']['socket'].write_message('{"event":"oppanswer", "correct":true, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
else:
print('wrong')
me['score'] -= 5
me['wrong'].append(msgjson['text'])
self.write_message('{"event":"youanswer", "correct":false, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
if msgjson['playernum'] == 1:
game['players']['player2']['socket'].write_message('{"event":"oppanswer", "correct":false, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
else:
game['players']['player1']['socket'].write_message('{"event":"oppanswer", "correct":false, "score":'+str(me['score'])+', "text": "'+msgjson['text']+'", "num":"'+str(msgjson['num'])+'"}')
elif msgjson['event'] == 'vardump':
print(games)
elif msgjson['event'] == 'signalendround':
players = games[details]['rooms'][msgjson['gamenum']]['players']
game = games[details]['rooms'][msgjson['gamenum']]
#Start new round
round = self.makeRound()
game['currentround'] = round
finished = []
if msgjson['roundnum'] < 4:
players['player1']['socket'].write_message('{"event":"startgame", "data" : {"roundnum": '+str(msgjson['roundnum']+ 1 )+', "set": '+json.dumps(round)+'}}')
players['player2']['socket'].write_message('{"event":"startgame", "data" : {"roundnum": '+str(msgjson['roundnum']+ 1 )+', "set": '+json.dumps(round)+'}}')
else:
players['player1']['socket'].write_message('{"event":"finishgame"}')
players['player2']['socket'].write_message('{"event":"finishgame"}')
def on_close(self):
details=self.get_argument("c")
for game in games[details]['rooms']:
if 'player1' in game['players']:
if game['players']['player1']['socket'] == self:
print('player1 left')
del game['players']['player1']
if 'player2' in game['players']:
game['players']['player2']['socket'].write_message('{event:"oppleft"}')
pass
if 'player2' in game['players']:
if game['players']['player2']['socket'] == self:
print('player2 left')
del game['players']['player2']
if 'player1' in game['players']:
game['players']['player1']['socket'].write_message('{"event":"oppleft"}')
pass
print("WebSocket closed")
application = web.Application([
(r"/", IndexHandler),
(r'/public/(.*)', web.StaticFileHandler, {'path': "public"}),
(r'/play', PlayHandler),
(r'/game', GameHandler),
(r'/ws/([^/]+)', SocketHandler),
(r'/ws', SocketHandler)
], debug=True)
if __name__ == "__main__":
application.listen(9008)
ioloop.IOLoop.instance().start()