summaryrefslogtreecommitdiff
path: root/dealconvert/formats/ber.py
blob: d20a0ff2d0e7c218793221a81a33e5bae09c27f2 (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
import sys

from . import DealFormat
from .. import dto

class BERFormat(DealFormat):
    number_warning = 'WARNING: .ber file format assumes consequent deal numbers from 1'
    cards = 'AKQJT98765432'

    @property
    def suffix(self):
        return '.ber'

    def parse_content(self, content):
        print self.number_warning
        dealset = []
        number = 1
        while True:
            deal_str = content.read(52).strip()
            if len(deal_str) > 0:
                if len(deal_str) < 52:
                    print 'WARNING: truncated .ber input: %s' % (deal_str)
                    break
                deal = dto.Deal()
                deal.number = number
                deal.dealer = deal.get_dealer(number)
                deal.vulnerable = deal.get_vulnerability(number)
                for suit in range(0, 4):
                    for card in range(0, 13):
                        try:
                            deal.hands[int(deal_str[suit*13 + card])-1][suit].append(self.cards[card])
                        except (IndexError, ValueError):
                            print 'ERROR: invalid character in .ber file: %s' % (deal_str[suit*13 + card])
                            sys.exit()
                dealset.append(deal)
                number += 1
            else:
                break
        return dealset


    def output_content(self, out_file, dealset):
        print self.number_warning
        for board in dealset:
            deal_str = [' '] * 52
            for i, hand in enumerate(board.hands):
                for j, suit in enumerate(hand):
                    for card in suit:
                        try:
                            deal_str[j*13 + self.cards.index(card)] = str(i + 1)
                        except ValueError:
                            print 'ERROR: invalid card character: %s' % (card)
            if ' ' in deal_str:
                print 'WARNING: not all cards present in board %d' % (board.number)
            out_file.write(''.join(deal_str))