-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
229 lines (180 loc) · 5.95 KB
/
app.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
import os
import json
from random import choice, shuffle
from string import ascii_lowercase
from uuid import uuid4
from flask import (
Flask,
jsonify,
redirect,
render_template,
request,
session,
)
from flask_cachebuster import CacheBuster
from game import CATEGORIES, get_categories_shortlist
from version import random_version
LOBBIES_DIR = os.path.join(os.path.dirname(__file__), 'lobbies')
if not os.path.isdir(LOBBIES_DIR):
os.mkdir(LOBBIES_DIR)
app = Flask(__name__)
app.secret_key = str(os.urandom(32))
CacheBuster(config={'extensions': ['.js', '.css']}).init_app(app)
def validate_lobby_code(code):
code = code.lower()
if (
isinstance(code, str) and
code in os.listdir(LOBBIES_DIR)
):
return code
def entry_filename_for_code(lobby_code):
return os.path.join(LOBBIES_DIR, lobby_code)
def state_filename_for_code(lobby_code):
return entry_filename_for_code(lobby_code) + '.json'
def load_state(lobby_code):
with open(state_filename_for_code(lobby_code), 'r') as rsf:
return json.load(rsf)
def save_state(lobby_code, state):
with open(state_filename_for_code(lobby_code), 'w') as wsf:
return json.dump(state, wsf)
def generate_lobby_code():
code = ''.join((choice(ascii_lowercase) for c in range(4)))
open(entry_filename_for_code(code), 'a').close()
return code
@app.route('/')
def index():
return render_template('index.html')
@app.route('/', methods=['POST'])
def dispatch():
code = request.form.get('lobby')
mode = request.form.get('mode')
if mode == 'join':
code = validate_lobby_code(code)
name = request.form.get('name')
if not (code and name):
return redirect('/')
else:
session['playing_lobby'] = code
session['name'] = (
name.replace('\n', '').replace('\r', '').replace('#', '')
)
session['player_uuid'] = str(uuid4())
state = load_state(code)
state['players'][session['player_uuid']] = {
'name': name,
'score': 0,
'turns': 0,
}
save_state(code, state)
return redirect('/play')
elif mode == 'start':
code = generate_lobby_code()
session['hosting_lobby'] = code
save_state(code, {'players': {}})
return redirect('/host')
@app.route('/host')
def host():
session_code = session.get('hosting_lobby')
if session_code:
return render_template('host.html', session_code=session_code)
else:
return redirect('/')
@app.route('/play')
def play():
return render_template('player.html')
@app.route('/play', methods=['POST'])
def log_entry():
entry = request.form.get('entry')
if not entry.strip():
return redirect('')
if not validate_lobby_code(session.get('playing_lobby')):
return redirect('/')
with open(
entry_filename_for_code(session.get('playing_lobby')), 'a',
) as lf:
lf.write('{}#{}#{}'.format(
session.get('name'),
session.get('player_uuid'),
entry.replace('\n', '').replace('\r', ''),
))
lf.write('\n')
return redirect('')
@app.route('/_categories', methods=['POST'])
def _categories():
state = load_state(session.get('hosting_lobby'))
if not len(state['players'].keys()) >= 2:
return 'Get at least two people to join the session first.', 400
winner = request.form.get('winner')
if winner and winner in state['players']:
state['players'][winner]['score'] += 1
judge = request.form.get('judge')
if judge and judge in state['players']:
state['players'][judge]['turns'] += 1
fewest_turns = min((
pl['turns'] for pl in state['players'].values()
))
player_id = choice([
uuid for uuid, p in state['players'].items()
if p['turns'] == fewest_turns
])
save_state(session.get('hosting_lobby'), state)
turn_set = {p['turns'] for p in state['players'].values()}
if len(turn_set) == 1:
turn, = turn_set
if turn == 0:
message = None
else:
message = (
'Round complete! The scores are:\n\n{}'
.format('\n'.join((
'{name}: {score}'.format(**p) for p in sorted(
state['players'].values(),
key=lambda pl: pl['score'], reverse=True
)
)))
)
else:
message = None
return jsonify({
'categories': get_categories_shortlist(),
'player': {
'uuid': player_id, 'name': state['players'][player_id]['name'],
},
'message': message,
})
@app.route('/_prompt', methods=['POST'])
def _prompt():
category_name = request.form.get('category')
category = CATEGORIES.get(category_name)
if not category:
return '', 400
# wipe out the existing submissions
session_code = validate_lobby_code(session.get('hosting_lobby'))
if session_code:
open(entry_filename_for_code(session_code), 'w').close()
else:
return '', 400
product = choice(category['releases'])
product['version'] = random_version()
product['category'] = category_name
if product['comments'] or category['generic_comments']:
product['comment'] = choice(
product['comments'] or category['generic_comments']
)
return product
@app.route('/_entries', methods=['POST'])
def _entries():
code = validate_lobby_code(session.get('hosting_lobby'))
if not code:
return '', 400
with open(entry_filename_for_code(code)) as ef:
entries = [{
'name': name, 'uuid': uuid, 'entry': entry,
} for name, uuid, entry in (
e.strip().split('#', 2)
for e in ef.readlines() if e.strip()
)]
shuffle(entries)
return jsonify({
'entries': entries,
})