-
Notifications
You must be signed in to change notification settings - Fork 0
/
events.py
309 lines (250 loc) · 8.26 KB
/
events.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
import time
import requests
import socketio
import threading
import aiplayer as ai
import format
from format import *
login_url = 'https://nope-server.azurewebsites.net/api/auth/login'
register_url = 'https://nope-server.azurewebsites.net/api/auth/register'
sio = socketio.Client()
access_token = None
player_id = None
hand = None
topCard = None
last_topCard = None
last_move = None
current_player = None
opp_hand_size = None
tournament_started = False
lock = threading.Lock()
def login(name, password):
"""
Handles Client-Login
:param name: Name of client-player
:param password: password of client-player
:return: true if successful, false otherwise
"""
data = {"username": name, "password": password}
response = requests.post(login_url, json=data)
if response.status_code == 400 or response.status_code == 401:
return False
# Try to get Access-Token
try:
player = response.json()['user']
global player_id
player_id = (player['id'])
except KeyError or requests.exceptions.JSONDecodeError:
return False
# Save Access-Token
global access_token
access_token = response.json()['accessToken']
# Connect to server
sio.connect("https://nope-server.azurewebsites.net", namespaces='/', auth={'token': access_token})
return True
def registration(name, password, firstname, lastname):
"""
Handles Client-Registration
:param name: Username of new user
:param password: Password of new user
:param firstname: Real firstname of User
:param lastname: Real lastname of user
:return: true if successful, false otherwise
"""
data = {"username": name, "password": password, "firstname": firstname, "lastname": lastname}
# Register on server
response = requests.post(register_url, json=data)
if response.status_code == 201:
return True
return False
# Server -> Client
@sio.event
def connect():
"""
Connect to server
:return: nothing
"""
print(f"\n{Color.GREEN_BOLD}Connected to server.{Color.RESET}")
@sio.event
def disconnect():
"""
Disconnect from server
:return: nothing
"""
print(f"\n{Color.GREEN_BOLD}Disconnected from server{Color.RESET}")
@sio.event
def callback(data):
"""
Prints data on acknowledgment
:param data: data received from server
:return: nothing
"""
print(data)
@sio.on("tournament:playerInfo")
def player_info(data, _):
"""
Prints player-info
:param data: player-info-data received from server
:param _: placeholder
:return: nothing
"""
with lock:
print("\n")
print("PLAYER INFO: ")
print(data['message'])
print("-" * 20)
@sio.on("tournament:info")
def tournament_info(data, _):
"""
Prints tournament-info
:param data: tournament-info-data received from server
:param _: placeholder
:return: nothing
"""
with lock:
global tournament_started, access_token
print("\n")
print("TOURNAMENT INFO: ")
print(f"{Color.WHITE_BACKGROUND_BRIGHT} + {Color.BLACK_BOLD}{data['message']}{Color.RESET}\n"
f"{Color.WHITE_BACKGROUND_BRIGHT} + {Color.BLACK_BOLD}{data['status']}.{Color.RESET}")
print("-" * 20)
if (data['status']) == "FINISHED":
tournament_started = False
print_menu()
if (data['status']) == "IN_PROGRESS":
tournament_started = True
@sio.on("match:info")
def match_info(data, _):
"""
Prints match-info
:param data: match-info-data received from server
:param _: placeholder
:return: nothing
"""
with lock:
print("MATCH INFO: ")
print(f"{Color.WHITE_BACKGROUND_BRIGHT} + {Color.BLACK_BOLD}{data['message']}.{Color.RESET}")
print("-" * 20)
print("\n")
@sio.on("list:tournaments")
def list_tournaments(data, _):
"""
Prints list of tournaments
:param data: tournament-list data received from server
:param _: placeholder
:return: nothing
"""
with lock:
if not tournament_started:
format.formatted_data = {}
format.counter = 0
# Lists tournament info for all tournaments
content = []
row_content = []
for tournament in data:
row_content.append(tournament['id'])
row_content.append(tournament['status'])
for player in tournament["players"]:
row_content.append(player["username"])
content.append(row_content)
row_content = []
for entry in content:
format.add_entry(entry)
print(f"\n{Color.RESET}")
for key, value in format.formatted_data.items():
print(f"{Color.WHITE_BRIGHT} + {key}: {value}{Color.RESET}")
print("\n")
@sio.on("game:makeMove")
def make_move(data):
"""
Initializes ai-player move
:param data: turn-data received from server
:return: move to make
"""
with lock:
global topCard, hand
move = ai.ai_player_build_move(hand, topCard, last_topCard, last_move)
time.sleep(0.5)
return move
@sio.on("game:state")
def game_state(data, _):
"""
Prints the current game-state
:param data: game-state-data received from server
:param _: placeholder
:return: nothing
"""
with lock:
global topCard, hand, last_move, current_player, last_topCard, player_id, opp_hand_size
topCard = data['topCard']
last_topCard = data['lastTopCard']
hand = data['hand']
last_move = data['lastMove']
current_player = data['currentPlayer']
for player in data['players']:
if player_id != player['id']:
opp_hand_size = player['handSize']
if player_id == current_player['id']:
print(f"\nIts Your Turn!")
if last_move is not None:
print_move_formatted(last_move, prefix="LAST-")
print_hand_formatted(hand, opp_hand_size)
print_top_card_formatted(topCard)
@sio.on("game:status")
def game_status(data, _):
"""
Prints message and winner
:param data: status-data received from server
:param _: placeholder
:return: nothing
"""
time.sleep(0.5)
print(f"{Color.WHITE_BACKGROUND_BRIGHT} + {Color.BLACK_BOLD}{data['message']}.{Color.RESET}\n"
f"{Color.WHITE_BACKGROUND_BRIGHT} + {Color.BLACK_BOLD}WINNER: {data['winner']['id']} : "
f"{data['winner']['username']} : "
f"{data['winner']['points']}.{Color.RESET}")
# Client -> Server
# tournament:create
def create_tournament(num_best_of_matches):
"""
Creates a tournament with an emit to the server
:param num_best_of_matches: number of max matches
:return: nothing
"""
response = sio.call("tournament:create", num_best_of_matches)
print(f"\n{Color.GREEN_BOLD}TOURNAMENT CREATED{Color.RESET}"
if response['success'] else f"\n{Color.RED_BOLD}{response['error']['message']}"
f"{Color.RESET}\n")
# tournament:join
def join_tournament(tournament_id):
"""
Join a tournament with an id
:param tournament_id: tournament you want to join
:return: nothing
"""
response = sio.call("tournament:join", tournament_id)
print(f"\n{Color.GREEN_BOLD}TOURNAMENT JOINED{Color.RESET}"
if response['success'] else f"\n{Color.RED_BOLD}{response['error']['message']}"
f"{Color.RESET}\n")
# tournament:leave
def leave_tournament():
"""
Leave a tournament
:return: nothing
"""
response = sio.call("tournament:leave")
print(f"\n{Color.GREEN_BOLD}TOURNAMENT LEFT{Color.RESET}"
if response['success'] else f"\n{Color.RED_BOLD}{response['error']['message']}"
f"{Color.RESET}\n")
# tournament:start
def start_tournament():
"""
Start a tournament
:return: true if successful, false otherwise
"""
response = sio.call("tournament:start")
print(f"\n{Color.GREEN_BOLD}TOURNAMENT STARTED{Color.RESET}"
if response['success'] else f"\n{Color.RED_BOLD}{response['error']['message']}"
f"{Color.RESET}\n")
if response['success']:
return True