summaryrefslogtreecommitdiff
path: root/src/ParScore.cs
blob: 068be9042272da2c46f4aebdafeae430d8c35020 (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
230
231
232
233
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace BCDD
{
    class ParScoreInvalidException : FieldNotFoundException
    {
        public ParScoreInvalidException() : base() { }
        public ParScoreInvalidException(String msg) : base(msg) { }
    }

    class ParScore
    {
        private PBNBoard board;
        private static Regex pbnContractPattern = new Regex(@"(\d)([CDHSN])(X?)\s+([NESW])");
        private static Regex pbnScorePattern = new Regex(@"(NS|EW)\s+(-?\d})");
        private static Regex jfrContractPattern = new Regex(@"^(\d)([CDHSN])(D?)([NESW])(-?\d+)$");

        public ParScore(PBNBoard board)
        {
            this.board = board;
        }

        public ParContract GetPBNParContract()
        {
            String contractField = this.board.GetOptimumResult();
            if ("Pass".Equals(contractField))
            {
                return new ParContract();
            }
            Match contractMatch = ParScore.pbnContractPattern.Match(contractField);
            if (!contractMatch.Success)
            {
                throw new ParScoreInvalidException("Invalid format for OptimumResult field: " + contractField);
            }
            String scoreField = this.board.GetOptimumScore();
            Match scoreMatch = ParScore.pbnScorePattern.Match(scoreField);
            if (!scoreMatch.Success)
            {
                throw new ParScoreInvalidException("Invalid format for OptimumScore field: " + scoreField);
            }
            int score = Int16.Parse(scoreMatch.Groups[2].Value);
            if ("EW".Equals(scoreMatch.Groups[1].Value))
            {
                score = -score;
            }
            ParContract contract = new ParContract(Int16.Parse(contractMatch.Groups[1].Value),
                contractMatch.Groups[2].Value[0],
                contractMatch.Groups[4].Value[0],
                "X".Equals(contractMatch.Groups[3].Value),
                score);
            return contract.Validate();
        }

        public ParContract GetJFRParContract()
        {
            String parString = this.board.GetMinimax();
            Match parMatch = ParScore.jfrContractPattern.Match(parString);
            if (!parMatch.Success)
            {
                throw new ParScoreInvalidException("Invalid format for Minimax field: " + parString);
            }
            if ("0".Equals(parMatch.Groups[4].Value))
            {
                return new ParContract(); // pass-out
            }
            ParContract contract = new ParContract(Int16.Parse(parMatch.Groups[1].Value),
                parMatch.Groups[2].Value[0],
                parMatch.Groups[4].Value[0],
                "D".Equals(parMatch.Groups[3].Value),
                Int16.Parse(parMatch.Groups[5].Value));
            return contract.Validate();
        }

        private bool determineVulnerability(String vulnerability, char declarer)
        {
            vulnerability = vulnerability.ToUpper();
            return "ALL".Equals(vulnerability) || "BOTH".Equals(vulnerability)
                || (!"LOVE".Equals(vulnerability) && !"NONE".Equals(vulnerability) && vulnerability.Contains(declarer));
        }

        private ParContract getHighestMakeableContract(int[,] ddTable, bool forNS = true, bool forEW = true)
        {
            ParContract contract = new ParContract();
            int tricks = 0;
            for (int i = 3; i >= 0; i--)
            {
                if ((i % 2 == 0 && forNS)
                    || (i % 2 == 1 && forEW))
                {
                    for (int j = 0; j < 5; j++)
                    {
                        int level = ddTable[i, j] - 6;
                        if (level > contract.Level
                            || (level == contract.Level && j > Array.IndexOf(BCalcWrapper.DENOMINATIONS, contract.Denomination)))
                        {
                            contract.Level = level;
                            contract.Denomination = BCalcWrapper.DENOMINATIONS[j];
                            contract.Declarer = BCalcWrapper.PLAYERS[i];
                            tricks = ddTable[i, j];
                        }
                    }
                }
            }
            String vulnerability = this.board.GetVulnerable().ToUpper();
            bool vulnerable = this.determineVulnerability(vulnerability, contract.Declarer);
            contract.Score = contract.CalculateScore(tricks, vulnerable);
            return contract;
        }

        public ParContract GetDDTableParContract(int[,] ddTable)
        {
            String dealer = this.board.GetDealer();
            String vulnerability = this.board.GetVulnerable().ToUpper();
            ParContract nsHighest = this.getHighestMakeableContract(ddTable, true, false);
            ParContract ewHighest = this.getHighestMakeableContract(ddTable, false, true);
            bool nsPlaying = ("N".Equals(dealer) || "S".Equals(dealer));
            if (nsHighest == ewHighest)
            {
                return nsPlaying ? nsHighest.Validate() : ewHighest.Validate();
            }
            ParContract highest = nsHighest.Higher(ewHighest) ? nsHighest : ewHighest;
            ParContract otherSideHighest = nsHighest.Higher(ewHighest) ? ewHighest : nsHighest;
            nsPlaying = ('N'.Equals(highest.Declarer) || 'S'.Equals(highest.Declarer));
            bool defenseVulnerability = this.determineVulnerability(vulnerability, nsPlaying ? 'E' : 'N');
            ParContract highestDefense = highest.GetDefense(ddTable, defenseVulnerability);
            if (highestDefense != null)
            {
                // Highest contract has profitable defense
                return highestDefense.Validate();
            }
            int denominationIndex = Array.IndexOf(BCalcWrapper.DENOMINATIONS, highest.Denomination);
            int declarerIndex = Array.IndexOf(BCalcWrapper.PLAYERS, highest.Declarer);
            List<int> playerIndexes = new List<int>();
            playerIndexes.Add(declarerIndex);
            playerIndexes.Add((declarerIndex + 2) & 3);
            bool vulnerable = this.determineVulnerability(vulnerability, highest.Declarer);
            int scoreSquared = highest.Score * highest.Score;
            List<ParContract> possibleOptimums = new List<ParContract>();
            for (int i = 0; i < 5; i++)
            {
                foreach (int player in playerIndexes)
                {
                    int level = highest.Level;
                    if (i > denominationIndex)
                    {
                        level--;
                    }
                    while (level > 0)
                    {
                        ParContract contract = new ParContract(level, BCalcWrapper.DENOMINATIONS[i], BCalcWrapper.PLAYERS[player], false, 0);
                        contract.Score = contract.CalculateScore(ddTable[player, i], vulnerable);
                        if (otherSideHighest.Higher(contract))
                        {
                            // Contract is lower than other side's contract
                            break;
                        }
                        if (highest.Score * contract.Score > 0)
                        {
                            // Contract makes
                            if (Math.Abs(contract.Score) >= Math.Abs(highest.Score))
                            {
                                // Contract is profitable
                                ParContract defense = contract.GetDefense(ddTable, defenseVulnerability);
                                if (defense != null && (contract.Score * contract.Score > contract.Score * defense.Score))
                                {
                                    // Contract has defense
                                    possibleOptimums.Add(defense);
                                    // So lower contracts will too.
                                    break;
                                }
                                else
                                {
                                    // Contract does not have defense
                                    possibleOptimums.Add(contract);
                                }
                            }
                            else
                            {
                                // Contract is not profitable
                                break;
                            }
                        }
                        level--;
                    }
                }
            }
            foreach (ParContract contract in possibleOptimums)
            {
                if ((Math.Abs(contract.Score) > Math.Abs(highest.Score)))
                {
                    // Contract is more profitable
                    highest = contract;
                }
                else
                {
                    if (contract.Score == highest.Score)
                    {
                        if (highest.Higher(contract))
                        {
                            // Equally profitable, but lower
                            highest = contract;
                        }
                    }
                }
            }
            return highest.Validate();
        }

        public ParContract GetParContract(int[,] ddTable)
        {
            try
            {
                return this.GetJFRParContract();
            }
            catch (FieldNotFoundException)
            {
                try
                {
                    return this.GetPBNParContract();
                }
                catch (FieldNotFoundException)
                {
                    return this.GetDDTableParContract(ddTable);
                }
            }
        }

    }
}