-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
129 lines (100 loc) · 2.55 KB
/
main.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
import socket as s
import json
import time
import sys
import Abalone_V2 as av
import math
class NotAJSONObject(Exception):
pass
class Timeout(Exception):
pass
def sendJSON(socket, obj):
"""
Vérifie que l'objet est bien un JSON\n
Le convertit en objet JSON et l'envoie vers l'adresse liée au socket
"""
message = json.dumps(obj)
if message[0] != '{':
raise NotAJSONObject('sendJSON support only JSON Object Type')
message = message.encode('utf8')
total = 0
while total < len(message):
sent = socket.send(message[total:])
total += sent
def receiveJSON(socket, timeout = 1):
"""
Reçoit un socket et un timer, attend que le message soit reçu.\n
Vérifie que le message est bien un JSON et le convertit.\n
Retourne l'objet JSON.
"""
finished = False
message = ''
data = ''
start = time.time()
while not finished:
message += socket.recv(4096).decode('utf8')
if len(message) > 0 and message[0] != '{':
raise NotAJSONObject('Received message is not a JSON Object')
try:
data = json.loads(message)
finished = True
except json.JSONDecodeError:
if time.time() - start > timeout:
raise Timeout()
return data
def fetch(address, data, timeout=1):
"""
Utilise receiveJSON et sendJSON.\n
Envoie un message vers l'adresse encodée.\n
Attend un retour et renvoie la réponse.
"""
socket = s.socket()
socket.connect(address)
sendJSON(socket, data)
response = receiveJSON(socket, timeout)
return response
if __name__ == '__main__':
port = int(sys.argv[1])
print("Start...")
response = fetch(('127.0.0.1', 3000), {
"request": "subscribe",
"port": port,
"name": "zozo le donzo",
"matricules": ["18332", "20324"]
})
socket = s.socket(s.AF_INET, s.SOCK_STREAM)
try:
socket.bind(('127.0.0.1', port))
except s.error as e:
print(e)
print("Waiting for ping...")
socket = s.socket(s.AF_INET, s.SOCK_STREAM)
try:
socket.bind(('127.0.0.1', port))
except s.error as e:
print(e)
socket.listen()
while True:
client, addr = socket.accept()
data = receiveJSON(client)
if data["request"] == "ping":
sendJSON(client, {"response":"pong"})
elif data["request"] == "play":
board = data["state"]["board"]
currentPlayer = data["state"]["current"]
if currentPlayer == 0:
player = False
else:
player = True
state = av.Board(board)
score, move = av.minimax(state, 2, True, player, - math.inf, math.inf)
print(move)
sendJSON(client, {
"response":"move",
"move" : {
"marbles": move[0],
"direction": move[1]
},
"message":"il est tard"
})
client.close()