bridgeobjects 0.1.32__tar.gz → 0.1.33__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/PKG-INFO +6 -2
  2. bridgeobjects-0.1.33/pyproject.toml +24 -0
  3. bridgeobjects-0.1.33/pyproject.toml.orig +29 -0
  4. bridgeobjects-0.1.33/src/bridgeobjects/_create_pbn_string.py +212 -0
  5. bridgeobjects-0.1.33/src/bridgeobjects/_create_rbn_string.py +76 -0
  6. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/_parse_lin_string.py +0 -3
  7. bridgeobjects-0.1.33/src/bridgeobjects/_parse_pbn_string.py +323 -0
  8. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/_parse_rbn_string.py +75 -70
  9. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/board.py +135 -98
  10. bridgeobjects-0.1.33/src/bridgeobjects/constants.py +402 -0
  11. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/contract.py +2 -4
  12. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/event.py +34 -24
  13. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/file_operations.py +11 -26
  14. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/hand.py +169 -120
  15. bridgeobjects-0.1.33/src/bridgeobjects/tests/__init__.py +0 -0
  16. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_auctions.py +101 -0
  17. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_boards.py +580 -0
  18. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_calls.py +242 -0
  19. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_cards.py +185 -0
  20. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_contracts.py +151 -0
  21. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/lin_input_file_1.lin +33 -0
  22. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/pbn_auction_1.pbn +47 -0
  23. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/pbn_auction_2.pbn +47 -0
  24. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/pbn_input_3.pbn +120 -0
  25. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/pbn_input_file_1.pbn +1287 -0
  26. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/pbn_output_file_1.pbn +22 -0
  27. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/rbn_input_file_1.rbn +24 -0
  28. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_data/rbn_output_file_1.rbn +124 -0
  29. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_denominations.py +139 -0
  30. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_events.py +66 -0
  31. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_hands.py +946 -0
  32. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_lin.py +218 -0
  33. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_pbn.py +237 -0
  34. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_rbn.py +218 -0
  35. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_scores.py +460 -0
  36. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_suits.py +134 -0
  37. bridgeobjects-0.1.33/src/bridgeobjects/tests/test_trick.py +61 -0
  38. bridgeobjects-0.1.32/pyproject.toml +0 -15
  39. bridgeobjects-0.1.32/src/bridgeobjects/_create_pbn_string.py +0 -283
  40. bridgeobjects-0.1.32/src/bridgeobjects/_parse_pbn_string.py +0 -300
  41. bridgeobjects-0.1.32/src/bridgeobjects/constants.py +0 -271
  42. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/README.md +0 -0
  43. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/__init__.py +0 -0
  44. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/_file_constants.py +0 -0
  45. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/_version.py +0 -0
  46. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/auction.py +0 -0
  47. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/call.py +0 -0
  48. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/card.py +0 -0
  49. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/denomination.py +0 -0
  50. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/suit.py +0 -0
  51. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/suit_base.py +0 -0
  52. {bridgeobjects-0.1.32 → bridgeobjects-0.1.33}/src/bridgeobjects/trick.py +0 -0
@@ -1,9 +1,13 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: bridgeobjects
3
- Version: 0.1.32
4
- Summary: A collection of modules that allows the user to utilise objects used in bridge games, for example, a board or a contract.
3
+ Version: 0.1.33
4
+ Summary: Objects used in bridge games, for example, board, hand, bid or a contract.
5
5
  Author: Jeff
6
6
  Author-email: Jeff <<jeffwatkins2000@gmail.com>>
7
+ Requires-Dist: iniconfig>=2.1.0
8
+ Requires-Dist: packaging>=25.0
9
+ Requires-Dist: pluggy>=1.6.0
10
+ Requires-Dist: pygments>=2.19.2
7
11
  Requires-Python: ==3.13.*
8
12
  Description-Content-Type: text/markdown
9
13
 
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "bridgeobjects"
3
+ version = "0.1.33"
4
+ requires-python = "==3.13.*"
5
+ description = "Objects used in bridge games, for example, board, hand, bid or a contract."
6
+ readme = "README.md"
7
+ include = ["HISTORY.md"]
8
+ dependencies = [
9
+ "iniconfig>=2.1.0",
10
+ "packaging>=25.0",
11
+ "pluggy>=1.6.0",
12
+ "pygments>=2.19.2",
13
+ ]
14
+
15
+ [[project.authors]]
16
+ name = "Jeff"
17
+ email = "<jeffwatkins2000@gmail.com>"
18
+
19
+ [dependency-groups]
20
+ dev = ["pytest"]
21
+
22
+ [build-system]
23
+ requires = ["uv-build"]
24
+ build-backend = "uv_build"
@@ -0,0 +1,29 @@
1
+ [project]
2
+ name = "bridgeobjects"
3
+ version = "0.1.33"
4
+ requires-python = "==3.13.*"
5
+ description = "Objects used in bridge games, for example, board, hand, bid or a contract."
6
+ authors = [
7
+ { name = "Jeff", email = "<jeffwatkins2000@gmail.com>" },
8
+ ]
9
+ readme = "README.md"
10
+ include = [
11
+ "HISTORY.md",
12
+ ]
13
+ dependencies = [
14
+ "iniconfig>=2.1.0",
15
+ "packaging>=25.0",
16
+ "pluggy>=1.6.0",
17
+ "pygments>=2.19.2",
18
+ ]
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "pytest",
23
+ ]
24
+
25
+ [build-system]
26
+ requires = [
27
+ "uv-build",
28
+ ]
29
+ build-backend = "uv_build"
@@ -0,0 +1,212 @@
1
+ """Processes to create a pbn event."""
2
+ from typing import TYPE_CHECKING
3
+ if TYPE_CHECKING:
4
+ from .board import Board
5
+
6
+ from .event import Event
7
+ from .constants import SUIT_NAMES, RANKS, SEATS
8
+ from ._file_constants import (PBN_VULNERABILITY_CONVERSION,
9
+ PBN_CALL_CONVERSION,
10
+ PBN_VERSION_TEXT, PBN_FORMAT_TEXT,
11
+ PBN_CONTENT_TEXT, PBN_CREATOR_TEXT,
12
+ RBN_VERSION_TEXT, RBN_CREATOR_TEXT)
13
+
14
+ PBN_DATE_FORMAT = '%Y.%m.%d'
15
+
16
+
17
+ def create_pbn_event_list(events: list[Event], path: str = '') -> list[str]:
18
+ """Create a list of strings for events in pbn format."""
19
+ output = []
20
+ output = _append_pbn_header()
21
+ if path:
22
+ if not path.is_file():
23
+ output = _append_pbn_header()
24
+ else:
25
+ with open(path, 'r') as pbn_file:
26
+ for line in pbn_file.readlines():
27
+ line = line.replace('\n', '')
28
+ if len(line.replace(' ', '')) > 0 and line[1] != '%':
29
+ output = _append_pbn_header()
30
+ break
31
+ contents = pbn_file.readlines()
32
+ if len(contents) == 0:
33
+ output = _append_pbn_header()
34
+
35
+ for event in events:
36
+ output.extend(_create_pbn_event(event))
37
+ return output
38
+
39
+
40
+ def _create_pbn_event(event: Event) -> list[str]:
41
+ """Return an event as string in pbn format as a list."""
42
+ # output = [f'[Event "{event.name}"]', f'[Site "{event.site}"]']
43
+ # print(f"a {event=} {output}")
44
+ # if event.date:
45
+ # event_date = event.date.strftime(PBN_DATE_FORMAT)
46
+ # output.append(f'[Date "{event_date}"]')
47
+ # output.append('')
48
+ output = []
49
+ for board in event.boards:
50
+ output.extend(_create_pbn_board_list(board, event))
51
+ return output
52
+
53
+
54
+ def _append_pbn_header() -> list[str]:
55
+ """Create a list containing the pbn file header."""
56
+ return [
57
+ PBN_VERSION_TEXT,
58
+ PBN_FORMAT_TEXT,
59
+ PBN_CONTENT_TEXT,
60
+ PBN_CREATOR_TEXT,
61
+ '',
62
+ ]
63
+
64
+
65
+ def create_pbn_board(board: "Board") -> str:
66
+ board_list = _create_pbn_board_list(board)
67
+ return '\n'.join(board_list)
68
+
69
+
70
+ def _create_pbn_board_list(board: "Board", event: Event = None) -> list[str]:
71
+ """Return a board as a list of strings in pbn format."""
72
+ mandatory_fields = {
73
+ # Mandatory fields - in this order
74
+ 'Event': event,
75
+ 'Site': board.site,
76
+ 'Date': board.date.strftime(PBN_DATE_FORMAT),
77
+ 'Board': board.number,
78
+ 'West': board.west,
79
+ 'North': board.north,
80
+ 'East': board.east,
81
+ 'South': board.south,
82
+ 'Dealer': board.dealer,
83
+ 'Vulnerable': board.vulnerable.replace("Both", "All"),
84
+ 'Deal': f"{board.dealer}:{get_pbn_deal(board)}",
85
+ 'Scoring': '?',
86
+ 'Declarer': _question_from_null(board.contract.declarer),
87
+ 'Contract': _handle_contract(board),
88
+ 'Result': _question_from_null(board.result),
89
+
90
+ 'Auction': _create_pbn_auction(board),
91
+ 'Play': _create_pbn_play_section(board)
92
+ }
93
+
94
+ optional_fields = {
95
+ # Optional fields - alphabetically
96
+ 'DealId': board.deal_id,
97
+ 'Description': board.description,
98
+ # 'EventDate': board.event.date,
99
+ # 'Generator': board.generator,
100
+ # 'Tag': board.tag,
101
+ }
102
+
103
+ output = []
104
+ output.extend(
105
+ f'[{field} "{value}"]' for field, value in mandatory_fields.items()
106
+ )
107
+ output.extend(
108
+ f'[{field} "{value}"]'
109
+ for field, value in optional_fields.items() if value
110
+ )
111
+ output.append('')
112
+ return output
113
+
114
+
115
+ def _handle_contract(board: "Board") -> str:
116
+ if board.contract.declarer and board.contract.denomination:
117
+ denomination = board.contract.denomination.name
118
+ if result := board.optimum_result_table[board.contract.declarer][
119
+ denomination
120
+ ]:
121
+ board.result = result
122
+ return _question_from_null(board.contract.call.name)
123
+
124
+
125
+ def _question_from_null(value: str) -> str:
126
+ """Return a question mark if value is None or ''."""
127
+ return value or "?"
128
+
129
+
130
+ def get_pbn_deal(board: "Board", delimiter: str = ' ') -> str:
131
+ """Return a board's hands as a string in pbn format."""
132
+ hands_list = []
133
+ if board.dealer not in SEATS:
134
+ return []
135
+ dealer_index = SEATS.index(board.dealer)
136
+ for index in range(4):
137
+ seat = (dealer_index + index) % 4
138
+ hand = board.hands[seat]
139
+ hand_list = []
140
+ for suit_name in reversed(SUIT_NAMES):
141
+ suit_cards = []
142
+ for rank in reversed(RANKS[1:]):
143
+ suit_cards.extend(
144
+ card.rank
145
+ for card in hand.cards
146
+ if card.name == ''.join([rank, suit_name])
147
+ )
148
+ hand_list.append(''.join(suit_cards))
149
+ hands_list.append('.'.join(hand_list))
150
+ return delimiter.join(hands_list)
151
+
152
+
153
+ def _create_pbn_auction(board: "Board") -> list[str]:
154
+ """Return an auction as a pbn list."""
155
+ auction_list = [f'[Auction "{board.dealer}"]']
156
+ """
157
+ See PBN Spec at https://tistis.nl/pbn/
158
+
159
+ In import format the player in the Auction tag value need not be
160
+ the dealer. For example, the calls are given in a table
161
+ of 4 columns with West in the first column. In that case, each
162
+ player before the dealer has a hyphen ("-") in the
163
+ first auction line.
164
+
165
+ In this case, the player will be the dealer
166
+ """
167
+ line = []
168
+ for call in board.auction.calls:
169
+ if call.name in PBN_CALL_CONVERSION:
170
+ pbn_call = PBN_CALL_CONVERSION[call.name]
171
+ else:
172
+ pbn_call = call.name
173
+ line.append(pbn_call)
174
+ if len(line) == 4:
175
+ auction_list.append(' '.join(list(line)))
176
+ line = []
177
+ auction_list.append(' '.join(list(line)))
178
+ return auction_list
179
+
180
+
181
+ def _create_pbn_play_section(board: "Board") -> list[str]:
182
+ """Return board's tricks as a pbn list."""
183
+ if not board.tricks:
184
+ return []
185
+
186
+ trick_list = [f'[Play "{board.tricks[0].leader}"]']
187
+ for trick in board.tricks:
188
+ if trick.leader:
189
+ line = []
190
+ for index, card in enumerate(trick.cards):
191
+ if card:
192
+ line.append(''.join([card.name[1], card.name[0]]))
193
+ if trick.note_keys[index]:
194
+ line.append(f'={trick.note_keys[index]}=')
195
+ trick_list.append(' '.join(list(line)))
196
+ return trick_list
197
+
198
+
199
+ def _write_file(output: list[str], path: str, append: bool) -> bool:
200
+ """Write the list 'output' to a text file defined by path."""
201
+ if not path.is_file():
202
+ with open(path, 'w') as f_clear_pbn_file:
203
+ f_clear_pbn_file.write('')
204
+ try:
205
+ mode = 'a' if append else 'w'
206
+ with open(path, mode) as f_pbn_file:
207
+ f_pbn_file.write('\n'.join(output))
208
+ return True
209
+ except FileNotFoundError as error:
210
+ error_text = f'invalid file path: {path}. File not written'
211
+ raise FileNotFoundError(error_text) from error
212
+ return False
@@ -0,0 +1,76 @@
1
+
2
+ from .event import Event
3
+ from ._file_constants import (PBN_VULNERABILITY_CONVERSION,
4
+ PBN_CALL_CONVERSION,
5
+ PBN_VERSION_TEXT, PBN_FORMAT_TEXT,
6
+ PBN_CONTENT_TEXT, PBN_CREATOR_TEXT,
7
+ RBN_VERSION_TEXT, RBN_CREATOR_TEXT)
8
+
9
+ from ._create_pbn_string import get_pbn_deal
10
+
11
+
12
+ def create_rbn_list(events: list[Event]) -> list[str]:
13
+ """Create a list of strings for events in rbn format."""
14
+ output = [RBN_VERSION_TEXT, RBN_CREATOR_TEXT]
15
+ for event in events:
16
+ output.extend(_create_rbn_event(event))
17
+ return output
18
+
19
+
20
+ def _create_rbn_event(event: Event) -> list[str]:
21
+ """Return an event as string in rbn format as a list."""
22
+ output = [f'E {event.name}', f'L {event.site}']
23
+ if event.date:
24
+ event_date = event.date.strftime('%Y%m%d')
25
+ output.append(f'D {event_date}')
26
+ output.append(f'M {_question_from_null(event.scoring_method)}')
27
+ for board in event.boards:
28
+ output.extend(_create_rbn_board(board))
29
+ return output
30
+
31
+
32
+ def _create_rbn_board(board: "Board") -> list[str]:
33
+ """Return a board as a list of strings in pbn format."""
34
+ output = [f'B {board.number}']
35
+
36
+ if names := _create_rbn_names(board):
37
+ output.append(f'N {names}')
38
+
39
+ # hands
40
+ deal = get_pbn_deal(board, ':')
41
+ output.append(f'H {board.dealer}:{deal}')
42
+
43
+ # auction
44
+ vulnerable = PBN_VULNERABILITY_CONVERSION[board.vulnerable]
45
+ output.append(f'A {board.dealer}{vulnerable}:')
46
+
47
+ # contract
48
+ board_contract = _question_from_null(board.contract.name)
49
+ board_declarer = _question_from_null(board.declarer)
50
+ contract = ':'.join([board_contract, board_declarer])
51
+ if contract != "?:?":
52
+ output.append(f'C {contract}')
53
+
54
+ # result
55
+ result = _question_from_null(board.result)
56
+ if result != "?":
57
+ output.append('[R result')
58
+ output.append('')
59
+ return output
60
+
61
+
62
+ def _create_rbn_names(board: "Board") -> str:
63
+ """Return the boards players in rbn format."""
64
+ names = f'{board.north}+{board.south}:{board.west}+{board.east}'
65
+ if names == "+:+":
66
+ names = ""
67
+ if names[:3] == "+:":
68
+ names = names.replace("+:", ";")
69
+ if names[-3:] == ":+":
70
+ names = names.replace(":+", ";")
71
+ return names
72
+
73
+
74
+ def _question_from_null(value: str) -> str:
75
+ """Return a question mark if value is None or ''."""
76
+ return value or "?"
@@ -28,9 +28,6 @@ from .constants import SEATS
28
28
  from ._file_constants import LIN_VULNERABILITY_CONVERSION
29
29
 
30
30
 
31
- MODULE_COLOUR = 'red'
32
-
33
-
34
31
  # TODO test for lin event
35
32
  def parse_lin(file_text: list[str]) -> list[Event]:
36
33
  """Populate bridgeobjects objects from a lin file."""
@@ -0,0 +1,323 @@
1
+ """Helper functions for parsing pbn strings."""
2
+
3
+ import re
4
+ from datetime import datetime, date
5
+ from dataclasses import dataclass
6
+
7
+ from .event import Event
8
+ from .board import Board
9
+ from .contract import Contract
10
+ from .auction import Auction
11
+ from .hand import Hand
12
+ from .call import Call
13
+ from .constants import CALLS, SEATS, VULNERABLE
14
+ from ._file_constants import PBN_CALL_CONVERSION
15
+
16
+ TODAY = datetime.now().strftime('%Y%m%D')
17
+
18
+
19
+ def parse_pbn(file_lines: list[str]) -> list[Event]:
20
+ """Populate bridgeobjects objects from a pbn file."""
21
+ return PbnFile(file_lines).events
22
+
23
+
24
+ @dataclass
25
+ class PbnBoard():
26
+ def __init__(self) -> None:
27
+ self.event: str = ''
28
+ self.event_name: str = ''
29
+ self.site: str = ''
30
+ self.date: str = ''
31
+ self.board: str = ''
32
+ self.west: str = ''
33
+ self.north: str = ''
34
+ self.east: str = ''
35
+ self.south: str = ''
36
+ self.dealer: str = ''
37
+ self.vulnerable: str = ''
38
+ self.deal: str = ''
39
+ self.scoring: str = ''
40
+ self.declarer: str = ''
41
+ self.contract: str = ''
42
+ self.result: str = ''
43
+
44
+ self.tag: str = ''
45
+ self.number: str = ''
46
+ self.deal_id: str = ''
47
+ self.description: str = ''
48
+ self.french_mp: str = ''
49
+ self.generator: str = ''
50
+ self.hidden: str = ''
51
+ self.room: str = ''
52
+ self.termination: str = ''
53
+ self.score: str = ''
54
+ self.event_date: str = ''
55
+
56
+ self.auction: list = []
57
+ self.auction_notes: list = []
58
+ self.play: list = []
59
+ self.play_notes: list = []
60
+
61
+
62
+ class PbnFile():
63
+ def __init__(self, lines: list) -> None:
64
+ self.events = []
65
+ self.events_holder = {}
66
+ self.current_event_name = ''
67
+ self.pbn_board = None
68
+ self.pbn_boards = []
69
+ self.event_number = 0
70
+ self.string_fields = self._get_string_fields()
71
+ self._set_state()
72
+ # self.auction = []
73
+ # self.play = []
74
+
75
+ # Execute
76
+ self._parse_file_lines(lines)
77
+ self._build_events()
78
+
79
+ def _get_string_fields(self) -> dict:
80
+ return {
81
+ 'Event': 'event_name',
82
+ 'Site': 'site',
83
+ 'Date': 'date',
84
+ 'Board': 'board',
85
+ 'West': 'west',
86
+ 'North': 'north',
87
+ 'East': 'east',
88
+ 'South': 'south',
89
+ 'Dealer': 'dealer',
90
+ 'Vulnerable': 'vulnerable',
91
+ 'Deal': 'deal',
92
+ 'Scoring': 'scoring',
93
+ 'Declarer': 'declarer',
94
+ 'Contract': 'contract',
95
+ 'Result': 'result',
96
+
97
+ 'DealId': 'deal_id',
98
+ 'Description': 'description',
99
+ 'EventDate': 'event_date',
100
+ 'Generator': 'generator',
101
+ 'Tag': 'tag',
102
+
103
+ # 'FrenchMP': 'french_mp',
104
+ # 'Hidden': 'hidden',
105
+ # 'Room': 'room',
106
+ # 'Termination': 'termination',
107
+ }
108
+
109
+ def _set_state(self, activate: str = '') -> None:
110
+ states = {
111
+ 'Auction': 'auction_state',
112
+ 'Play': 'play_state',
113
+ 'Board': 'board_state',
114
+ 'Result': 'result_table',
115
+ }
116
+ for key, state in states.items():
117
+ setattr(self, state, False)
118
+ if key == activate:
119
+ setattr(self, state, True)
120
+
121
+ def _parse_file_lines(self, lines: list) -> None:
122
+ for line in lines:
123
+ if not line or line.startswith("%"): # Comments
124
+ continue
125
+
126
+ if line.startswith("["):
127
+ (tag, value) = self._parse_pbn_line(line)
128
+
129
+ self._parse_line(tag, value, line)
130
+
131
+ def _parse_line(self, tag: str, value: str, line: str) -> None:
132
+ if tag == 'Event':
133
+ self.pbn_board = PbnBoard()
134
+ self.pbn_boards.append(self.pbn_board)
135
+
136
+ self.event_name = value
137
+ setattr(self.pbn_board, self.string_fields[tag], value)
138
+
139
+ elif tag == 'Board':
140
+ self.pbn_board.number = value
141
+ self.pbn_board.auction = []
142
+ self.pbn_board.auction_notes = []
143
+ self.pbn_board.play = []
144
+ self.pbn_board.play_notes = []
145
+
146
+ elif tag in self.string_fields:
147
+ setattr(self.pbn_board, self.string_fields[tag], value)
148
+
149
+ elif tag in {'Auction', 'Play'}:
150
+ self._set_state(tag)
151
+
152
+ if self.auction_state:
153
+ if tag != 'Note':
154
+ self.pbn_board.auction.append(line)
155
+ else:
156
+ self.pbn_board.auction_notes.append(value)
157
+
158
+ if self.play_state:
159
+ if tag != 'Note':
160
+ self.pbn_board.play.append(line)
161
+ else:
162
+ self.pbn_board.play_notes.append(value)
163
+
164
+ def _build_events(self):
165
+ for pbn_board in self.pbn_boards:
166
+ event = self._get_event(pbn_board)
167
+
168
+ if pbn_board.event_date:
169
+ event.date = self.parse_date(pbn_board.event_date)
170
+
171
+ if not pbn_board.deal_id:
172
+ pbn_board.deal_id = f'{event.id}:{len(event.boards)+1}'
173
+
174
+ board = self._build_board(pbn_board)
175
+ board.event = event
176
+ event.site = board.site
177
+ board.contract.declarer = board.declarer # not used
178
+ board.auction = self._get_auction(pbn_board)
179
+ event.boards.append(board)
180
+
181
+ def _get_event(self, pbn_board: PbnBoard) -> Event:
182
+ event_name = self._get_event_name(pbn_board.event_name)
183
+
184
+ if event_name in self.events_holder:
185
+ return self.events_holder[event_name]
186
+
187
+ event = Event(event_name)
188
+ event.date = self.parse_date(pbn_board.date)
189
+ self.events_holder[event_name] = event
190
+ self.events.append(event)
191
+ return event
192
+
193
+ def _get_event_name(self, event_name: str) -> str:
194
+ if event_name:
195
+ self.current_event_name = ''
196
+ return event_name
197
+
198
+ if self.current_event_name:
199
+ return self.current_event_name
200
+
201
+ self.event_number += 1
202
+ self.current_event_name = f'{TODAY} - {self.event_number}'
203
+ return self.current_event_name
204
+
205
+ def _build_board(self, pbn_board: PbnBoard) -> Board:
206
+ board = Board()
207
+
208
+ # self._print_details()
209
+ board.number = pbn_board.number
210
+ board.deal_id = pbn_board.deal_id
211
+ board.site = pbn_board.site
212
+ board.date = self.parse_date(pbn_board.date)
213
+ board.west = pbn_board.west
214
+ board.north = pbn_board.north
215
+ board.east = pbn_board.east
216
+ board.south = pbn_board.south
217
+ board.dealer = pbn_board.dealer
218
+ board.vulnerable = (pbn_board.vulnerable
219
+ if pbn_board.vulnerable in VULNERABLE else 'None')
220
+ board.hands = self._get_deal(pbn_board)
221
+ board.scoring_method = pbn_board.scoring
222
+ board.contract = self._contract_handler(board, pbn_board)
223
+ board.contract.declarer == pbn_board.declarer
224
+ board.description = pbn_board.description
225
+ return board
226
+
227
+ def _print_details(self) -> None:
228
+ for tag, attr in self._get_string_fields().items():
229
+ print(tag, getattr(self, attr))
230
+
231
+ @staticmethod
232
+ def _parse_pbn_line(line: str) -> tuple[str, str]:
233
+ """Return the tag and value from a pbn text line."""
234
+ # example pbn line: [Vulnerable "None"]
235
+ line = line.strip()
236
+ space_at = line.find(' ')
237
+ tag = line[1:space_at]
238
+ value = line[space_at + 1:]
239
+ value = value[:-1]
240
+ value = value.replace('"', '')
241
+ return (tag, value)
242
+
243
+ def _contract_handler(self, board: Board, pbn_board: PbnBoard) -> Contract:
244
+ value = pbn_board.contract
245
+ contract = Contract()
246
+ if not value or value == '?':
247
+ return contract
248
+
249
+ if value.endswith('XX'):
250
+ value = value.replace('XX', 'R')
251
+ elif value.endswith('X'):
252
+ value = value.replace('X', 'D')
253
+ contract.name = value
254
+ return contract
255
+
256
+ def parse_date(self, value: str) -> date:
257
+ """Return a datetime date object from a pbn date string."""
258
+ # example date value: 2018.02.26
259
+ is_valid = re.search("[0-9]{4}.[\0-9]{2}.[0-9]{2}", value)
260
+ if not is_valid:
261
+ return None
262
+ date_str = value.split('.')
263
+ date_list = list(map(int, date_str))
264
+ return date(date_list[0], date_list[1], date_list[2])
265
+
266
+ def _get_deal(self, pbn_board: PbnBoard) -> dict[object, Hand]:
267
+ """Return a list of hands from a pbn deal string."""
268
+ # example deal value:
269
+ # N:K87.Q642.AJ6.K73 T5.85.Q752.Q6542 AQJ96.73.T843.JT 432.AKJT9.K9.A98
270
+ hands: dict[object, Hand] = {}
271
+ # Assign hands to board in correct seat; 0 and 'N, 1 and 'E' etc..
272
+ raw_hands = pbn_board.deal[2:].split(" ")
273
+ if not pbn_board.deal:
274
+ return hands
275
+ first_seat = SEATS.index(pbn_board.deal[0])
276
+ for index, card_list in enumerate(raw_hands):
277
+ seat_index = (first_seat + index) % 4
278
+ seat_name = SEATS[seat_index]
279
+ hand = Hand(card_list)
280
+ hands[seat_index] = hand
281
+ hands[seat_name] = hand
282
+ return hands
283
+
284
+ def _check_state(self) -> None:
285
+ self.auction_state = False
286
+ self.play_state = False
287
+ self.result_table = False
288
+
289
+ def _get_auction(self, pbn_board: PbnBoard) -> Auction:
290
+ """Use the tag and value to update the auction attributes."""
291
+ auction = Auction()
292
+ if not pbn_board.auction:
293
+ return auction
294
+
295
+ data = []
296
+ for line in pbn_board.auction[1:]:
297
+ data.extend(line.split())
298
+
299
+ for element in data:
300
+ self._handle_auction_call(auction, element)
301
+
302
+ for note in pbn_board.auction_notes:
303
+ note_as_list = note.split(':')
304
+ auction.notes[note_as_list[0]] = note_as_list[1]
305
+ return auction
306
+
307
+ def _handle_auction_call(self, auction: Auction, element: str) -> None:
308
+ if element in PBN_CALL_CONVERSION:
309
+ element = PBN_CALL_CONVERSION[element]
310
+
311
+ if element == '-':
312
+ pass
313
+ elif element == 'A':
314
+ passes = [Call('P')] * 4
315
+ auction.calls = passes
316
+ elif element in CALLS:
317
+ auction.calls.append(Call(element))
318
+ auction.note_keys.append('')
319
+ elif element.startswith('='):
320
+ auction.note_keys.pop(-1)
321
+ auction.note_keys.append(element.replace('=', ''))
322
+ else:
323
+ raise ValueError(f'invalid element in calls: {element}')