-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
275 lines (247 loc) · 8.92 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
#!/usr/bin/env python3
import configparser
import threading
import socket
import argparse
import os
import json
import random
import time
# Liczba graczy potrzebna do rozpoczęcia
MIN_PLAYERS = 3
# Pula haseł
TITLES = [
"Python",
"3",
"JavaScript",
"Hamburger",
"Wieloryb",
"Szkoła",
"Uniwersytet",
"Remiza",
"Pomidor",
"Radość",
"Młot",
"Baran",
"Hiacynt",
"Jedzenie w samolocie",
"Rozpacz",
"Ciasto",
"Słońce",
"Pantofel",
"Widmo",
"Dama",
"Krawędź",
"Japonki",
"Zamek",
"Szmalcownik",
"Bazy danych",
"Szarada",
"Głaz",
"Piwnica",
"Pióro",
"Rachunek prawdopodobieństwa",
"Jabłko",
"Granat",
"Przystań",
"Sumo",
"Baba",
"Tygrys",
"Staw",
"Oliwa",
"Grzebień",
"Kuba",
"Piła",
"Polka",
"Warta",
"Róża",
"Kosa",
"Narcyz",
"Zebra",
"Kapelusz",
"Kule",
"Mars",
"Kiwi",
"Mysz"
]
class Server(threading.Thread):
def __init__(self, host, port):
super().__init__()
self.config = configparser.ConfigParser()
self.config.read("config.ini", "UTF8")
self.connections = []
self.host = host
self.port = port
# Init ustawień
self.data = {}
self.data["title"] = "undefined"
self.data["state"] = "wait"
self.data["users"] = {}
self.data["messages"] = {}
self.data["scores"] = {}
self.data["total_scores"] = {}
self.votes = {}
# Callowane po każdej rundzie
def reset(self):
time.sleep(10)
print("New round")
self.votes = {}
self.data["scores"] = {}
self.data["messages"] = {}
self.data["title"] = random.choice(TITLES)
self.data["state"] = "wait"
# Stan zależny od liczby graczy
if self.player_count() >= MIN_PLAYERS:
self.data["state"] = "game"
else:
self.data["state"] = "wait"
dump = json.dumps(self.data, ensure_ascii=False)
self.broadcast_all(dump)
def run(self):
# Init serwera
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((self.host, self.port))
sock.listen(1)
print('Listening at', sock.getsockname())
idx = 0
try:
while True:
# Czekaj na nowe połączenie i twórz nowe ""wątki""
sc, sockname = sock.accept()
print('{} has joined'.format(idx))
server_socket = ServerSocket(sc, sockname, self, idx)
idx += 1
server_socket.start()
# self.connections trzyma wszystkie aktualne połączenia
self.connections.append(server_socket)
except KeyboardInterrupt:
self.quit()
def quit(self):
with open("config.ini", 'w') as config_file:
self.config.write(config_file)
os._exit(0)
def broadcast(self, message, source):
for connection in self.connections:
# Wyślij wiadomość do wszystkich oprócz source
if connection.sockname != source:
connection.send(message)
def broadcast_all(self, message):
for connection in self.connections:
connection.send(message)
def remove_connection(self, connection):
self.connections.remove(connection)
def player_count(self):
return len(self.connections)
# Klasa reprezentująca jedno połączenie
class ServerSocket(threading.Thread):
def __init__(self, sc, sockname, server, id):
super().__init__()
self.sc = sc
self.id = id
self.sockname = sockname
self.server = server
self.username = ""
# Rozłącz i usuń się z danych
def call_quit(self):
print('{} has left'.format(self.id))
self.server.data["users"].pop(self.id, None)
self.server.data["messages"].pop(self.id, None)
self.server.data["scores"].pop(self.id, None)
self.server.data["total_scores"].pop(self.id, None)
self.server.votes.pop(self.id, None)
self.sc.close()
server.remove_connection(self)
if self.server.player_count() == 0:
self.server.data["state"] = "wait"
def run(self):
try:
data = self.server.data
while True:
message = self.sc.recv(1024).decode('utf8')
if not message:
self.call_quit()
return
elif message:
# Nie ma zainicjalizowanego username => ten klient się wita
if self.username == "":
self.username = message
data["users"][self.id] = self.username
# Zmień stan, gdy jest już wystarczająca liczba graczy
if len(data["users"]) >= MIN_PLAYERS and data["state"] == "wait":
data["title"] = random.choice(TITLES)
data["state"] = "game"
dump = json.dumps(data, ensure_ascii=False)
self.server.broadcast(dump, self.sockname)
data_copy = data.copy()
data_copy["playerid"] = self.id
dump = json.dumps(data_copy, ensure_ascii=False)
self.send(dump)
# Klient wysłał aforyzm
elif data["state"] == "game":
data["messages"][self.id] = message
# Zmień stan, gdy wszyscy wysłali
if len(data["messages"]) == self.server.player_count():
data["state"] = "vote"
dump = json.dumps(data, ensure_ascii=False)
self.server.broadcast_all(dump)
# Klient głosuje
elif data["state"] == "vote":
self.server.votes[self.id] = int(message)
if len(self.server.votes) == self.server.player_count():
# Zliczanie głosów
for key in self.server.votes:
player = self.server.votes[key]
if player not in data["scores"]:
data["scores"][player] = 0
data["scores"][player] += 1
# Naokoło dodawanie ich do totala oraz do configa
# Config jest osobno, bo jeśli są name clashe, to istnieją dwa total_scores i jeden wpis w configu
for player in data["scores"]:
name = data["users"][player]
if player not in data["total_scores"]:
if name in self.server.config["DEFAULT"]:
data["total_scores"][player] = int(
self.server.config["DEFAULT"][name])
else:
data["total_scores"][player] = 0
self.server.config["DEFAULT"][name] = "0"
data["total_scores"][player] += data["scores"][player]
self.server.config["DEFAULT"][name] = str(int(
int(self.server.config["DEFAULT"][name]) + int(data["scores"][player])))
# Zmiana stanu na display
data["state"] = "display"
dump = json.dumps(data, ensure_ascii=False)
self.server.broadcast_all(dump)
with open("config.ini", 'w') as config_file:
self.server.config.write(config_file)
self.server.reset()
except KeyboardInterrupt or EOFError:
print("Caught keyboard interrupt, exiting")
self.call_quit()
os._exit(0)
except ConnectionResetError:
self.call_quit()
def send(self, message):
self.sc.sendall(message.encode('utf8'))
def quit(server):
for connection in server.connections:
connection.sc.close()
os._exit(0)
# Wyjście na Ctrl+C albo Ctrl+Z
def exit(server):
try:
while True:
input('')
except KeyboardInterrupt:
quit(server)
except EOFError:
quit(server)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Aphorism Server')
parser.add_argument('host', help='Interface the server listens at')
args = parser.parse_args()
server = Server(args.host, 7312)
server.start()
exit = threading.Thread(target=exit, args=(server,))
exit.start()