-
Notifications
You must be signed in to change notification settings - Fork 4
/
SpyPartyDraft.py
499 lines (412 loc) · 15.3 KB
/
SpyPartyDraft.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
import datetime
import random
import time
import uuid
import boto3
from threading import Thread
import os
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
from draft.drafttype import DraftType
from room import Room
from draft.upload_draft_to_manager import Uploader
# !/usr/bin/env python
# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on available packages.
async_mode = None
if async_mode is None:
try:
import eventlet
async_mode = 'eventlet'
except ImportError(eventlet):
pass
if async_mode is None:
try:
from gevent import monkey
async_mode = 'gevent'
except ImportError(monkey):
pass
if async_mode is None:
async_mode = 'threading'
print('async_mode is ' + async_mode)
# monkey patching is necessary because this application uses a background
# thread
if async_mode == 'eventlet':
import eventlet
eventlet.monkey_patch()
elif async_mode == 'gevent':
from gevent import monkey
monkey.patch_all()
dynamo_db_table_name = os.environ['DYNAMO_DB_TABLE']
# dynamodb = boto3.resource('dynamodb')
# table = dynamodb.Table(dynamo_db_table_name)
table = None
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ['SECRET_KEY']
socketio = SocketIO(app, async_mode=async_mode)
thread = None
ROOM_LENGTH = 5
room_map = {}
draft_types = DraftType.get_draft_type('config/draft_types.json')
uploader = Uploader()
def generate_room_id():
return 'sp' + ''.join(random.choice('0123456789abcdef') for _ in range(ROOM_LENGTH))
def create_room(id_, draft_type_id):
room_map[id_] = Room(id_, broadcast_to_room, broadcast_to_spectator, draft_types[draft_type_id])
def broadcast_to_spectator(spectator_id, data):
emit('spectator_update', data, room=spectator_id)
def tell_clients_draft_has_started(room):
print 'dumping draft info'
emit('draft_start',
{
'map_pool': room.serializable_map_pool(),
'player_one': room.draft.player_one,
'player_two': room.draft.player_two,
'state': room.draft.state,
'room_id': room.id
}, room=room.id)
def background_thread():
print 'cleanup thread started'
while True:
time.sleep(300)
cleanable = [k for k, v in room_map.iteritems() if room_map[k].should_be_cleaned()]
for x in cleanable:
del room_map[x]
print "cleaned room {}".format(x)
# we probably want to close the room here...?
print "should really clean things up here"
@app.route('/')
def index():
global thread
if thread is None:
thread = Thread(target=background_thread)
thread.daemon = True
thread.start()
return render_template('index.html')
@socketio.on('my event', namespace='/test')
def test_message(message):
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my response',
{'data': message['data'], 'count': session['receive_count']})
@socketio.on('my broadcast event', namespace='/test')
def test_broadcast_message(message):
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my response',
{'data': message['data'], 'count': session['receive_count']},
broadcast=True)
@socketio.on('create', namespace='/test')
def create(message):
print "got create message"
print "username: " + message['data']
username = message['data'][:32]
id_ = generate_room_id()
create_room(id_, message['draft_type_id'])
room_map[id_].player_list.append(username)
room_map[id_].post_event({
'type': "join_room",
'player': username,
'msg': "{} has joined the room!".format(username)
})
join_room(id_)
emit('create_success',
{
'room_id': id_,
'draft_type': room_map[id_].draft_type.name
})
broadcast_to_room(id_, "{} has joined the room!".format(username))
broadcast_to_room(id_, "Players currently in room: {}".format(' and '.join(room_map[id_].player_list)))
def broadcast_to_room(room_id, msg):
print 'broadcasting: ' + msg
emit('room_broadcast',
{'msg': msg,
'room': room_id
},
room=room_id)
@socketio.on('join_draft', namespace='/test')
def join_draft(message):
room_to_join = message['room_id']
if room_to_join not in room_map:
emit('join_error',
{
'message': 'Room {} does not exist'.format(room_to_join)
})
return
room = room_map[room_to_join]
if len(room.player_list) >= 2:
emit('join_error',
{
'message': 'Room {} already has two players in it'.format(room.id)
})
return
room.touch()
join_room(room.id)
username = message['username'][:32]
room.player_list.append(username)
room.post_event({
'type': "join",
'player': username,
'msg': "{} has joined the room!".format(username)
})
emit('join_success',
{
'room_id': room.id,
'draft_type': room.draft_type.name
})
broadcast_to_room(room.id, "{} has joined the room!".format(username))
broadcast_to_room(room.id, "Players currently in room: {}".format(' and '.join(room.player_list)))
if len(room.player_list) == 2:
room.start_draft()
print "back from draft started"
tell_clients_draft_has_started(room)
@socketio.on('join', namespace='/test')
def join(message):
join_room(message['room'])
emit('my response',
{'data': 'In rooms: ' + ', '.join(rooms()),
'count': session['receive_count']})
@socketio.on('leave', namespace='/test')
def leave(message):
leave_room(message['room'])
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my response',
{'data': 'In rooms: ' + ', '.join(rooms()),
'count': session['receive_count']})
@socketio.on('close room', namespace='/test')
def close(message):
session['receive_count'] = session.get('receive_count', 0) + 1
emit('my response', {'data': 'Room ' + message['room'] + ' is closing.',
'count': session['receive_count']},
room=message['room'])
close_room(message['room'])
@socketio.on('coin_flip', namespace='/test')
def coin_flip(message):
print 'got coinflip {}'.format(message['choice'])
print message
room = room_map[message['room_id']]
room.touch()
user_flip = message['choice']
# room.post_event({
# 'type': 'coin_flip_choice',
# 'message': '{} has chosen {}'.format(message['username'], message['choice']),
# 'choice': message['choice']
# })
emit('coin_chosen', {
'player_one': room.draft.player_one,
'message': '{} has chosen {}'.format(message['username'], message['choice']),
'choice': message['choice']
}, room=room.id)
our_flip = random.choice(['heads', 'tails'])
if user_flip == our_flip:
winner = room.draft.player_two
else:
winner = room.draft.player_one
# appended to event payload
room.post_event({
'type': "coin_flip_winner",
# 'flip_coice': user_flip, #might want to add to payload.
# 'flip+result': our_flip, #don't want to mess with the payload just in case
'player': winner,
'msg': "{} has won the coin flip".format(winner)
})
room.draft.coin_flip_winner = winner
# emitted to socket
emit('flip_winner', {
'message': '{} has won the coin toss'.format(winner),
'flip_choice': user_flip,
'flip_result': our_flip,
'winner': winner
}, room=room.id)
@socketio.on('get_draft_types', namespace='/test')
def get_draft_types():
dts = []
for dt_id, dt in draft_types.items():
dts.append({'id': dt_id, 'name': dt.name, 'selected': dt.is_default_draft})
emit('draft_types_update', dts)
def ask_spy_order(room, msg):
data = {
'username': room.draft.coin_flip_loser(),
'message': msg
}
emit('select_spy_order', data, room=room.id)
def ask_pick_order(room, msg):
data = {
'username': room.draft.coin_flip_loser(),
'message': msg
}
emit('select_pick_order', data, room=room.id)
def persist_draft(room):
print "Uploading..."
uploader.upload_room(room)
print "Maybe uploaded?"
def dump_draft(room):
response_type = 'draft_info'
if room.draft.draft_complete():
# set draft over if it's over
response_type = 'draft_over'
persist_draft(room)
room.touch()
emit(response_type, room.serialize(), room=room.id)
@socketio.on('second_option_pick', namespace='/test')
def second_option_pick(message):
# choice was made by the coin-flip-loser
room = room_map[message['room_id']]
choice = message['choice']
if choice == 'pickfirst':
room.post_event({
'type': "pick_first",
'player': room.draft.coin_flip_loser(),
'msg': "{} has opted to pick map first".format(room.draft.coin_flip_loser())
})
room.draft.start_player = room.draft.coin_flip_loser()
else:
room.post_event({
'type': "pick_second",
'player': room.draft.coin_flip_loser(),
'msg': "{} has opted to pick map second".format(room.draft.coin_flip_loser())
})
room.draft.start_player = room.draft.coin_flip_winner
room.draft.start_draft()
dump_draft(room)
@socketio.on('second_option_spy', namespace='/test')
def second_option_spy(message):
room = room_map[message['room_id']]
choice = message['choice']
if choice == 'spyfirst':
room.post_event({
'type': "spy_first",
'player': room.draft.coin_flip_loser(),
'msg': "{} has opted to play spy first".format(room.draft.coin_flip_loser())
})
room.draft.first_spy = room.draft.coin_flip_loser()
else:
room.post_event({
'type': "spy_second",
'player': room.draft.coin_flip_loser(),
'msg': "{} has opted to play spy_second".format(room.draft.coin_flip_loser())
})
room.draft.first_spy = room.draft.coin_flip_winner
room.draft.start_draft()
dump_draft(room)
@socketio.on('first_option_form', namespace='/test')
def first_option_form(message):
choice = message['choice']
room = room_map[message['room_id']]
room.touch()
print "got choice {}".format(choice)
if choice == "pickfirst":
room.draft.start_player = room.draft.coin_flip_winner
room.post_event({
'type': "pick_first",
'player': room.draft.coin_flip_winner,
'msg': "{} has opted to pick map first".format(room.draft.coin_flip_winner)
})
ask_spy_order(room, "You opponent has opted to pick map first")
elif choice == "picksecond":
room.draft.start_player = room.draft.coin_flip_loser()
room.post_event({
'type': "pick_second",
'player': room.draft.coin_flip_winner,
'msg': "{} has opted to pick second".format(room.draft.coin_flip_winner)
})
ask_spy_order(room, "Your opponent has opted to pick map second")
elif choice == "spyfirst":
room.draft.first_spy = room.draft.coin_flip_winner
room.post_event({
'type': "spy_first",
'player': room.draft.coin_flip_winner,
'msg': "{} has opted to spy first".format(room.draft.coin_flip_winner)
})
ask_pick_order(room, "Your opponent has opted to play spy first")
elif choice == "spysecond":
room.draft.first_spy = room.draft.coin_flip_loser()
room.post_event({
'type': "spy_second",
'player': room.draft.coin_flip_winner,
'msg': "{} has opted to spy second".format(room.draft.coin_flip_winner)
})
ask_pick_order(room, "Your opponent has opted to play spy second")
elif choice == "defer":
# we're going to pretend the other player won the flip, but
# don't let them defer
room.post_event("{} has opted to defer".format(room.draft.coin_flip_winner))
room.draft.coin_flip_winner = room.draft.coin_flip_loser()
emit('winner_deferred', {
'room_id': room.id,
'picker': room.draft.coin_flip_winner
}, room=room.id)
@socketio.on('disconnect_request', namespace='/test')
def disconnect_request(req):
print 'disconnecting'
disconnect()
@socketio.on('draft_map', namespace='/test')
def draft_map(message):
room = room_map[message['room_id']]
chosen_map = None
chosen_map_name = "nothing"
if message['choice'] != 'nothing':
chosen_map = [x for x in room.draft.map_pool if x.slug == message['choice']][0]
chosen_map_name = chosen_map.name
if room.draft.state.startswith('PICK') and not chosen_map.slug.endswith('k2'):
chosen_map_name = chosen_map.map_mode_name()
if room.draft.is_banning():
room.post_event({
'type': "map_banned",
'map': chosen_map.as_map() if chosen_map else None,
'player': room.draft.current_player,
'msg': "{} has banned {}".format(room.draft.current_player, chosen_map_name)
})
elif room.draft.is_restricting():
room.post_event({
'type': "map_restricted",
'map': chosen_map.as_map() if chosen_map else None,
'player': room.draft.current_player,
'msg': "{} has restricted {}".format(room.draft.current_player, chosen_map_name)
})
else:
room.post_event({
'type': "map_picked",
'map': chosen_map.as_map(),
'player': room.draft.current_player,
'is_doubled': room.draft.is_double_pick(),
'msg': "{} has picked {} {}".format(room.draft.current_player, chosen_map_name, " (Doubled) " if room.draft.is_double_pick() else "")
})
room.draft.mark_map(chosen_map)
dump_draft(room)
@socketio.on('connect', namespace='/test')
def test_connect():
emit('my response', {'data': 'Connected', 'count': 0})
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected', request.sid)
@socketio.on('spectate_draft', namespace='/test')
def spectate_draft(message):
room_to_join = message['room_id']
if room_to_join not in room_map:
print "'{}' doesn't exist as a room".format(room_to_join)
emit('spectate_error',
{
'message': 'Room {} does not exist'.format(room_to_join)
})
return
room = room_map[room_to_join]
room.spectator_list.append(request.sid)
emit('spectate_join_success', {
'room_id': room_to_join,
'sid': request.sid
})
broadcast_to_spectator(request.sid, room.get_spectator_data())
@socketio.on('chat_message', namespace='/test')
def chat_message(message):
room = room_map[message['room_id']]
text = message['chat_text'][:128]
print 'got chat message ' + text
data = {
'room_id': room.id,
'talker': message['username'],
'text': text
}
emit('chat_event', data, room=room.id)
if __name__ == '__main__':
socketio.run(app)