/
server.py
394 lines (308 loc) · 12.6 KB
/
server.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
from jinja2 import StrictUndefined
from flask import (Flask, render_template, redirect, request, flash,
session, jsonify, url_for, g)
from flask_debugtoolbar import DebugToolbarExtension
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from model import User, Game, AbstractPlayer, HumanPlayer, AIPlayer, BidHistory
from model import db, connect_to_db
from game_play import *
from bidding import get_total_dice
app = Flask(__name__)
# app.config['JSON_SORT_KEYS'] = False
# Required to use Flask sessions and the debug toolbar
app.secret_key = "ABC"
# Normally, if you use an undefined variable in Jinja2, it fails
# silently. This is horrible. Fix this so that, instead, it raises an
# error.
app.jinja_env.undefined = StrictUndefined
@app.route('/')
def index():
"""Homepage."""
return render_template("homepage.html")
@app.route('/register')
def register_form():
"""Prompts user to register"""
return render_template("register.html")
@app.route('/instructions')
def instructions():
"""Provides the user instructions on how to play"""
return render_template("instructions.html")
@app.route('/login')
def login():
"""Prompt user to log in"""
return render_template("login.html")
@app.route('/logout')
def logout():
"""Logs a user out"""
del session['username']
flash("You have successfully logged out!")
return redirect("/")
@app.route('/signin', methods=['POST'])
def signin():
"""Sign user in"""
username = request.form.get('username') # use email as username
password = request.form.get('password')
user = User.query.filter(User.username == username).first()
if user:
if user.password == password:
session['username'] = username
flash("You have successfully logged in!")
return redirect('/')
else:
flash("That was not the correct password, please try again.")
return redirect('/login')
else:
flash("No one is registered at this email, please create a new account.")
return redirect('/register')
@app.route('/signup', methods=['POST'])
def signup():
"""Sign up new user"""
username = request.form.get('username')
password = request.form.get('password')
name = request.form.get('name')
dob = request.form.get('dob')
user = User.query.filter(User.username == username).first()
#Check if username already exists, if so, redirect to signup. Else, register!
if user:
flash("You already have an account associated with that email. Please log in.")
return redirect('/login')
else:
session['username'] = username
new_user = User(username=username,
password=password,
name=name,
date_of_birth=dob)
db.session.add(new_user)
db.session.commit()
flash("Congrats, " + name + ", you are now registered!")
return redirect('/')
@app.route('/creategame')
def create_game():
"""Create a New Liar's Dice Game - prompt user for options"""
return render_template("create_game.html")
@app.route('/game', methods=['POST'])
def setup_game():
"""Setup the liar's dice game and players, and render the game page."""
num_players = int(request.form.get("num-players"))
difficulty = request.form.get("difficulty")
username = session['username'] # if none, don't allow saving...
game = create_new_game(num_players, difficulty, username)
url = '/game/{id}'.format(id=game.id)
return redirect(url)
@app.route('/game/<game_id>')
def play_game(game_id):
"""Page for game play."""
game = Game.query.filter(Game.id == game_id).first()
players = get_active_players_in_game(game.id)
# if this is the first time the page ever loads, roll dice
if players[0].current_die_roll is None and players[0].die_count == 5:
roll_player_dice(players)
total_dice = get_total_dice(players)
current_turn_player = get_current_turn_player(game)
#pass current bids into table on game page...
bids = (BidHistory.query
.filter(BidHistory.game_id == game_id)
.order_by(BidHistory.id)
.all())
return render_template("play_game.html",
game=game,
players=players,
total_dice=total_dice,
bids=bids,
current_turn_name=current_turn_player.name)
@app.route('/game_over/<game_id>')
def game_over(game_id):
"""Display end game to user"""
game = Game.query.filter(Game.id == game_id).first()
human_player = AbstractPlayer.query.filter(AbstractPlayer.game_id == game_id,
AbstractPlayer.position == 1).first()
return render_template("game_over.html", game=game, human_player=human_player)
#AJAX routes
@app.route('/loadgames.json')
def load_games():
"""Get list of players by game id, and roll dice for all players."""
username = session['username']
humans = User.query.filter(User.username == username).first().humans
game_ids = []
for human in humans:
if human.die_count > 0 and not human.game.is_finished:
game_ids.append(human.game_id)
game_ids.sort()
if len(game_ids) == 0:
return jsonify({})
results = {'games': game_ids}
return jsonify(results)
@app.route('/compturn.json', methods=['POST'])
def comp_bidding():
"""Start the bidding for a computer"""
#if human, show form on front end and get bid information, if computer, calc
#bid odds and determine resulting bid
game_id = int(request.form.get('game_id'))
game = Game.query.filter(Game.id == game_id).first()
players = get_players_in_game(game_id)
player = (AbstractPlayer
.query
.filter(AbstractPlayer.game_id == game_id,
AbstractPlayer.position == game.turn_marker)
.first())
#have comp make a bid, save to db, and set turn marker
bid = player.comp.bidding()
if bid == "Challenge" or bid == "Exact":
request_items = {'bid': bid.lower(), 'game_id': game_id}
return jsonify(request_items)
update_turn_marker(game)
current_turn_player = get_current_turn_player(game)
total_dice = get_total_dice(players)
#add bidding probabilities if it's the player's turn next
if game.turn_marker == 1:
player_probs = get_player_probs(game_id, bid.die_choice, bid.die_count)
else:
player_probs = None
requests = {'name': player.name,
'die_choice': bid.die_choice,
'die_count': bid.die_count,
'turn_marker_name': current_turn_player.name,
'turn_marker': game.turn_marker,
'game_id': game.id,
'total_dice': total_dice,
'player_probs': player_probs}
return jsonify(requests)
@app.route('/finishturn.json', methods=['POST'])
def finish_turn():
"""Remove the bids from the db, and roll dice for new turn.
Do this once player has pressed the finish turn button so they can analyze
the results of the turn if they choose."""
game_id = request.form.get('game_id')
players = AbstractPlayer.query.filter(AbstractPlayer.game_id == game_id).all()
####dont do this automatically!!!
#Clear bid history after round
BidHistory.query.filter(BidHistory.game_id == game_id).delete()
#roll dice for next round
player_info = roll_player_dice(players)
db.session.commit()
return jsonify(player_info)
@app.route('/endturn.json', methods=['POST'])
def end_turn():
"""End the turn when challenged - check who won and adjust game accordingly.
Remove bids from DB, check bid, remove a die, next turn."""
game_id = request.form.get('game_id')
bid_type = request.form.get('bid').lower()
requests = get_bidding_result(game_id, bid_type)
return jsonify(requests)
@app.route('/playerturn.json', methods=['POST'])
def player_turn():
"""When it's a human player turn, render form to complete bid."""
die_choice = request.form.get('die_choice')
die_count = request.form.get('die_count')
game_id = request.form.get('game_id')
player = AbstractPlayer.query.filter(AbstractPlayer.game_id == game_id,
AbstractPlayer.position == 1).first()
players = get_players_in_game(game_id)
game = Game.query.filter(Game.id == game_id).first()
#save bid ##make function?
new_bid = BidHistory(game_id, player.id, die_choice, die_count)
db.session.add(new_bid)
db.session.commit()
#update turn marker
update_turn_marker(game)
current_turn_player = get_current_turn_player(game)
total_dice = get_total_dice(players)
requests = {'name': player.name,
'die_choice': die_choice,
'die_count': die_count,
'turn_marker': game.turn_marker,
'turn_marker_name': current_turn_player.name,
'game_id': game.id,
'total_dice': total_dice}
return jsonify(requests)
@app.route('/game_details.json')
def get_game_details():
"""Get details needed to update the values in the die count filters."""
game_id = request.args.get('game_id')
#check if this is the initial round setup (if so, starting turn will be passed)
if request.args.get('starting_turn'):
starting_turn = True
else:
starting_turn = False
game = Game.query.filter(Game.id == game_id).first()
players = get_active_players_in_game(game.id)
# if this is the first time the page ever loads, roll dice
if players[0].current_die_roll is None and players[0].die_count == 5:
roll_player_dice(players)
total_dice = get_total_dice(players)
#pass current bids into table on game page...
last_bid = (BidHistory.query
.filter(BidHistory.game_id == game_id)
.order_by(BidHistory.created_at.desc())
.first())
#add bidding probabilities if it's the player's turn
if game.turn_marker == 1 and last_bid:
player_probs = get_player_probs(game_id, last_bid.die_choice, last_bid.die_count)
else:
player_probs = None
current_turn_player = get_current_turn_player(game)
if not last_bid:
results = {'total_dice': total_dice,
'die_count': None,
'die_choice': None,
'turn_marker': game.turn_marker,
'turn_marker_name': current_turn_player.name,
'starting_turn': starting_turn,
'player_probs': player_probs}
else:
results = {'total_dice': total_dice,
'die_count': last_bid.die_count,
'die_choice': last_bid.die_choice,
'turn_marker': game.turn_marker,
'turn_marker_name': current_turn_player.name,
'starting_turn': starting_turn,
'player_probs': player_probs}
return jsonify(results)
@app.route('/factor_charts.json')
def get_factor_charts():
"""Gets details needed to render charts for opponents."""
game_id = request.args.get('game_id')
player_position = request.args.get('position')
player = (AbstractPlayer
.query
.filter(AbstractPlayer.game_id == game_id,
AbstractPlayer.position == player_position)
.order_by(AbstractPlayer.id)
.first())
data_dict = {
"labels": [
"Bluffing",
"Aggression",
"Intelligence"
],
"position": [player_position],
"datasets": [
{
"data": [player.comp.liar_factor, player.comp.aggressive_factor, player.comp.intelligence_factor],
"backgroundColor": [
"#FF6384",
"#36A2EB",
"#FFCE56"
],
"hoverBackgroundColor": [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
}
return jsonify(data_dict)
if __name__ == "__main__":
# We have to set debug=True here, since it has to be True at the
# point that we invoke the DebugToolbarExtension
app.debug = True
app.jinja_env.auto_reload = app.debug # make sure templates, etc. are not cached in debug mode
import sys
if sys.argv[-1] == "setest":
connect_to_db(app=app, uri="postgresql:///testdb")
else:
connect_to_db(app)
# Use the DebugToolbar
# DebugToolbarExtension(app)
app.run(port=5000, host='0.0.0.0')