2 # -*- coding: utf-8 -*-
4 # Copyright 2008-2011, Carl Gherardi
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 ########################################################################
22 _
= L10n
.get_translation()
28 from HandHistoryConverter
import *
29 from decimal_wrapper
import Decimal
33 class OnGame(HandHistoryConverter
):
36 codepage
= ("utf8", "cp1252")
37 siteId
= 5 # Needs to match id entry in Sites database
39 mixes
= { } # Legal mixed games
40 sym
= {'USD': "\$", 'CAD': "\$", 'T$': "", "EUR": u
"\u20ac", "GBP": "\xa3"}
42 'LEGAL_ISO' : "USD|EUR|GBP|CAD|FPP", # legal ISO currency codes
43 'LS' : u
"\$|\xe2\x82\xac|\u20ac|", # Currency symbols - Euro(cp1252, utf-8)
46 currencies
= { u
'\u20ac':'EUR', u
'\xe2\x82\xac':'EUR', '$':'USD', '':'T$' }
48 limits
= { 'NO_LIMIT':'nl', 'POT_LIMIT':'pl', 'LIMIT':'fl'}
50 games
= { # base, category
51 "TEXAS_HOLDEM" : ('hold','holdem'),
52 'OMAHA_HI' : ('hold','omahahi'),
53 # 'Omaha Hi/Lo' : ('hold','omahahilo'),
54 # 'Razz' : ('stud','razz'),
55 # 'RAZZ' : ('stud','razz'),
56 'SEVEN_CARD_STUD' : ('stud','studhi'),
57 'SEVEN_CARD_STUD_HI_LO' : ('stud','studhilo'),
58 # 'Badugi' : ('draw','badugi'),
59 # 'Triple Draw 2-7 Lowball' : ('draw','27_3draw'),
60 'FIVE_CARD_DRAW' : ('draw','fivedraw')
64 # ***** End of hand R5-75443872-57 *****
65 re_SplitHands
= re
.compile(u
'\*\*\*\*\*\sEnd\sof\shand\s[-A-Z\d]+.*\n(?=\*)')
67 #TODO: detect play money
68 # "Play money" rather than "Real money" and set currency accordingly
69 # Table:\s(\[SPEED\]\s)?(?P<TABLE>[-\'\w\#\s\.]+)\s\[\d+\]\s\(
70 re_HandInfo
= re
.compile(u
"""
71 \*{5}\sHistory\sfor\shand\s(?P<HID>[-A-Z\d]+)(\s\(TOURNAMENT:\s\"(?P<NAME>.+?)\",\s(?P<TID>[-A-Z\d]+),\sbuy-in:\s(?P<BUYINCUR>[%(LS)s]?)(?P<BUYIN>[%(NUM)s]+)\))?\s\*{5}\s?
72 Start\shand:\s(?P<DATETIME>.*?)\s?
73 Table:\s(\[SPEED\]\s)?(?P<TABLE>.+?)\s\[\d+\]\s\(
75 (?P<LIMIT>NO_LIMIT|Limit|LIMIT|Pot\sLimit|POT_LIMIT)\s
76 (?P<GAME>TEXAS_HOLDEM|OMAHA_HI|SEVEN_CARD_STUD|SEVEN_CARD_STUD_HI_LO|RAZZ|FIVE_CARD_DRAW)\s
77 (?P<CURRENCY>%(LS)s|)?(?P<SB>[.0-9]+)/
78 (%(LS)s)?(?P<BB>[.0-9]+)
80 """ % substitutions
, re
.MULTILINE|re
.DOTALL|re
.VERBOSE
)
82 re_TailSplitHands
= re
.compile(u
'(\*\*\*\*\*\sEnd\sof\shand\s[-A-Z\d]+.*\n)(?=\*)')
83 re_Button
= re
.compile('Button: seat (?P<BUTTON>\d+)', re
.MULTILINE
) # Button: seat 2
84 re_Board
= re
.compile(r
"\[(?P<CARDS>.+)\]")
86 # Wed Aug 18 19:45:30 GMT+0100 2010
87 re_DateTime
= re
.compile("""
91 (?P<H>[0-9]+):(?P<MIN>[0-9]+):(?P<S>[0-9]+)\s
92 (?P<OFFSET>\w+([-+]\d+)?)\s
94 """, re
.MULTILINE|re
.VERBOSE
)
96 #Seat 1: .Lucchess ($4.17 in chips)
97 #Seat 1: phantomaas ($27.11)
98 #Seat 5: mleo17 ($9.37)
99 #Seat 2: Montferat (1500)
100 re_PlayerInfo
= re
.compile(u
'Seat (?P<SEAT>[0-9]+):\s(?P<PNAME>.*)\s\((%(LS)s)?(?P<CASH>[,.0-9]+)\)' % substitutions
)
102 def compilePlayerRegexs(self
, hand
):
103 players
= set([player
[1] for player
in hand
.players
])
104 if not players
<= self
.compiledPlayers
: # x <= y means 'x is subset of y'
105 # we need to recompile the player regexs.
106 # TODO: should probably rename re_HeroCards and corresponding method,
107 # since they are used to find all cards on lines starting with "Dealt to:"
108 # They still identify the hero.
109 self
.compiledPlayers
= players
112 #helander2222 posts blind ($0.25), lopllopl posts blind ($0.50).
113 player_re
= "(?P<PNAME>" + "|".join(map(re
.escape
, players
)) + ")"
114 subst
= {'PLYR': player_re
, 'CUR': self
.sym
[hand
.gametype
['currency']]}
115 self
.re_PostSB
= re
.compile('(?P<PNAME>.*) posts small blind \((%(CUR)s)?(?P<SB>[\.0-9]+)\)' % subst
, re
.MULTILINE
)
116 self
.re_PostBB
= re
.compile('(?P<PNAME>.*) posts big blind \((%(CUR)s)?(?P<BB>[\.0-9]+)\)' % subst
, re
.MULTILINE
)
117 self
.re_Antes
= re
.compile(r
"^%(PLYR)s: posts the ante (%(CUR)s)?(?P<ANTE>[\.0-9]+)" % subst
, re
.MULTILINE
)
118 self
.re_BringIn
= re
.compile(r
"^%(PLYR)s: brings[- ]in( low|) for (%(CUR)s)?(?P<BRINGIN>[\.0-9]+)" % subst
, re
.MULTILINE
)
119 self
.re_PostBoth
= re
.compile('(?P<PNAME>.*): posts small \& big blind \( (%(CUR)s)?(?P<SBBB>[\.0-9]+)\)' % subst
)
120 self
.re_PostDead
= re
.compile('(?P<PNAME>.*) posts dead blind \((%(CUR)s)?(?P<DEAD>[\.0-9]+)\)' % subst
, re
.MULTILINE
)
121 self
.re_HeroCards
= re
.compile('(New\shand\sfor|Dealing\sto)\s%(PLYR)s:\s\[(?P<CARDS>.*)\]' % subst
)
123 self
.re_Action
= re
.compile('(, )?(?P<PNAME>.*?)(?P<ATYPE> bets| checks| raises| calls| folds| changed)( (%(CUR)s)?(?P<BET>[\d\.]+))?( to (%(CUR)s)?(?P<BET2>[\d\.]+))?( and is all-in)?' % subst
)
124 #self.re_Board = re.compile(r"\[board cards (?P<CARDS>.+) \]")
126 #Uchilka shows [ KC,JD ]
127 self
.re_ShowdownAction
= re
.compile('(?P<PNAME>.*) shows \[ (?P<CARDS>.+) \]')
129 #Main pot: $3.57 won by mleo17 ($3.40)
130 #Side pot 1: $3.26 won by maac_5 ($3.10)
131 #Main pot: $2.87 won by maac_5 ($1.37), sagi34 ($1.36)
132 self
.re_Pot
= re
.compile('(Main|Side)\spot(\s\d+)?:\s.*won\sby\s(?P<POT>.*$)', re
.MULTILINE
)
133 self
.re_CollectPot
= re
.compile('\s*(?P<PNAME>.*)\s\((%(CUR)s)?(?P<POT>[\.\d]+)\)' % subst
)
134 #Seat 5: mleo17 ($3.40), net: +$2.57, [Jd, Qd] (TWO_PAIR QUEEN, JACK)
135 self
.re_ShownCards
= re
.compile("^Seat (?P<SEAT>[0-9]+): (?P<PNAME>.*) \(.*\), net:.* \[(?P<CARDS>.*)\].*" % subst
, re
.MULTILINE
)
136 self
.re_sitsOut
= re
.compile('(?P<PNAME>.*) sits out')
138 def readSupportedGames(self
):
139 return [["ring", "hold", "nl"],
140 ["ring", "hold", "pl"],
141 ["ring", "hold", "fl"],
143 ["ring", "stud", "fl"],
145 ["ring", "draw", "fl"],
146 ["ring", "draw", "pl"],
147 ["ring", "draw", "nl"],
149 ["tour", "hold", "nl"],
150 ["tour", "hold", "pl"],
151 ["tour", "hold", "fl"],
153 ["tour", "stud", "fl"],
155 ["tour", "draw", "fl"],
156 ["tour", "draw", "pl"],
157 ["tour", "draw", "nl"],
160 def determineGameType(self
, handText
):
161 # Inspect the handText and return the gametype dict
162 # gametype dict is: {'limitType': xxx, 'base': xxx, 'category': xxx}
165 m
= self
.re_HandInfo
.search(handText
)
167 tmp
= handText
[0:200]
168 log
.error(_("OnGameToFpdb.determineGameType: '%s'") % tmp
)
172 #print "DEBUG: mg: %s" % mg
174 info
['type'] = 'ring'
175 if mg
['TID'] != None:
176 info
['type'] = 'tour'
179 info
['currency'] = self
.currencies
[mg
['CURRENCY']]
182 if mg
['LIMIT'] in self
.limits
:
183 info
['limitType'] = self
.limits
[mg
['LIMIT']]
185 tmp
= handText
[0:200]
186 log
.error(_("OnGameToFpdb.determineGameType: Limit not found in '%s'") % tmp
)
189 (info
['base'], info
['category']) = self
.games
[mg
['GAME']]
191 info
['sb'] = self
.clearMoneyString(mg
['SB'])
193 info
['bb'] = self
.clearMoneyString(mg
['BB'])
195 #log.debug("determinegametype: returning "+str(info))
198 def readHandInfo(self
, hand
):
200 m
= self
.re_HandInfo
.search(hand
.handText
)
202 tmp
= hand
.handText
[0:200]
203 log
.error(_("OnGameToFpdb.readHandInfo: '%s'") % tmp
)
206 info
.update(m
.groupdict())
207 #log.debug("readHandInfo: %s" % info)
209 if key
== 'DATETIME':
210 #'Wed Aug 18 19:45:30 GMT+0100 2010
211 # %a %b %d %H:%M:%S %z %Y
212 #hand.startTime = time.strptime(m.group('DATETIME'), "%a %b %d %H:%M:%S GMT%z %Y")
213 # Stupid library doesn't seem to support %z (http://docs.python.org/library/time.html?highlight=strptime#time.strptime)
214 # So we need to re-interpret te string to be useful
215 a
= self
.re_DateTime
.search(info
[key
])
217 datetimestr
= "%s/%s/%s %s:%s:%s" % (a
.group('Y'),a
.group('M'), a
.group('D'), a
.group('H'),a
.group('MIN'),a
.group('S'))
218 tzoffset
= a
.group('OFFSET')
220 datetimestr
= "2010/Jan/01 01:01:01"
221 log
.error("OnGameToFpdb.readHandInfo: " + _("DATETIME not matched: '%s'") % info
[key
])
223 #print (_("DEBUG:") + " readHandInfo: " + _("DATETIME not matched: '%s'") % info[key])
224 # TODO: Manually adjust time against OFFSET
225 hand
.startTime
= datetime
.datetime
.strptime(datetimestr
, "%Y/%b/%d %H:%M:%S") # also timezone at end, e.g. " ET"
226 hand
.startTime
= HandHistoryConverter
.changeTimezone(hand
.startTime
, tzoffset
, "UTC")
228 hand
.handid
= info
[key
]
229 # Need to remove non-alphanumerics for MySQL
230 hand
.handid
= hand
.handid
.replace('T','')
231 hand
.handid
= hand
.handid
.replace('R','')
232 hand
.handid
= hand
.handid
.replace('-','')
234 hand
.tourNo
= info
[key
]
236 hand
.tourNo
= hand
.tourNo
.replace('T','')
237 hand
.tourNo
= hand
.tourNo
.replace('S','')
238 hand
.tourNo
= hand
.tourNo
.replace('R','')
239 hand
.tourNo
= hand
.tourNo
.replace('O','')
240 hand
.tourNo
= hand
.tourNo
.replace('-','')
241 if key
== 'BUYIN' and info
[key
] is not None:
242 hand
.buyin
= int(100*Decimal(self
.clearMoneyString(info
[key
])))
243 hand
.fee
= int(hand
.buyin
- hand
.buyin
/1.1)
244 hand
.buyin
-= hand
.fee
245 if key
== 'BUYINCUR' and info
[key
] is not None:
246 hand
.buyinCurrency
= self
.currencies
[info
[key
]]
248 hand
.buyinCurrency
= 'FREE'
250 hand
.tablename
= info
[key
]
254 hand
.maxseats
= None # Set to None - Hand.py will guessMaxSeats()
257 def readPlayerStacks(self
, hand
):
258 #log.debug("readplayerstacks: re is '%s'" % self.re_PlayerInfo)
259 head
= re
.split(re
.compile('Summary:'), hand
.handText
)
260 m
= self
.re_PlayerInfo
.finditer(head
[0])
262 hand
.addPlayer(int(a
.group('SEAT')), a
.group('PNAME'), a
.group('CASH'))
264 def markStreets(self
, hand
):
265 if hand
.gametype
['base'] in ("hold"):
266 m
= re
.search(r
"pocket cards(?P<PREFLOP>.+(?= Dealing flop )|.+(?=Summary))"
267 r
"( Dealing flop (?P<FLOP>\[\S\S, \S\S, \S\S\].+(?= Dealing turn)|.+(?=Summary)))?"
268 r
"( Dealing turn (?P<TURN>\[\S\S\].+(?= Dealing river)|.+(?=Summary)))?"
269 r
"( Dealing river (?P<RIVER>\[\S\S\].+(?=Summary)))?", hand
.handText
, re
.DOTALL
)
270 elif hand
.gametype
['base'] in ("stud"):
271 m
= re
.search(r
"(?P<ANTES>.+(?=Dealing pocket cards)|.+)"
272 r
"(Dealing pocket cards(?P<THIRD>.+(?=Dealing 4th street)|.+))?"
273 r
"(Dealing 4th street(?P<FOURTH>.+(?=Dealing 5th street)|.+))?"
274 r
"(Dealing 5th street(?P<FIFTH>.+(?=Dealing 6th street)|.+))?"
275 r
"(Dealing 6th street(?P<SIXTH>.+(?=Dealing river)|.+))?"
276 r
"(Dealing river(?P<SEVENTH>.+))?", hand
.handText
,re
.DOTALL
)
277 elif hand
.gametype
['base'] in ("draw"):
278 # isolate the first discard/stand pat line
279 discard_split
= re
.split(r
"(?:(.+(?: changed).+))", hand
.handText
,re
.DOTALL
)
280 if len(hand
.handText
) == len(discard_split
[0]):
281 # handText was not split, no DRAW street occurred
284 # DRAW street found, reassemble, with DRAW marker added
285 discard_split
[0] += "*** DRAW ***\r\n"
287 for i
in discard_split
:
289 m
= re
.search(r
"(?P<PREDEAL>.+(?=Dealing pocket cards)|.+)"
290 r
"(Dealing pocket cards(?P<DEAL>.*(?=\*\*\* DRAW \*\*\*)|.+))?"
291 r
"(\*\*\* DRAW \*\*\*(?P<DRAWONE>.+))?", hand
.handText
,re
.DOTALL
)
293 #pprint.pprint(m.groupdict())
297 #Needs to return a list in the format
298 # ['player1name', 'player2name', ...] where player1name is the sb and player2name is bb,
299 # addtional players are assumed to post a bb oop
301 def readButton(self
, hand
):
302 m
= self
.re_Button
.search(hand
.handText
)
304 hand
.buttonpos
= int(m
.group('BUTTON'))
306 log
.info('readButton: ' + _('not found'))
308 # def readCommunityCards(self, hand, street):
309 # #print hand.streets.group(street)
310 # if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
311 # m = self.re_Board.search(hand.streets.group(street))
312 # hand.setCommunityCards(street, m.group('CARDS').split(','))
314 def readCommunityCards(self
, hand
, street
): # street has been matched by markStreets, so exists in this hand
315 if street
in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
316 #print "DEBUG readCommunityCards:", street, hand.streets.group(street)
317 m
= self
.re_Board
.search(hand
.streets
[street
])
318 hand
.setCommunityCards(street
, m
.group('CARDS').split(', '))
320 def readBlinds(self
, hand
):
322 m
= self
.re_PostSB
.search(hand
.handText
)
323 hand
.addBlind(m
.group('PNAME'), 'small blind', self
.clearMoneyString(m
.group('SB')))
324 except exceptions
.AttributeError: # no small blind
325 log
.debug( _("No small blinds found.")+str(sys
.exc_info()) )
326 #hand.addBlind(None, None, None)
327 for a
in self
.re_PostBB
.finditer(hand
.handText
):
328 hand
.addBlind(a
.group('PNAME'), 'big blind', self
.clearMoneyString(a
.group('BB')))
329 for a
in self
.re_PostDead
.finditer(hand
.handText
):
330 #print "DEBUG: Found dead blind: addBlind(%s, 'secondsb', %s)" %(a.group('PNAME'), a.group('DEAD'))
331 hand
.addBlind(a
.group('PNAME'), 'secondsb', self
.clearMoneyString(a
.group('DEAD')))
332 for a
in self
.re_PostBoth
.finditer(hand
.handText
):
333 hand
.addBlind(a
.group('PNAME'), 'small & big blinds', self
.clearMoneyString(a
.group('SBBB')))
335 def readAntes(self
, hand
):
336 log
.debug(_("reading antes"))
337 m
= self
.re_Antes
.finditer(hand
.handText
)
339 #~ log.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
340 hand
.addAnte(player
.group('PNAME'), self
.clearMoneyString(player
.group('ANTE')))
342 def readBringIn(self
, hand
):
343 m
= self
.re_BringIn
.search(hand
.handText
,re
.DOTALL
)
345 #~ log.debug("readBringIn: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
346 hand
.addBringIn(m
.group('PNAME'), self
.clearMoneyString(m
.group('BRINGIN')))
348 def readHeroCards(self
, hand
):
349 # streets PREFLOP, PREDRAW, and THIRD are special cases beacause
350 # we need to grab hero's cards
351 for street
in ('PREFLOP', 'DEAL'):
352 if street
in hand
.streets
.keys():
353 m
= self
.re_HeroCards
.finditer(hand
.streets
[street
])
355 hand
.hero
= found
.group('PNAME')
356 newcards
= found
.group('CARDS').split(', ')
357 hand
.addHoleCards(street
, hand
.hero
, closed
=newcards
, shown
=False, mucked
=False, dealt
=True)
359 for street
in hand
.holeStreets
:
360 if hand
.streets
.has_key(street
):
361 if not hand
.streets
[street
] or street
in ('PREFLOP', 'DEAL') or hand
.gametype
['base'] == 'hold': continue # already done these
362 m
= self
.re_HeroCards
.finditer(hand
.streets
[street
])
364 player
= found
.group('PNAME')
365 newcards
= found
.group('CARDS').split(', ')
367 if street
== 'THIRD' and len(newcards
) == 3: # hero in stud game
369 hand
.dealt
.add(player
) # need this for stud??
370 hand
.addHoleCards(street
, player
, closed
=newcards
[0:2], open=[newcards
[2]], shown
=False, mucked
=False, dealt
=False)
372 hand
.addHoleCards(street
, player
, closed
=newcards
, shown
=False, mucked
=False, dealt
=False)
374 def readAction(self
, hand
, street
):
375 m
= self
.re_Action
.finditer(hand
.streets
[street
])
377 #acts = action.groupdict()
378 #print "readaction: acts: %s" %acts
380 if action
.group('ATYPE') == ' folds':
381 hand
.addFold( street
, action
.group('PNAME'))
382 elif action
.group('ATYPE') == ' checks':
383 hand
.addCheck( street
, action
.group('PNAME'))
384 elif action
.group('ATYPE') == ' calls':
385 hand
.addCall( street
, action
.group('PNAME'), action
.group('BET') )
386 elif action
.group('ATYPE') == ' raises':
387 hand
.addRaiseTo( street
, action
.group('PNAME'), action
.group('BET2') )
388 elif action
.group('ATYPE') == ' bets':
389 hand
.addBet( street
, action
.group('PNAME'), action
.group('BET') )
390 elif action
.group('ATYPE') == ' changed':
391 if int(action
.group('BET'))>0:
392 hand
.addDiscard(street
, action
.group('PNAME'), action
.group('BET'))
394 hand
.addStandsPat( street
, action
.group('PNAME'))
396 print (_("DEBUG:") + " " + _("Unimplemented %s: '%s' '%s'") % ("readAction", action
.group('PNAME'), action
.group('ATYPE')))
398 def readShowdownActions(self
, hand
):
399 for shows
in self
.re_ShowdownAction
.finditer(hand
.handText
):
400 cards
= shows
.group('CARDS')
401 cards
= set(cards
.split(','))
402 hand
.addShownCards(cards
, shows
.group('PNAME'))
404 def readCollectPot(self
,hand
):
405 for m
in self
.re_Pot
.finditer(hand
.handText
):
406 for splitpot
in m
.group('POT').split(','):
407 for m
in self
.re_CollectPot
.finditer(splitpot
):
408 hand
.addCollectPot(player
=m
.group('PNAME'),pot
=m
.group('POT'))
410 def readShownCards(self
,hand
):
411 for m
in self
.re_ShownCards
.finditer(hand
.handText
):
412 cards
= m
.group('CARDS')
413 cards
= cards
.split(', ') # needs to be a list, not a set--stud needs the order
415 (shown
, mucked
) = (False, False)
416 if m
.group('CARDS') is not None:
418 hand
.addShownCards(cards
=cards
, player
=m
.group('PNAME'), shown
=shown
, mucked
=mucked
)