/
player.py
383 lines (273 loc) · 13.2 KB
/
player.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
"""This module containts the abstract class Player and some implementations."""
import os
import copy
from random import shuffle, choice
from card import Suit, Rank, Card, Deck
from rules import is_card_valid
OUT_FILE = None
class Player(object):
"""
Abstract class defining the interface of a Computer Player.
"""
def __init__(self, verbose=False):
self.seen_cards = []
self.freeze_cards = []
self.transfer_cards = {}
self.name = None
self.position = None
self.expose = False
self.proactive_mode = set()
self.void_info = {0: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False},
1: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False},
2: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False},
3: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False}}
self.remaining_cards = set(Deck().cards)
self.num_hand_cards = {0: 13, 1: 13, 2: 13, 3: 13}
self.verbose = verbose
def say(self, message, *formatargs):
if self.verbose:
global OUT_FILE
message = message.format(*formatargs)
if os.path.exists("/log"):
if OUT_FILE is None: OUT_FILE = open("/log/game.log", "a")
OUT_FILE.write("{}\n".format(message))
else:
print(message)
def set_transfer_card(self, received_player, card):
self.transfer_cards.setdefault(received_player, [])
if isinstance(card, list):
self.transfer_cards[received_player].extend(card)
elif isinstance(card, Card):
self.transfer_cards[received_player].append(card)
else:
raise
def set_position(self, idx):
self.position = idx
def pass_cards(self, hand, round_idx):
"""Must return a list of three cards from the given hand."""
return NotImplemented
def freeze_pass_card(self, card):
self.freeze_cards.append(card)
def is_pass_card(self, card):
return card in self.freeze_cards
def play_card(self, game):
return NotImplemented
def expose_hearts_ace(self, hand_cards):
self.expose = False
return self.expose
def see_played_trick(self, card, game):
self.seen_cards.append(card)
for tc in game._player_hands[self.position]:
if tc in self.remaining_cards:
self.remaining_cards.remove(tc)
else:
break
if card in self.remaining_cards:
self.remaining_cards.remove(card)
if game.trick[0].suit != card.suit:
self.void_info[game.current_player_idx][game.trick[0].suit] = True
self.num_hand_cards[game.current_player_idx] -= 1
def get_leading_suit_and_rank(self, trick):
leading_suit = trick[0].suit
max_rank_in_leading_suit = max([card.rank for card in trick if card.suit == leading_suit])
return leading_suit, max_rank_in_leading_suit
def undesirability(self, card, take_pig_card=False):
additional_rank = 0
if not take_pig_card and card.suit == Suit.spades:
if card.rank == Rank.queen:
additional_rank = 15
elif card.rank > Rank.queen:
additional_rank = 10
elif card.suit == Suit.hearts:
additional_rank = 2
elif card == Card(Suit.clubs, Rank.ten):
additional_rank = 2
return card.rank.value + additional_rank
def get_valid_cards(self, hand, game):
cards = [card for card in hand if is_card_valid(hand, game.trick, card, game.trick_nr, game.is_heart_broken)]
cards.sort(key=lambda x: self.undesirability(x, game.take_pig_card), reverse=(True if game.trick else False))
return cards
def get_remaining_cards(self, hand_cards):
deck = Deck()
remaining_cards = []
for c in deck.cards:
for pc in hand_cards + self.seen_cards:
if c == pc:
break
else:
remaining_cards.append(c)
return remaining_cards
def simple_redistribute_cards(self, game, remaining_cards):
#print("start to simple_redistribute_cards")
fixed_cards = {}
for player_idx in range(4):
for card in self.transfer_cards.get(player_idx, []):
if card in remaining_cards:
remaining_cards.remove(card)
fixed_cards.setdefault(player_idx, [])
fixed_cards[player_idx].append(card)
shuffle(remaining_cards)
for idx in range(len(game._player_hands)):
if idx != self.position:
cards = fixed_cards.get(idx, [])
game._player_hands[idx] = remaining_cards[:len(game._player_hands[idx])-len(cards)]
#choice(remaining_cards, len(game._player_hands[idx])-len(cards), replace=False).tolist()
for used_card in game._player_hands[idx]:
remaining_cards.remove(used_card)
if cards:
game._player_hands[idx].extend(cards)
if remaining_cards:
self.say("Error in redistributing cards, {}, {}, {}", type(self).__name__, remaining_cards, [len(v) for v in game._player_hands])
raise
return game
def redistribute_cards(self, copy_game, copy_remaining_cards):
retry = 3
while retry >= 0:
game = copy.deepcopy(copy_game)
remaining_cards = copy.deepcopy(copy_remaining_cards)
shuffle(remaining_cards)
ori_size, fixed_cards = [], set()
for idx in range(len(game._player_hands)):
if idx != self.position:
size = len(game._player_hands[idx])
ori_size.append(size)
game._player_hands[idx] = []
for card in self.transfer_cards.get(idx, []):
if card in remaining_cards:
game._player_hands[idx].append(card)
remaining_cards.remove(card)
fixed_cards.add(card)
removed_cards = []
for card in remaining_cards:
if game.lacking_cards[idx][card.suit] == False:
game._player_hands[idx].append(card)
removed_cards.append(card)
if len(game._player_hands[idx]) == size:
break
for card in removed_cards:
remaining_cards.remove(card)
else:
ori_size.append(len(game._player_hands[idx]))
retry2 = 3
lacking_idx = [idx for idx in range(4) if len(game._player_hands[idx]) < ori_size[idx]]
while retry2 >= 0 and any([ori_size[player_idx] != len(game._player_hands[player_idx]) for player_idx in range(4)]):
removed_cards = []
for card in remaining_cards:
latest_lacking_idx = [idx for idx in range(4) if len(game._player_hands[idx]) < ori_size[idx]]
player_idx = choice([player_idx for player_idx in range(4) if player_idx not in latest_lacking_idx + [self.position]])
hand_cards = game._player_hands[player_idx]
for card_idx, hand_card in enumerate(hand_cards):
if hand_card not in fixed_cards and not game.lacking_cards[latest_lacking_idx[0]][hand_card.suit]:
game._player_hands[player_idx][card_idx] = card
game._player_hands[latest_lacking_idx[0]].append(hand_card)
removed_cards.append(card)
break
for card in removed_cards:
remaining_cards.remove(card)
for player_idx, size in enumerate(ori_size):
if len(game._player_hands[player_idx]) > size:
for idx in range(len(game._player_hands[player_idx])-size):
candidated_cards = [card for card in game._player_hands[player_idx] if card not in fixed_cards]
if candidated_cards:
card = choice(candidated_cards)
game._player_hands[player_idx].remove(card)
remaining_cards.append(card)
retry2 -= 1
if remaining_cards or any([ori_size[player_idx] != len(game._player_hands[player_idx]) for player_idx in range(4)]):
retry -= 1
else:
copy_game = game
break
else:
self.simple_redistribute_cards(copy_game, copy_remaining_cards)
return copy_game
def reset(self):
self.seen_cards = []
self.freeze_cards = []
self.transfer_cards = {}
self.expose = False
self.proactive_mode = set()
self.void_info = {0: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False},
1: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False},
2: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False},
3: {Suit.spades: False, Suit.hearts: False, Suit.diamonds: False, Suit.clubs: False}}
self.remaining_cards = set(Deck().cards)
self.num_hand_cards = {0: 13, 1: 13, 2: 13, 3: 13}
class StupidPlayer(Player):
def __init__(self, verbose=False):
super(StupidPlayer, self).__init__(verbose=verbose)
def pass_cards(self, hand, round_idx):
cards = []
for card in hand:
if len(cards) == 3:
break
elif self.is_pass_card(card):
continue
else:
cards.append(card)
return cards
def play_card(self, game):
hand = game._player_hands[game.current_player_idx]
# Play first card that is valid
shuffle(hand)
for card in hand:
if is_card_valid(hand, game.trick, card, game.trick_nr, game.is_heart_broken):
return card
game.verbose = True
game.print_game_status()
raise AssertionError('Apparently there is no valid card that can be played. This should not happen.')
class SimplePlayer(Player):
"""
This player has a notion of a card being undesirable.
It will try to get rid of the most undesirable cards while trying not to win a trick.
"""
def __init__(self, verbose=False):
super(SimplePlayer, self).__init__(verbose=verbose)
def pass_cards(self, hand, round_idx):
hand.sort(key=self.undesirability, reverse=True)
cards = []
for card in hand:
if len(cards) == 3:
break
elif self.is_pass_card(card):
continue
else:
cards.append(card)
return cards
def play_card(self, game):
hand = game._player_hands[game.current_player_idx]
# Lead with a low card
if not game.trick:
card = None
if game.trick_nr == 0:
for card in hand:
if card.suit == Suit.clubs and card.rank == Rank.two:
break
else:
hand.sort(key=lambda card:
100 if not game.is_heart_broken and card.suit == Suit.hearts else
card.rank.value)
try:
card = hand[0]
except IndexError:
print(hand)
raise
return card
hand.sort(key=self.undesirability, reverse=True)
#self.say('Hand: {}', hand)
#self.say('Trick so far: {}', game.trick)
# Safe cards are cards which will not result in winning the trick
leading_suit, max_rank_in_leading_suit = self.get_leading_suit_and_rank(game.trick)
valid_cards = self.get_valid_cards(hand, game)
safe_cards = [card for card in valid_cards
if card.suit != leading_suit or card.rank <= max_rank_in_leading_suit]
self.say('Valid cards: {}, Safe cards: {}', valid_cards, safe_cards)
if len(safe_cards) > 0:
return safe_cards[0]
else:
queen_of_spades = Card(Suit.spades, Rank.queen)
# Don't try to take a trick by laying the queen of spades
if valid_cards[0] == queen_of_spades and len(valid_cards) > 1:
return valid_cards[1]
else:
return valid_cards[0]