-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.py
396 lines (343 loc) · 14.6 KB
/
client.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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#!/usr/bin/env python3
from sys import stdout
from threading import Thread
import GameData
import socket
import time
import os
import argparse
import matplotlib.pyplot as plt
import numpy as np
from constants import *
from agent import Agent, Knowledge
from ruleset import Ruleset
# Arguments management
parser = argparse.ArgumentParser()
parser.add_argument('--ip', type=str, default=HOST, help='IP address of the host')
parser.add_argument('--port', type=int, default=PORT, help='Port of the server')
player = parser.add_mutually_exclusive_group()
player.add_argument('--player-name', type=str, help='Player name')
player.add_argument('--ai-player', type=str, help='Play with the AI agent and give him a name')
args = parser.parse_args()
ip = args.ip
port = args.port
AI = False
agent = None
playerName = ""
if args.ai_player is not None:
playerName = args.ai_player
AI = True
else:
if args.player_name is None:
print("You need the player name to start the game, or play with the AI by specifying '--ai-player'.")
exit(-1)
else:
playerName = args.player_name
num_cards = ""
run = True
first = True
statuses = ["Lobby", "Game", "GameHint"]
status = statuses[0]
observation = {'players': None,
'current_player': None,
'usedStormTokens': 0,
'usedNoteTokens': 0,
'fireworks': None,
'discard_pile': None,
'playersKnowledge': []
}
scores = []
player_names = []
ruleset = Ruleset()
def agentPlay():
global run
global status
global observation
global first
if status == statuses[0]: # Lobby
print("I am ready to start the game.")
s.send(GameData.ClientPlayerStartRequest(playerName).serialize())
while run:
if status == statuses[1]:
if observation['current_player'] == playerName:
print("[" + playerName + " - " + status + "]: ", end="")
# AI action
if len(player_names) == 2: # best agent for 2 players game: rule_choice_delta
action = agent.rule_choice_delta(observation)
else:
action = agent.piers_choice(observation)
# action = agent.rl_choice(observation)
# action = agent.piers_choice(observation)
# action = agent.osawa_outer_choice(observation)
# action = agent.vanDerBergh_choice(observation)
# action = agent.vanDerBergh_choice_prob(observation)
# action = agent.rule_choice(observation)
# action = agent.rule_choice_beta(observation)
# action = agent.rule_choice_delta(observation)
try:
s.send(action.serialize())
except:
print("Error")
run = False
observation['current_player'] = ""
def next_turn():
# Get observation : ask to the server to show the data
s.send(GameData.ClientGetGameStateRequest(playerName).serialize())
def manageInput():
global run
global status
while run:
print("[" + playerName + " - " + status + "]: ", end="")
command = input()
# Choose data to send
if command == "exit":
run = False
os._exit(0)
elif command == "ready" and status == statuses[0]:
s.send(GameData.ClientPlayerStartRequest(playerName).serialize())
elif command == "show" and status == statuses[1]:
s.send(GameData.ClientGetGameStateRequest(playerName).serialize())
elif command.split(" ")[0] == "discard" and status == statuses[1]:
try:
cardStr = command.split(" ")
cardOrder = int(cardStr[1])
s.send(GameData.ClientPlayerDiscardCardRequest(playerName, cardOrder).serialize())
except:
print("Maybe you wanted to type 'discard <num>'?")
continue
elif command.split(" ")[0] == "play" and status == statuses[1]:
try:
cardStr = command.split(" ")
cardOrder = int(cardStr[1])
s.send(GameData.ClientPlayerPlayCardRequest(playerName, cardOrder).serialize())
except:
print("Maybe you wanted to type 'play <num>'?")
continue
elif command.split(" ")[0] == "hint" and status == statuses[1]:
try:
destination = command.split(" ")[2]
t = command.split(" ")[1].lower()
if t != "colour" and t != "color" and t != "value":
print("Error: type can be 'color' or 'value'")
continue
value = command.split(" ")[3].lower()
if t == "value":
value = int(value)
if int(value) > 5 or int(value) < 1:
print("Error: card values can range from 1 to 5")
continue
else:
if value not in ["green", "red", "blue", "yellow", "white"]:
print("Error: card color can only be green, red, blue, yellow or white")
continue
s.send(GameData.ClientHintData(playerName, destination, t, value).serialize())
except:
print("Maybe you wanted to type 'hint <type> <destinatary> <value>'?")
continue
elif command == "":
print("[" + playerName + " - " + status + "]: ", end="")
else:
print("Unknown command: " + command)
continue
stdout.flush()
def initialize(players):
global agent
global num_cards
if len(players) < 4:
num_cards = 5
else:
num_cards = 4
if AI:
agent = Agent(playerName, players.index(playerName), num_cards, ruleset)
playersKnowledge = {name: [Knowledge(color=None, value=None) for j in range(num_cards)] for name in players}
return playersKnowledge
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
# 0) open the connection
s.connect((ip, port))
# 1) request a connection from the server
print("Trying to establish a connection with the server...")
request = GameData.ClientPlayerAddData(playerName)
s.send(request.serialize())
# 2) wait the response of the server
try:
data = s.recv(DATASIZE)
data = GameData.GameData.deserialize(data)
except:
print("Error")
run = False
data = ""
if type(data) is GameData.ServerPlayerConnectionOk:
print("Connection accepted by the server. Welcome " + playerName)
print("[" + playerName + " - " + status + "]: ", end="")
if AI:
Thread(target=agentPlay).start()
else:
Thread(target=manageInput).start()
while run:
dataOk = False
# 5) Wait the response from the server
try:
data = s.recv(DATASIZE)
data = GameData.GameData.deserialize(data)
except:
print("Error")
run = False
if not data:
continue
if type(data) is GameData.ServerPlayerStartRequestAccepted:
dataOk = True
# 6) Wait until everyone is ready and the game can start.
# data = s.recv(DATASIZE)
# data = GameData.GameData.deserialize(data)
if type(data) is GameData.ServerStartGameData:
dataOk = True
player_names = data.players
playersKnowledge = initialize(data.players)
print("Game start!")
if AI: next_turn()
# 7) The game can finally start
s.send(GameData.ClientPlayerReadyData(playerName).serialize())
# 8) Set the status from lobby to game.
if not AI:
status = statuses[1]
print("---Starting game process done----")
if type(data) is GameData.ServerGameStateData:
dataOk = True
if not AI:
print("Current player: " + data.currentPlayer)
print("Player hands: ")
for p in data.players:
print(p.toClientString())
print("Table cards: ")
for pos in data.tableCards:
print(pos + ": [ ")
for c in data.tableCards[pos]:
print(c.toClientString() + " ")
print("]")
print("Discard pile: ")
for c in data.discardPile:
print("\t" + c.toClientString())
print("Note tokens used: " + str(data.usedNoteTokens) + "/8")
print("Storm tokens used: " + str(data.usedStormTokens) + "/3")
else:
observation = {'players': data.players,
'current_player': data.currentPlayer,
'usedStormTokens': data.usedStormTokens,
'usedNoteTokens': data.usedNoteTokens,
'fireworks': data.tableCards,
'discard_pile': data.discardPile,
'playersKnowledge': playersKnowledge}
if AI and first:
# 8) Set the status from lobby to game.
status = statuses[1]
agent.set_players(observation)
first = False
if type(data) is GameData.ServerActionInvalid:
dataOk = True
print("Invalid action performed. Reason:")
print(data.message)
if type(data) is GameData.ServerActionValid: # DISCARD
dataOk = True
print(" [", data.lastPlayer, "] :", data.action, data.card.toString())
# update players knowledge
playersKnowledge[data.lastPlayer].pop(data.cardHandIndex)
if data.handLength == num_cards: # if the player got a new card
playersKnowledge[data.lastPlayer].append(Knowledge(None, None))
# if the player was the agent update its internal possibilities
if AI and data.lastPlayer == playerName:
agent.reset_possibilities(data.cardHandIndex, data.handLength == num_cards)
if AI: next_turn()
if type(data) is GameData.ServerPlayerMoveOk:
dataOk = True
print("[", data.lastPlayer, "] :", data.action, data.card.toString())
# update players knowledge
playersKnowledge[data.lastPlayer].pop(data.cardHandIndex)
if data.handLength == num_cards: # if the player got a new card
playersKnowledge[data.lastPlayer].append(Knowledge(None, None))
# if the player was the agent update its internal possibilities
if AI and data.lastPlayer == playerName:
agent.reset_possibilities(data.cardHandIndex, data.handLength == num_cards)
if AI: next_turn()
if type(data) is GameData.ServerPlayerThunderStrike: # PLAYED WRONG
dataOk = True
print("[", data.lastPlayer, "] :", data.action, data.card.toString())
# update players knowledge
playersKnowledge[data.lastPlayer].pop(data.cardHandIndex)
if data.handLength == num_cards: # if the player got a new card
playersKnowledge[data.lastPlayer].append(Knowledge(None, None))
# if the player was the agent update its internal possibilities
if AI and data.lastPlayer == playerName:
agent.reset_possibilities(data.cardHandIndex, data.handLength == num_cards)
if AI: next_turn()
if type(data) is GameData.ServerHintData: # HINT
dataOk = True
print("[" + data.source + "]: " + "Hinted to " + data.destination + " cards with value/color " + str(
data.value) + " are: ", data.positions)
d_val = d_col = None
if data.type == 'value':
d_val = data.value
else:
d_col = data.value
for i in data.positions:
if d_val is not None:
playersKnowledge[data.destination][i].value = d_val
if d_col is not None:
playersKnowledge[data.destination][i].color = d_col
if AI and data.destination == playerName:
agent.receive_hint(data.destination, data.type, data.value, data.positions)
if AI: next_turn()
if type(data) is GameData.ServerInvalidDataReceived:
dataOk = True
print(data.data)
if type(data) is GameData.ServerGameOver:
dataOk = True
print(data.message)
print(data.score)
print(data.scoreMessage)
scores.append(data.score)
avg = sum(scores) / len(scores)
print(" |Average score so far: ", avg)
print(" |Games played: ", len(scores))
print(" |Best result: ", max(scores))
print(" |Worst result: ", min(scores))
'''
# plotting results
if len(scores) >= 100:
x = np.arange(0, len(scores), 1)
plt.plot(x, scores)
plt.plot(x, [avg] * len(scores), 'r--') # plotting the average
plt.scatter(x, scores)
plt.xlabel('games')
plt.ylabel('scores')
plt.xticks(x)
plt.yticks(scores)
plt.title('Agent =rule_choice_delta Num_players = 5')
t = time.localtime()
timestamp = time.strftime('%b-%d-%Y_%H%M', t)
plt.savefig('graphs/' + timestamp + '.png')
run = False
'''
# reset and re-initialize
if run is not False:
del agent
observation = {'players': None,
'current_player': None,
'usedStormTokens': 0,
'usedNoteTokens': 0,
'fireworks': None,
'discard_pile': None,
'playersKnowledge': []}
#time.sleep(5)
status = statuses[0]
first = True
playersKnowledge = initialize(player_names)
if AI: next_turn()
stdout.flush()
# run = False
print("Ready for a new game")
if not dataOk:
print("Unknown or unimplemented data type: " + str(type(data)))
if not AI:
print("[" + playerName + " - " + status + "]: ", end="")
stdout.flush()
print("END")