forked from datamllab/rlcard
-
Notifications
You must be signed in to change notification settings - Fork 1
/
doudizhu_rule_models.py
180 lines (162 loc) · 6.17 KB
/
doudizhu_rule_models.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
''' Dou Dizhu rule models
'''
import numpy as np
import rlcard
from rlcard.games.doudizhu.utils import CARD_TYPE, INDEX
from rlcard.models.model import Model
class DouDizhuRuleAgentV1(object):
''' Dou Dizhu Rule agent version 1
'''
def __init__(self):
self.use_raw = True
def step(self, state):
''' Predict the action given raw state. A naive rule.
Args:
state (dict): Raw state from the game
Returns:
action (str): Predicted action
'''
state = state['raw_obs']
trace = state['trace']
# the rule of leading round
if len(trace) == 0 or (len(trace) >= 3 and trace[-1][1] == 'pass' and trace[-2][1] == 'pass'):
comb = self.combine_cards(state['current_hand'])
min_card = state['current_hand'][0]
for _, actions in comb.items():
for action in actions:
if min_card in action:
return action
# the rule of following cards
else:
target = state['trace'][-1][-1]
target_player = state['trace'][-1][0]
if target == 'pass':
target = state['trace'][-2][-1]
target_player = state['trace'][-1][0]
the_type = CARD_TYPE[0][target][0][0]
chosen_action = ''
rank = 1000
for action in state['actions']:
if action != 'pass' and the_type == CARD_TYPE[0][action][0][0]:
if int(CARD_TYPE[0][action][0][1]) < rank:
rank = int(CARD_TYPE[0][action][0][1])
chosen_action = action
if chosen_action != '':
return chosen_action
landlord = state['landlord']
if target_player != landlord and state['self'] != landlord:
return 'pass'
return np.random.choice(state['actions'])
def eval_step(self, state):
''' Step for evaluation. The same to step
'''
return self.step(state), []
def combine_cards(self, hand):
'''Get optimal combinations of cards in hand
'''
comb = {'rocket': [], 'bomb': [], 'trio': [], 'trio_chain': [],
'solo_chain': [], 'pair_chain': [], 'pair': [], 'solo': []}
# 1. pick rocket
if hand[-2:] == 'BR':
comb['rocket'].append('BR')
hand = hand[:-2]
# 2. pick bomb
hand_cp = hand
for index in range(len(hand_cp) - 3):
if hand_cp[index] == hand_cp[index+3]:
bomb = hand_cp[index: index+4]
comb['bomb'].append(bomb)
hand = hand.replace(bomb, '')
# 3. pick trio and trio_chain
hand_cp = hand
for index in range(len(hand_cp) - 2):
if hand_cp[index] == hand_cp[index+2]:
trio = hand_cp[index: index+3]
if len(comb['trio']) > 0 and INDEX[trio[-1]] < 12 and (INDEX[trio[-1]]-1) == INDEX[comb['trio'][-1][-1]]:
comb['trio'][-1] += trio
else:
comb['trio'].append(trio)
hand = hand.replace(trio, '')
only_trio = []
only_trio_chain = []
for trio in comb['trio']:
if len(trio) == 3:
only_trio.append(trio)
else:
only_trio_chain.append(trio)
comb['trio'] = only_trio
comb['trio_chain'] = only_trio_chain
# 4. pick solo chain
hand_list = self.card_str2list(hand)
chains, hand_list = self.pick_chain(hand_list, 1)
comb['solo_chain'] = chains
# 5. pick par_chain
chains, hand_list = self.pick_chain(hand_list, 2)
comb['pair_chain'] = chains
hand = self.list2card_str(hand_list)
# 6. pick pair and solo
index = 0
while index < len(hand) - 1:
if hand[index] == hand[index+1]:
comb['pair'].append(hand[index] + hand[index+1])
index += 2
else:
comb['solo'].append(hand[index])
index += 1
if index == (len(hand) - 1):
comb['solo'].append(hand[index])
return comb
@staticmethod
def card_str2list(hand):
hand_list = [0 for _ in range(15)]
for card in hand:
hand_list[INDEX[card]] += 1
return hand_list
@staticmethod
def list2card_str(hand_list):
card_str = ''
cards = [card for card in INDEX]
for index, count in enumerate(hand_list):
card_str += cards[index] * count
return card_str
@staticmethod
def pick_chain(hand_list, count):
chains = []
str_card = [card for card in INDEX]
hand_list = [str(card) for card in hand_list]
hand = ''.join(hand_list[:12])
chain_list = hand.split('0')
add = 0
for index, chain in enumerate(chain_list):
if len(chain) > 0:
if len(chain) >= 5:
start = index + add
min_count = int(min(chain)) // count
if min_count != 0:
str_chain = ''
for num in range(len(chain)):
str_chain += str_card[start+num]
hand_list[start+num] = int(hand_list[start+num]) - int(min(chain))
for _ in range(min_count):
chains.append(str_chain)
add += len(chain)
hand_list = [int(card) for card in hand_list]
return (chains, hand_list)
class DouDizhuRuleModelV1(Model):
''' Dou Dizhu Rule Model version 1
'''
def __init__(self):
''' Load pretrained model
'''
env = rlcard.make('doudizhu')
rule_agent = DouDizhuRuleAgentV1()
self.rule_agents = [rule_agent for _ in range(env.num_players)]
@property
def agents(self):
''' Get a list of agents for each position in a the game
Returns:
agents (list): A list of agents
Note: Each agent should be just like RL agent with step and eval_step
functioning well.
'''
return self.rule_agents