/
app.py
164 lines (129 loc) · 4.84 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
from flask import Flask, render_template, session, request, jsonify, redirect, \
Response, url_for
from flask_login import LoginManager, UserMixin, current_user, login_user, \
logout_user
from flask_session import Session
from flask_socketio import SocketIO, emit
from utils import format_cards
from jj import Game
app = Flask(__name__, static_url_path='')
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION_TYPE'] = 'filesystem' # redis
login = LoginManager(app)
Session(app)
socketio = SocketIO(app, manage_session=False)
################################################################################
# User & Session of User:
# * Locally, every login logout --> single username in a session
# * Globally, every login logout --> single user object in a user heap
# * TODO: At every login, authorize the users with player handler id
################################################################################
app.current_user_ids = set([])
app.current_user_info = {}
def game_login_current_user():
app.current_user_ids.add(current_user.id)
if current_user.id not in app.current_user_info:
tmp = len(app.current_user_ids)-1
app.current_user_info[current_user.id] = [0+tmp, 2+tmp, 4+tmp]
print('Someone Logged in:', app.current_user_info)
def game_logout_current_user():
app.current_user_ids.remove(current_user.id)
app.current_user_info.pop(current_user.id)
print('Someone Logged out:', app.current_user_info)
class User(UserMixin, object):
def __init__(self, id=None):
self.id = id
@login.user_loader
def load_user(id):
return User(id)
@app.route('/session', methods=['GET', 'POST'])
def session_access():
if request.method == 'GET':
return jsonify({
'session': session.get('value', ''),
'user': current_user.id
if current_user.is_authenticated else 'anonymous'
})
data = request.get_json()
if 'session' in data:
session['value'] = data['session']
elif 'user' in data:
if data['user']:
login_user(User(data['user']))
game_login_current_user()
else:
game_logout_current_user()
logout_user()
return '', 204
@socketio.on('get-session')
def get_session():
emit('refresh-session', {
'session': session.get('value', ''),
'user': current_user.id
if current_user.is_authenticated else 'anonymous'
})
################################################################################
# Game Play: View Section
################################################################################
app.g = Game()
@socketio.on('init')
def restart():
app.g = Game()
print('\nStart a new game.')
emit('next-round', broadcast=True)
@app.route('/')
def refresh():
is_authenticated = current_user.is_authenticated
if not is_authenticated:
return render_template('sessions.html', is_authenticated=is_authenticated)
# Only authenticated user comes to the following lines
g = app.g
# an authenticated user is correctly logged in the game
if current_user.id not in app.current_user_ids:
game_login_current_user()
info = {}
user_playerids = app.current_user_info[current_user.id]#[0, 2, 4]
oppo_playerids = [0, 1, 2, 3, 4, 5]
info['user_players'] = []
info['oppo_players'] = []
info['round_player'] = g.get_round_player_id()
info['round_cards'] = format_cards(g.get_table()[1])
info['round_last'] = g.get_table()[0]
for i in user_playerids:
player = {}
player['id'] = i
player['cards'] = format_cards(g.get_cards(i))
info['user_players'].append(player)
for j in oppo_playerids:
player = {}
player['id'] = j
player['cnt'] = g.get_ncards(j)
info['oppo_players'].append(player)
#print(url_for('static', filename='cards.css'))
return render_template('sessions.html', is_authenticated=is_authenticated,
online_users=app.current_user_ids, **info)
################################################################################
# Game Play: Control Section
################################################################################
app.count = 0
@app.route('/send', methods=['POST'])
def update():
form = request.form.to_dict()
round_player_id = int(form.pop('playerid'))
cards = list(form.keys())
app.count += 1
###
g = app.g
round_status = g.play(round_player_id, cards)
###
return Response('success', status=200)
@socketio.on('ready4next')
def send_next():
print('Broadcast Next Round.\n')
emit('next-round', broadcast=True)
if __name__ == '__main__':
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
print('Server Starts.')
socketio.run(app, host='0.0.0.0', port=7777, log_output=False)