summaryrefslogtreecommitdiff
path: root/bcdd/PBNBoard.py
blob: 4d8f72fef852d5d7dda46653a62402eae3640830 (plain)
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
import re

from .BCalcWrapper import BCalcWrapper
from .Exceptions import FieldNotFoundException


class PBNField(object):

    def __init__(self, key=None, value=None, raw_data=None):
        self.key = key
        self.value = value
        self.raw_field = '[%s "%s"]' % (self.key, str(self.value)) \
                         if self.key is not None else raw_data

class PBNBoard(object):

    line_pattern = re.compile(r'\[(.*) "(.*)"\]')
    ability_pattern = re.compile(r'\b([NESW]):([0-9A-D]{5})\b')
    optimum_result_table_pattern = re.compile(
        r'^([NESW])\s+([CDHSN])T?\s+(\d+)$')

    def __init__(self, lines):
        self._has_optimum_result_table = None
        self._has_ability = None
        self.fields = []
        for line in lines:
            field = PBNField(raw_data=line)
            line_parse = self.line_pattern.match(line)
            if line_parse:
                field.key = line_parse.group(1)
                field.value = line_parse.group(2)
            self.fields.append(field)

    def has_field(self, key):
        for field in self.fields:
            if key == field.key:
                return True
        return False

    def get_field(self, key):
        for field in self.fields:
            if key == field.key:
                return field.value
        raise FieldNotFoundException(key + ' field not found')

    def delete_field(self, key):
        to_remove = []
        for field in self.fields:
            if key == field.key:
                to_remove.append(field)
        for remove in to_remove:
            self.fields.remove(remove)

    def get_event(self):
        return self.get_field('Event')

    def write_event(self, name):
        for i in range(0, len(self.fields)):
            if 'Board' == self.fields[i].key:
                self.fields.insert(i, PBNField(key='Event', value=name))
                break

    def get_layout(self):
        return self.get_field('Deal')

    def get_number(self):
        return self.get_field('Board')

    def get_vulnerable(self):
        return self.get_field('Vulnerable')

    def get_dealer(self):
        return self.get_field('Dealer')

    def validate_ability(self, ability):
        matches = self.ability_pattern.match(ability)
        if not matches:
            self._has_ability = False
            raise DDTableInvalidException('Invalid Ability line: ' + ability)
        players = []
        for match in matches:
            if match.group(1) in players:
                self._has_ability = False
                raise DDTableInvalidException(
                    'Duplicate entry in Ability: ' + match.group(0))
            else:
                players.append(match.group(1))
        self._has_ability = False
        return matches

    def get_ability(self):
        return self.get_field('Ability')

    def delete_ability(self):
        self.delete_field('Ability')

    def write_ability(self, dd_table):
        sb = ''
        for i in range(0, 4):
            sb += BCalcWrapper.PLAYERS[i]
            sb += ':'
            sb += ''.join(['%X' % (j) for j in dd_table[i]])[::-1]
            sb += ' '
        self.fields.append(PBNField(key='Ability', value=sb.strip()))

    def get_minimax(self):
        return self.get_field('Minimax')

    def delete_minimax(self):
        self.delete_field('Minimax')

    def write_minimax(self, contract):
        minimax = '7NS0' if contract.score == 0 \
                  else '%d%s%s%s%d' % (
                          contract.level,
                          contract.denomination,
                          'D' if contract.doubled else '',
                          contract.declarer,
                          contract.score)
        self.fields.append(PBNField(key='Minimax', value=minimax))

    def get_optimum_score(self):
        return self.get_field('OptimumScore')

    def delete_optimum_score(self):
        self.delete_field('OptimumScore')

    def write_optimum_score(self, contract):
        self.fields.append(
            PBNField(key='OptimumScore',
                     value='NS %d' % (contract.score)))

    def get_optimum_result(self):
        return self.get_field('OptimumResult')

    def validate_optimum_result_table(self, table):
        matches = []
        duplicates = []
        for line in table:
            match = self.optimum_result_table_pattern.match(line)
            if not match:
                self._has_optimum_result_table = False
                raise DDTableInvalidException(
                    'Invalid OptimumResultTable line: ' + line)
            position = match.group(1) + ' - ' + match.group(2)
            if position in duplicates:
                self._has_optimum_result_table = False
                raise DDTableInvalidException(
                    'Duplicate OptimumResultTable line: ' + line)
            else:
                duplicates.append(position)
            matches.append(match)
        self._has_optimum_result_table = True
        return matches

    def get_optimum_result_table(self):
        field_found = False
        result = []
        for field in self.fields:
            if 'OptimumResultTable' == field.key:
                field_found = True
            else:
                if field_found:
                    if field.key is None:
                        result.append(field.raw_field)
                    else:
                        break
        if not field_found:
            self._has_optimum_result_table = False
            raise FieldNotFoundException('OptimumResultTable field not found')
        return result

    def delete_optimum_result_table(self):
        field_found = False
        to_remove = []
        for field in self.fields:
            if 'OptimumResultTable' == field.key:
                field_found = True
                to_remove.append(field)
            else:
                if field_found:
                    if field.key is None:
                        to_remove.append(field)
                    else:
                        break
        for remove in to_remove:
            self.fields.remove(remove)

    def write_optimum_result_table(self, dd_table):
        self.fields.append(PBNField(
            key='OptimumResultTable',
            value=r'Declarer;Denomination\2R;Result\2R'))
        for i in range(0, 4):
            for j in range(0, 5):
                self.fields.append(PBNField(
                    raw_data='%s %s%s %d' % (
                        BCalcWrapper.PLAYERS[i],
                        BCalcWrapper.DENOMINATIONS[j],
                        'T' if BCalcWrapper.DENOMINATIONS[j] == 'N' else '',
                        dd_table[i][j])))

    def save_par_contract(self, contract):
        # we're not writing DDS custom fields, just parse them
        self.delete_optimum_score()
        self.write_optimum_score(contract)
        self.delete_minimax()
        self.write_minimax(contract)

    def save_dd_table(self, dd_table):
        if self._has_optimum_result_table is None:
            try:
                optimum_result_table = self.validate_optimum_result_table(
                    self.get_optimum_result_table())
                self._has_optimum_result_table = True
            except FieldNotFoundException:
                self._has_optimum_result_table = False
        if not self._has_optimum_result_table:
            self.delete_optimum_result_table()
            self.write_optimum_result_table(dd_table)
        if self._has_ability is None:
            try:
                ability = self.validate_ability(
                    self.get_ability())
                self._has_ability = True
            except FieldNotFoundException:
                self._has_ability = False
        if not self._has_ability:
            self.delete_ability()
            self.write_ability(dd_table)