forked from google-deepmind/hanabi-learning-environment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rl_env.py
705 lines (623 loc) · 27.7 KB
/
rl_env.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""RL environment for Hanabi, using an API similar to OpenAI Gym."""
from __future__ import absolute_import
from __future__ import division
import pyhanabi
from pyhanabi import color_char_to_idx
MOVE_TYPES = [_.name for _ in pyhanabi.HanabiMoveType]
#-------------------------------------------------------------------------------
# Environment API
#-------------------------------------------------------------------------------
class Environment(object):
"""Abtract Environment interface.
All concrete implementations of an environment should derive from this
interface and implement the method stubs.
"""
def reset(self, config):
"""Reset the environment with a new config.
Signals environment handlers to reset and restart the environment using
a config dict.
Args:
config: dict, specifying the parameters of the environment to be
generated.
Returns:
observation: A dict containing the full observation state.
"""
raise NotImplementedError("Not implemented in Abstract Base class")
def step(self, action):
"""Take one step in the game.
Args:
action: dict, mapping to an action taken by an agent.
Returns:
observation: dict, Containing full observation state.
reward: float, Reward obtained from taking the action.
done: bool, Whether the game is done.
info: dict, Optional debugging information.
Raises:
AssertionError: When an illegal action is provided.
"""
raise NotImplementedError("Not implemented in Abstract Base class")
class HanabiEnv(Environment):
"""RL interface to a Hanabi environment.
```python
environment = rl_env.make()
config = { 'players': 5 }
observation = environment.reset(config)
while not done:
# Agent takes action
action = ...
# Environment take a step
observation, reward, done, info = environment.step(action)
```
"""
def __init__(self, config):
r"""Creates an environment with the given game configuration.
Args:
config: dict, With parameters for the game. Config takes the following
keys and values.
- colors: int, Number of colors \in [2,5].
- ranks: int, Number of ranks \in [2,5].
- players: int, Number of players \in [2,5].
- hand_size: int, Hand size \in [4,5].
- max_information_tokens: int, Number of information tokens (>=0).
- max_life_tokens: int, Number of life tokens (>=1).
- observation_type: int.
0: Minimal observation.
1: First-order common knowledge observation.
- seed: int, Random seed.
- random_start_player: bool, Random start player.
"""
assert isinstance(config, dict), "Expected config to be of type dict."
self.game = pyhanabi.HanabiGame(config)
self.observation_encoder = pyhanabi.ObservationEncoder(
self.game, pyhanabi.ObservationEncoderType.CANONICAL)
self.players = self.game.num_players()
def reset(self):
r"""Resets the environment for a new game.
Returns:
observation: dict, containing the full observation about the game at the
current step. *WARNING* This observation contains all the hands of the
players and should not be passed to the agents.
An example observation:
{'current_player': 0,
'player_observations': [{'current_player': 0,
'current_player_offset': 0,
'deck_size': 40,
'discard_pile': [],
'fireworks': {'B': 0,
'G': 0,
'R': 0,
'W': 0,
'Y': 0},
'information_tokens': 8,
'legal_moves': [{'action_type': 'PLAY',
'card_index': 0},
{'action_type': 'PLAY',
'card_index': 1},
{'action_type': 'PLAY',
'card_index': 2},
{'action_type': 'PLAY',
'card_index': 3},
{'action_type': 'PLAY',
'card_index': 4},
{'action_type':
'REVEAL_COLOR',
'color': 'R',
'target_offset': 1},
{'action_type':
'REVEAL_COLOR',
'color': 'G',
'target_offset': 1},
{'action_type':
'REVEAL_COLOR',
'color': 'B',
'target_offset': 1},
{'action_type': 'REVEAL_RANK',
'rank': 0,
'target_offset': 1},
{'action_type': 'REVEAL_RANK',
'rank': 1,
'target_offset': 1},
{'action_type': 'REVEAL_RANK',
'rank': 2,
'target_offset': 1}],
'life_tokens': 3,
'observed_hands': [[{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1}],
[{'color': 'G', 'rank': 2},
{'color': 'R', 'rank': 0},
{'color': 'R', 'rank': 1},
{'color': 'B', 'rank': 0},
{'color': 'R', 'rank':
1}]],
'num_players': 2,
'vectorized': [ 0, 0, 1, ... ]},
{'current_player': 0,
'current_player_offset': 1,
'deck_size': 40,
'discard_pile': [],
'fireworks': {'B': 0,
'G': 0,
'R': 0,
'W': 0,
'Y': 0},
'information_tokens': 8,
'legal_moves': [],
'life_tokens': 3,
'observed_hands': [[{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1},
{'color': None, 'rank':
-1}],
[{'color': 'W', 'rank': 2},
{'color': 'Y', 'rank': 4},
{'color': 'Y', 'rank': 2},
{'color': 'G', 'rank': 0},
{'color': 'W', 'rank':
1}]],
'num_players': 2,
'vectorized': [ 0, 0, 1, ... ]}]}
"""
self.state = self.game.new_initial_state()
while self.state.cur_player() == pyhanabi.CHANCE_PLAYER_ID:
self.state.deal_random_card()
obs = self._make_observation_all_players()
obs["current_player"] = self.state.cur_player()
return obs
def vectorized_observation_shape(self):
"""Returns the shape of the vectorized observation.
Returns:
A list of integer dimensions describing the observation shape.
"""
return self.observation_encoder.shape()
def num_moves(self):
"""Returns the total number of moves in this game (legal or not).
Returns:
Integer, number of moves.
"""
return self.game.max_moves()
def step(self, action):
"""Take one step in the game.
Args:
action: dict, mapping to a legal action taken by an agent. The following
actions are supported:
- { 'action_type': 'PLAY', 'card_index': int }
- { 'action_type': 'DISCARD', 'card_index': int }
- {
'action_type': 'REVEAL_COLOR',
'color': str,
'target_offset': int >=0
}
- {
'action_type': 'REVEAL_RANK',
'rank': str,
'target_offset': int >=0
}
Alternatively, action may be an int in range [0, num_moves()).
Returns:
observation: dict, containing the full observation about the game at the
current step. *WARNING* This observation contains all the hands of the
players and should not be passed to the agents.
An example observation:
{'current_player': 0,
'player_observations': [{'current_player': 0,
'current_player_offset': 0,
'deck_size': 40,
'discard_pile': [],
'fireworks': {'B': 0,
'G': 0,
'R': 0,
'W': 0,
'Y': 0},
'information_tokens': 8,
'legal_moves': [{'action_type': 'PLAY',
'card_index': 0},
{'action_type': 'PLAY',
'card_index': 1},
{'action_type': 'PLAY',
'card_index': 2},
{'action_type': 'PLAY',
'card_index': 3},
{'action_type': 'PLAY',
'card_index': 4},
{'action_type': 'REVEAL_COLOR',
'color': 'R',
'target_offset': 1},
{'action_type': 'REVEAL_COLOR',
'color': 'G',
'target_offset': 1},
{'action_type': 'REVEAL_COLOR',
'color': 'B',
'target_offset': 1},
{'action_type': 'REVEAL_RANK',
'rank': 0,
'target_offset': 1},
{'action_type': 'REVEAL_RANK',
'rank': 1,
'target_offset': 1},
{'action_type': 'REVEAL_RANK',
'rank': 2,
'target_offset': 1}],
'life_tokens': 3,
'observed_hands': [[{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1}],
[{'color': 'G', 'rank': 2},
{'color': 'R', 'rank': 0},
{'color': 'R', 'rank': 1},
{'color': 'B', 'rank': 0},
{'color': 'R', 'rank': 1}]],
'num_players': 2,
'vectorized': [ 0, 0, 1, ... ]},
{'current_player': 0,
'current_player_offset': 1,
'deck_size': 40,
'discard_pile': [],
'fireworks': {'B': 0,
'G': 0,
'R': 0,
'W': 0,
'Y': 0},
'information_tokens': 8,
'legal_moves': [],
'life_tokens': 3,
'observed_hands': [[{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1}],
[{'color': 'W', 'rank': 2},
{'color': 'Y', 'rank': 4},
{'color': 'Y', 'rank': 2},
{'color': 'G', 'rank': 0},
{'color': 'W', 'rank': 1}]],
'num_players': 2,
'vectorized': [ 0, 0, 1, ... ]}]}
reward: float, Reward obtained from taking the action.
done: bool, Whether the game is done.
info: dict, Optional debugging information.
Raises:
AssertionError: When an illegal action is provided.
"""
if isinstance(action, dict):
# Convert dict action HanabiMove
action = self._build_move(action)
elif isinstance(action, int):
# Convert int action into a Hanabi move.
action = self.game.get_move(action)
else:
raise ValueError("Expected action as dict or int, got: {}".format(
action))
last_score = self.state.score()
# Apply the action to the state.
self.state.apply_move(action)
while self.state.cur_player() == pyhanabi.CHANCE_PLAYER_ID:
self.state.deal_random_card()
observation = self._make_observation_all_players()
done = self.state.is_terminal()
# Reward is score differential. May be large and negative at game end.
reward = self.state.score() - last_score
info = {}
return (observation, reward, done, info)
def _make_observation_all_players(self):
"""Make observation for all players.
Returns:
dict, containing observations for all players.
"""
obs = {}
player_observations = [self._extract_dict_from_backend(
player_id, self.state.observation(player_id))
for player_id in range(self.players)] # pylint: disable=bad-continuation
obs["player_observations"] = player_observations
obs["current_player"] = self.state.cur_player()
return obs
def _extract_dict_from_backend(self, player_id, observation):
"""Extract a dict of features from an observation from the backend.
Args:
player_id: Int, player from whose perspective we generate the observation.
observation: A `pyhanabi.HanabiObservation` object.
Returns:
obs_dict: dict, mapping from HanabiObservation to a dict.
"""
obs_dict = {}
obs_dict["current_player"] = self.state.cur_player()
obs_dict["current_player_offset"] = observation.cur_player_offset()
obs_dict["life_tokens"] = observation.life_tokens()
obs_dict["information_tokens"] = observation.information_tokens()
obs_dict["num_players"] = observation.num_players()
obs_dict["deck_size"] = observation.deck_size()
obs_dict["fireworks"] = {}
fireworks = self.state.fireworks()
for color, firework in zip(pyhanabi.COLOR_CHAR, fireworks):
obs_dict["fireworks"][color] = firework
obs_dict["legal_moves"] = []
obs_dict["legal_moves_as_int"] = []
for move in observation.legal_moves():
obs_dict["legal_moves"].append(move.to_dict())
obs_dict["legal_moves_as_int"].append(self.game.get_move_uid(move))
obs_dict["observed_hands"] = []
for player_hand in observation.observed_hands():
cards = [card.to_dict() for card in player_hand]
obs_dict["observed_hands"].append(cards)
obs_dict["discard_pile"] = [
card.to_dict() for card in observation.discard_pile()
]
# Return hints received.
obs_dict["card_knowledge"] = []
for player_hints in observation.card_knowledge():
player_hints_as_dicts = []
for hint in player_hints:
hint_d = {}
if hint.color() is not None:
hint_d["color"] = pyhanabi.color_idx_to_char(hint.color())
else:
hint_d["color"] = None
hint_d["rank"] = hint.rank()
player_hints_as_dicts.append(hint_d)
obs_dict["card_knowledge"].append(player_hints_as_dicts)
# ipdb.set_trace()
obs_dict["vectorized"] = self.observation_encoder.encode(observation)
obs_dict["pyhanabi"] = observation
return obs_dict
def _build_move(self, action):
"""Build a move from an action dict.
Args:
action: dict, mapping to a legal action taken by an agent. The following
actions are supported:
- { 'action_type': 'PLAY', 'card_index': int }
- { 'action_type': 'DISCARD', 'card_index': int }
- {
'action_type': 'REVEAL_COLOR',
'color': str,
'target_offset': int >=0
}
- {
'action_type': 'REVEAL_RANK',
'rank': str,
'target_offset': int >=0
}
Returns:
move: A `HanabiMove` object constructed from action.
Raises:
ValueError: Unknown action type.
"""
assert isinstance(action, dict), "Expected dict, got: {}".format(action)
assert "action_type" in action, ("Action should contain `action_type`. "
"action: {}").format(action)
action_type = action["action_type"]
assert (action_type in MOVE_TYPES), (
"action_type: {} should be one of: {}".format(action_type, MOVE_TYPES))
if action_type == "PLAY":
card_index = action["card_index"]
move = pyhanabi.HanabiMove.get_play_move(card_index=card_index)
elif action_type == "DISCARD":
card_index = action["card_index"]
move = pyhanabi.HanabiMove.get_discard_move(card_index=card_index)
elif action_type == "REVEAL_RANK":
target_offset = action["target_offset"]
rank = action["rank"]
move = pyhanabi.HanabiMove.get_reveal_rank_move(
target_offset=target_offset, rank=rank)
elif action_type == "REVEAL_COLOR":
target_offset = action["target_offset"]
assert isinstance(action["color"], str)
color = color_char_to_idx(action["color"])
move = pyhanabi.HanabiMove.get_reveal_color_move(
target_offset=target_offset, color=color)
else:
raise ValueError("Unknown action_type: {}".format(action_type))
legal_moves = self.state.legal_moves()
assert (str(move) in map(
str,
legal_moves)), "Illegal action: {}. Move should be one of : {}".format(
move, legal_moves)
return move
def make(environment_name="Hanabi-Full", num_players=2, pyhanabi_path=None):
"""Make an environment.
Args:
environment_name: str, Name of the environment to instantiate.
num_players: int, Number of players in this game.
pyhanabi_path: str, absolute path to header files for c code linkage.
Returns:
env: An `Environment` object.
Raises:
ValueError: Unknown environment name.
"""
if pyhanabi_path is not None:
prefixes=(pyhanabi_path,)
assert pyhanabi.try_cdef(prefixes=prefixes), "cdef failed to load"
assert pyhanabi.try_load(prefixes=prefixes), "library failed to load"
if (environment_name == "Hanabi-Full" or
environment_name == "Hanabi-Full-CardKnowledge"):
return HanabiEnv(
config={
"colors":
5,
"ranks":
5,
"players":
num_players,
"max_information_tokens":
8,
"max_life_tokens":
3,
"observation_type":
pyhanabi.AgentObservationType.CARD_KNOWLEDGE.value
})
elif environment_name == "Hanabi-Full-Minimal":
return HanabiEnv(
config={
"colors": 5,
"ranks": 5,
"players": num_players,
"max_information_tokens": 8,
"max_life_tokens": 3,
"observation_type": pyhanabi.AgentObservationType.MINIMAL.value
})
elif environment_name == "Hanabi-Small":
return HanabiEnv(
config={
"colors":
2,
"ranks":
5,
"players":
num_players,
"hand_size":
2,
"max_information_tokens":
3,
"max_life_tokens":
1,
"observation_type":
pyhanabi.AgentObservationType.CARD_KNOWLEDGE.value
})
elif environment_name == "Hanabi-Very-Small":
return HanabiEnv(
config={
"colors":
1,
"ranks":
5,
"players":
num_players,
"hand_size":
2,
"max_information_tokens":
3,
"max_life_tokens":
1,
"observation_type":
pyhanabi.AgentObservationType.CARD_KNOWLEDGE.value
})
else:
raise ValueError("Unknown environment {}".format(environment_name))
#-------------------------------------------------------------------------------
# Hanabi Agent API
#-------------------------------------------------------------------------------
class Agent(object):
"""Agent interface.
All concrete implementations of an Agent should derive from this interface
and implement the method stubs.
```python
class MyAgent(Agent):
...
agents = [MyAgent(config) for _ in range(players)]
while not done:
...
for agent_id, agent in enumerate(agents):
action = agent.act(observation)
if obs.current_player == agent_id:
assert action is not None
else
assert action is None
...
```
"""
def __init__(self, config, *args, **kwargs):
r"""Initialize the agent.
Args:
config: dict, With parameters for the game. Config takes the following
keys and values.
- colors: int, Number of colors \in [2,5].
- ranks: int, Number of ranks \in [2,5].
- players: int, Number of players \in [2,5].
- hand_size: int, Hand size \in [4,5].
- max_information_tokens: int, Number of information tokens (>=0)
- max_life_tokens: int, Number of life tokens (>=0)
- seed: int, Random seed.
- random_start_player: bool, Random start player.
*args: Optional arguments
**kwargs: Optional keyword arguments.
Raises:
AgentError: Custom exceptions.
"""
raise NotImplementedError("Not implemeneted in abstract base class.")
def reset(self, config):
r"""Reset the agent with a new config.
Signals agent to reset and restart using a config dict.
Args:
config: dict, With parameters for the game. Config takes the following
keys and values.
- colors: int, Number of colors \in [2,5].
- ranks: int, Number of ranks \in [2,5].
- players: int, Number of players \in [2,5].
- hand_size: int, Hand size \in [4,5].
- max_information_tokens: int, Number of information tokens (>=0)
- max_life_tokens: int, Number of life tokens (>=0)
- seed: int, Random seed.
- random_start_player: bool, Random start player.
"""
raise NotImplementedError("Not implemeneted in abstract base class.")
def act(self, observation):
"""Act based on an observation.
Args:
observation: dict, containing observation from the view of this agent.
An example:
{'current_player': 0,
'current_player_offset': 1,
'deck_size': 40,
'discard_pile': [],
'fireworks': {'B': 0,
'G': 0,
'R': 0,
'W': 0,
'Y': 0},
'information_tokens': 8,
'legal_moves': [],
'life_tokens': 3,
'observed_hands': [[{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1},
{'color': None, 'rank': -1}],
[{'color': 'W', 'rank': 2},
{'color': 'Y', 'rank': 4},
{'color': 'Y', 'rank': 2},
{'color': 'G', 'rank': 0},
{'color': 'W', 'rank': 1}]],
'num_players': 2}]}
Returns:
action: dict, mapping to a legal action taken by this agent. The following
actions are supported:
- { 'action_type': 'PLAY', 'card_index': int }
- { 'action_type': 'DISCARD', 'card_index': int }
- {
'action_type': 'REVEAL_COLOR',
'color': str,
'target_offset': int >=0
}
- {
'action_type': 'REVEAL_RANK',
'rank': str,
'target_offset': int >=0
}
"""
raise NotImplementedError("Not implemented in Abstract Base class")