This repository was archived by the owner on Sep 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
278 lines (206 loc) · 6.5 KB
/
Copy pathserver.py
File metadata and controls
278 lines (206 loc) · 6.5 KB
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
import json
import random
import socket
import threading
import tkinter as tk
from time import sleep
animals = ["Antilope anonima", "Barbagianni anonimo", "Leone anonimo", "Giraffa anonima", "Scoiattolo anonimo", "Squalo anonimo", "Orango anonimo"]
class Player:
def __init__(self):
self.username = random.choice(animals)
self.points = 0
def game_start():
global accept_answers
broadcast({
"cmd": "start"
})
broadcast({
"cmd": "question",
"question": "di che colore è il cavallo bianco di napoleone?",
"answers": [
"bianco",
"viola",
"arancione"
],
"time": 10
})
accept_answers = True
sleep(10)
close_question(0)
broadcast({
"cmd": "question",
"question": "di che colore è il cavallo rosso di napoleone?",
"answers": [
"bianco",
"rosso",
"arancione"
],
"time": 10
})
accept_answers = True
sleep(10)
close_question(1)
winner()
started = False
def start_button():
'''funzione per avviare il gioco e con esso il tempo'''
global started
if not started:
t = threading.Thread(target=game_start)
t.start()
started = True
def get_ip():
"""estrae l'ip per mostrarlo a video """
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except:
IP = '127.0.0.1'
finally:
s.close()
return IP
def receive(client, client_addr):
""" gestione ricezione dei messaggi."""
recv_buffer = ""
while True:
try:
data = client.recv(128)
recv_buffer = recv_buffer + data.decode("utf-8")
strings = recv_buffer.split('\0')
for s in strings[:-1]:
s = json.loads(s)
command = s["cmd"]
print(s)
if command == "join":
setUsername(client_addr, s["msg"])
if command == "sendMsg":
send_msg(client_addr, s["msg"])
if command == "answer":
receive_answer(client_addr, s["answer"])
recv_buffer = strings[-1]
except OSError:
break
def receive_answer(client_addr, answer):
if not accept_answers:
return
answers[client_addr] = answer
def close_question(correct_answer):
global accept_answers
accept_answers = False
for client_addr, answer in answers.items():
if answer == correct_answer:
players[client_addr].points += 100
sleep(3)
broadcast({
"cmd": "correction",
"answer": correct_answer
})
sleep(3)
update_leaderboard()
def winner():
broadcast({
"cmd": "winner",
"username": [player.username for player in sorted(list(players.values()), key=lambda a: a.points)][0]
})
def send_msg(client_addr, msg):
broadcast({
"cmd": "receiveMsg",
"msg": msg,
"sender": players[client_addr].username
})
def write_msg(msg):
object = {
"command": "",
"msg": msg
}
broadcast(object)
def setUsername(client_addr, username):
players[client_addr].username = username
print(username)
update_leaderboard()
def broadcast(obj):
"""funzione per inviare i messaggi a tutti i client associati alla chat"""
for c in clients.values():
send_to_client(c, obj)
def send_to_client(client, obj):
client.send(bytes(json.dumps(obj) + "\0", "utf-8"))
def accept_clients(server, y):
'''funzione per la gestione dell'accettazione di client da parte del server
la chat può accettare al massimo 10 client'''
if gioco_iniziato.get() == True:
return
try:
while True:
if client_counter.get() < 10:
client, client_addr = server.accept()
indirizzi[client] = client_addr
threading._start_new_thread(gestisce_client, (client, client_addr))
client_counter.set(client_counter.get() + 1)
except:
pass
def gestisce_client(client, client_addr):
'''funzione per la gestione dei client'''
addClientToList(client, client_addr)
#threading.Thread(target=receive, args=(client, client_addr))
receive(client, client_addr)
global game_timer
def addClientToList(client, client_ip):
clients[client_ip] = client
players[client_ip] = Player()
update_leaderboard()
lbl = label_counter.cget("text")
label_counter.config(text=str(lbl) + str(client_ip) + "\n")
label_counter.pack()
def update_leaderboard():
broadcast({
"cmd": "leaderboard",
"leaderboard": [{
"name": player.username,
"points": player.points
} for player in sorted(list(players.values()), key=lambda a: a.points)]
})
def close_window(window):
window.destroy()
if __name__ == '__main__':
# grafica
window = tk.Tk()
window.title("Server")
window.geometry("400x500")
window.config(bg="#4181C0")
window.resizable(False, False)
gioco_iniziato = tk.BooleanVar(False)
almeno_un_nome = tk.BooleanVar(False)
client_counter = tk.IntVar(0)
# start button
btnStart = tk.Button(window, bg="#4181C0", text="START GAME", font=("Elephant", 30, "bold"),
command=lambda: start_button())
btnStart.place(x=25, y=270, width=350, height=80)
# list
label_counter = tk.Label(window, text="", font=("forte", 14, "bold"), bg="#4181C0", relief="sunken")
label_counter.place(x=20, y=20, width=360, height=200)
# server ip
label_ip = tk.Label(window, text="Indirizzo IP:", font=("Perpetua", 25, "bold"), bg="#4181C0",
relief="groove")
label_ip.place(x=50, y=360, width=300, height=50)
label_ip = tk.Label(window, text=str(get_ip()), font=("Perpetua", 30, "bold"), bg="#4181C0",
relief="groove")
label_ip.place(x=50, y=420, width=300, height=70)
# variabili nel main
game_timer = 100
# gestione della connessione
server = None
HOST_ADDR = ""
HOST_PORT = 53000
BUFSIZ = 1024
clients = {}
players = {}
indirizzi = {}
answers = {}
accept_answers = False
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST_ADDR, HOST_PORT))
server.listen(10)
threading._start_new_thread(accept_clients, (server, " "))
window.mainloop()
server.close()