Skip to content

Commit

Permalink
Refactored code
Browse files Browse the repository at this point in the history
  • Loading branch information
mathranger101 committed Apr 14, 2016
1 parent c94024e commit c30b5cd
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 49 deletions.
49 changes: 26 additions & 23 deletions SpyPartyDraft.py
Expand Up @@ -8,13 +8,15 @@
if async_mode is None:
try:
import eventlet

async_mode = 'eventlet'
except ImportError:
pass

if async_mode is None:
try:
from gevent import monkey

async_mode = 'gevent'
except ImportError:
pass
Expand All @@ -28,26 +30,28 @@
# thread
if async_mode == 'eventlet':
import eventlet

eventlet.monkey_patch()
elif async_mode == 'gevent':
from gevent import monkey

monkey.patch_all()

import time
import random
import datetime
import random
import time
import uuid
from threading import Thread

from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
from room import Room
from draft.draft_type import Draft_type

import boto3
from draft.drafttype import DraftType
from room import Room

#dynamodb = boto3.resource('dynamodb')
#table = dynamodb.Table('spypartydraft_test')
# dynamodb = boto3.resource('dynamodb')
# table = dynamodb.Table('spypartydraft_test')
table = None

app = Flask(__name__)
Expand All @@ -56,19 +60,18 @@
thread = None
dynamo_db_table_name = "spypartydraft_test"


ROOM_LENGTH = 5

room_map = {}
draft_types = Draft_type.get_draft_type('config/draft_types.json')
draft_types = DraftType.get_draft_type('config/draft_types.json')


def generate_room_id():
return 'sp' + ''.join(random.choice('0123456789abcdef') for i 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 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):
Expand Down Expand Up @@ -129,26 +132,26 @@ 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("{} has joined the room!".format(username))
join_room(id)
id_ = generate_room_id()
create_room(id_, message['draft_type_id'])
room_map[id_].player_list.append(username)
room_map[id_].post_event("{} has joined the room!".format(username))
join_room(id_)
emit('create_success',
{
'room_id': id,
'draft_type' : room_map[id].draft_type.name
'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)))
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)


Expand Down Expand Up @@ -239,7 +242,7 @@ def coin_flip(message):
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})
dts.append({'id': dt_id, 'name': dt.name, 'selected': dt.is_default_draft})

emit('draft_types_update', dts)

Expand Down Expand Up @@ -352,7 +355,7 @@ def first_option_form(message):


@socketio.on('disconnect_request', namespace='/test')
def disconnect_request(message):
def disconnect_request():
print 'disconnecting'
disconnect()

Expand Down
15 changes: 7 additions & 8 deletions draft/draft.py
Expand Up @@ -87,18 +87,18 @@ def _advance_state(self):
or self.state == STATE_PICKING and self._picking_complete()):
self.state = NEXT_STATE[self.state]

def mark_map(self, map):
if map is None:
def mark_map(self, map_):
if map_ is None:
self.banned_maps.append("Nothing")
elif self.state.endswith("BANNING"):
self.banned_maps.append(map.name)
self.map_pool.remove(map)
self.banned_maps.append(map_.name)
self.map_pool.remove(map_)
else:
map_name = map.map_mode_name()
map_name = map_.map_mode_name()
if self.draft_type.multi_phase and len(self.picked_maps) < 2:
map_name = "*DOUBLED* " + map_name
self.picked_maps.append(map_name)
for x in [x for x in self.map_pool if x.family == map.family]:
for x in [x for x in self.map_pool if x.family == map_.family]:
self.map_pool.remove(x)
if self.draft_type.multi_phase:
self._multi_phase_advance_state()
Expand Down Expand Up @@ -154,5 +154,4 @@ def serializable_picks(self):
def draft_complete(self):
return self.state == STATE_DRAFT_COMPLETE

ordinal = lambda self, n: "%d%s" % (n, "tsnrhtdd"[(n / 10 % 10 != 1)*(n % 10 < 4)*n % 10 :: 4])

ordinal = lambda self, n: "%d%s" % (n, "tsnrhtdd"[(n / 10 % 10 != 1) * (n % 10 < 4) * n % 10:: 4])
5 changes: 3 additions & 2 deletions draft/draft_type.py → draft/drafttype.py
Expand Up @@ -3,7 +3,7 @@
from map import Map


class Draft_type:
class DraftType:
def __init__(self, name, nr_bans, nr_picks, map_pool_key, multi_phase):
self.name = name
self.nr_bans = nr_bans
Expand All @@ -18,7 +18,8 @@ def get_draft_type(file_name):
with open(file_name) as f:
data = json.load(f)
for dt in data["draft_types"]:
draft_types[dt['id']] = Draft_type(dt['name'], dt['nr_bans'], dt['nr_picks'], dt['map_pool'], dt['multi_phase'])
draft_types[dt['id']] = DraftType(dt['name'], dt['nr_bans'], dt['nr_picks'], dt['map_pool'],
dt['multi_phase'])
draft_types[data["default_draft"]].is_default_draft = 1
return draft_types

Expand Down
2 changes: 0 additions & 2 deletions draft/map.py
Expand Up @@ -26,5 +26,3 @@ def generate_map_pool(file_name, tourney):
data = json.load(f)
tourney_json = data[tourney]
return [Map(x['name'], x['slug'], x['family']) for x in tourney_json]


6 changes: 3 additions & 3 deletions draft/player.py
Expand Up @@ -4,10 +4,10 @@


class Player:
def __init__(self, id, name):
self.id = id
def __init__(self, id_, name):
self.id = id_
self.name = name
self.key = ''.join(random.choice('0123456789abcdef') for i in range(KEY_LENGTH))

def __repr__(self):
return '{} ({})'.format(self.name, self.key)
return '{} ({})'.format(self.name, self.key)
1 change: 1 addition & 0 deletions requirements.txt
@@ -1,3 +1,4 @@
gevent
boto3==1.2.3
botocore==1.3.15
docutils==0.12
Expand Down
14 changes: 6 additions & 8 deletions room.py
@@ -1,16 +1,15 @@
from draft.draft import Draft
from draft.map import Map
from draft.draft_type import Draft_type
import copy
import datetime

# TOOD: don't keep this hardcoded
from draft.draft import Draft

# TODO: don't keep this hardcoded
TOURNEY = "scl_season_1"


class Room:
def __init__(self, id, server, spectator_broadcast, draft_type):
self.id = id
def __init__(self, id_, server, spectator_broadcast, draft_type):
self.id = id_
self.player_list = []
self.spectator_list = []
self.draft = None
Expand Down Expand Up @@ -85,6 +84,5 @@ def serialize(self):
'first_spy': self.draft.first_spy,
'state': self.draft.state,
'user_readable_state': self.draft.user_readable_state(),
'draft_type' : self.draft_type.name
'draft_type': self.draft_type.name
}

5 changes: 3 additions & 2 deletions templates/index.html
Expand Up @@ -23,7 +23,7 @@ <h1>SpyParty Draft Tool <small>BETA version 0.0.10</small></h1>
<h3>Create a new Draft Room</h3>
<form id="create" method="POST" action='#' class="form-inline">
<input type="text" name="username" maxlength="32" id="username" placeholder="Username" class="form-control"/>
<select name="draft_type" id="draft_type" class="form-control" />
<select name="draft_type" id="draft_type" class="form-control"></select>
<input type="submit" id="create_button" value="Create new Draft Room" class="btn btn-primary" />
<div id="create_error"></div>
</form>
Expand Down Expand Up @@ -93,7 +93,8 @@ <h2>Room Info:</h2>
<h3 id="first_option_header">You've won the coin flip!</h3>
<form id="first_option_form" method="POST" action="#">
<input type="radio" name="choice" value="pickfirst" id="first_pickfirst" /><label class="control-label" for="first_pickfirst">Pick First</label><br />
<input type="radio" name="choice" value="picksecond"id="first_picksecond" /><label class="control-label" for="first_picksecond">Pick Second</label><br />
<input type="radio" name="choice" value="picksecond" id="first_picksecond"/><label
class="control-label" for="first_picksecond">Pick Second</label><br/>
<input type="radio" name="choice" value="spyfirst" id="first_spyfirst" /><label class="control-label" for="first_spyfirst">Spy First</label><br />
<input type="radio" name="choice" value="spysecond" id="first_spysecond" /><label class="control-label" for="first_spysecond">Spy Second</label><br />
<div id="first_defer_radio"><input type="radio" name="choice" value="defer" id="first_defer" /><label class="control-label" for="first_defer">Defer Option to Other Player</label></div><br />
Expand Down
2 changes: 1 addition & 1 deletion wsgi.py
Expand Up @@ -8,4 +8,4 @@
from SpyPartyDraft import app

if __name__ == '__main__':
app.run()
app.run()

0 comments on commit c30b5cd

Please sign in to comment.