diff --git a/create-release.sh b/create-release.sh
deleted file mode 100755
index 9f28a7ac..00000000
--- a/create-release.sh
+++ /dev/null
@@ -1,37 +0,0 @@
-#!/bin/sh
-
-#Copyright 2008 Steffen Jobbagy-Felso
-#This program is free software: you can redistribute it and/or modify
-#it under the terms of the GNU Affero General Public License as published by
-#the Free Software Foundation, version 3 of the License.
-#
-#This program is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-#GNU General Public License for more details.
-#
-#You should have received a copy of the GNU Affero General Public License
-#along with this program. If not, see .
-#In the "official" distribution you can find the license in
-#agpl-3.0.txt in the docs folder of the package.
-
-rm regression-test/*.found.txt
-rm regression-test/*.pyc
-rm pyfpdb/*.pyc
-
-mkdir fpdb-$1
-cp -R docs fpdb-$1/
-cp -R packaging fpdb-$1/
-cp -R pyfpdb fpdb-$1/
-rm fpdb-$1/pyfpdb/HUD_config.*
-cp pyfpdb/HUD_config.xml.example fpdb-$1/pyfpdb/HUD_config.xml
-cp -R regression-test fpdb-$1/
-cp -R utils fpdb-$1/
-
-cd fpdb-$1
-zip -r releases/fpdb-1.0_$1.zip *
-tar -cf - * | bzip2 >> releases/fpdb-1.0_$1.tar.bz2
-cd ..
-rm -r fpdb-$1
-
-echo "Please ensure the files are named fpdb-1.0_alpha*_p*.*"
diff --git a/docs/abbreviations.txt b/docs/abbreviations.txt
deleted file mode 100644
index 94fd5b16..00000000
--- a/docs/abbreviations.txt
+++ /dev/null
@@ -1,47 +0,0 @@
-HUD/table viewer
-================
-A3-7=3rd-7th street Complete/Raise percentage
-AF=Flop Bet/Raise percentage
-AT=River Bet/Raise percentage
-AR=Turn Bet/Raise percentage
-F3-7=3rd-7th street Fold percentage
-FB=like FSB but for big blinds only
-FF=Flop Fold percentage
-FR=River Fold percentage
-FSB=Fold to steal - combined of small and big blind (FSB means Fold Small Big). E.g. if a player faced a steal attempt in the SB 7 times and
-FS=like FSB but for small blinds only.
-FT=Turn Fold percentage
-HD=Hands
-PF3B4B=Pre Flop 3Bet or 4Bet
-PFR=Pre Flop Raise
-Postf A=Postflop (ie. flop+turn+river) Aggression%
-Postf F=Postflop Fold %
-SD/F=Showdown/Flop=WtSD=How often player went to showdown when he saw the flop
-ST=Steal chance (nobody had entered the pot before the player in question, and the player is in cutoff, button or SB position)
-W$wsF=Won $ when he saw flop
-W$@SD=Won $ at showdown
-VPI3=Voluntary Put In on 3rd Street (ie. call+complete+raise)
-VPIP=Voluntary Put In Preflop (ie. call+raise)
-
-Other
-=====
-CLI=Command Line Interface (Shell, Terminal, "DOS-window")
-FTP=Full Tilt Poker
-GUI=Graphical User Interface (normal interface with buttons and menus)
-HUD=Heads-Up Display (shows stats directly in the poker software)
-PS=PokerStars
-MTT=Multi Table Tournament
-SnG=Sit and Go
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/benchmarks.txt b/docs/benchmarks.txt
deleted file mode 100644
index 9f3bc680..00000000
--- a/docs/benchmarks.txt
+++ /dev/null
@@ -1,75 +0,0 @@
-benchmarks
-==========
-All measurements on my Athlon64@1.1GHz, 1 GB RAM, RAID5, Hardened Gentoo Linux 2.6.23
-From svn47 all measurements on my Athlon64 X2@1GHz, 2GB RAM
-All measurements were ran several times in a row, unless otherwise noted the computer was mostly idle
-svn12/15 were with PostgreSQL, svn23 onwards with MySQL
-All import measurements were taken immediately after reseting the tables
-
-svn12, whilst compiling open office in the background
-=====
-reseting tables (incl filling default data): 0.5-0.6s
-importing one hand from a file: 0.5-0.7s
-
-svn15
-=====
-reseting tables (incl filling default data): 0.35-0.4s
-importing one FTP hand from a file: 0.2-0.3s or 12-18k/hr
-importing 51 FTP hands: 2.8-2.9s or 63-66k/hr
-The large speedup will be partially due to not compiling in the background, and
-partially due to less connecting/disconnecting the DB I'd imagine.
-I'm VERY happy with this performance, but large gains could probably be made by
-making the importer just a bit more sensible.
-
-svn23
-=====
-reseting tables (incl filling default data): 0.3-0.35s
-importing 75 PS hands: 3.2s or 84k/hr
-importing 180 FTP hands: 7.7-7.9s 82k/hr
-This is the rewrite in import_FTP_and_PS.py, svn12/15 are with import_file.py
-Nice, it's substantially faster inspite of supporting PS and FTP (ish) rather
-than just FTP and handling more special cases.
-
-svn24
-=====
-importing 75 PS hands: 3.2-3.3s or 82k/hr
-importing 507 FTP hands: 23.5-23.8s or 77k/hr
-importing 947 FTP hands: 76.2-72.7s or 44k/hr
-As you can see FTP has gotten about 6% slower on 500 hands - but the much expanded handling
-of new cases (particularly the ante folding will be ALOT of extra string
-comparisons) easily explains that. In fact I expected a much bigger impact.
- (I suspect this is due to the parsing pausing whilst my shell catches up)
-
-svn47
-=====
-It significantly slows down as the database gets larger, after a few thousand
-hands it got to just one hand per second and slower. However, around 90% of the
-CPU load was MySQL. Any tips are most welcome..
-
-svn52 (whilst watching movie in a small window)
-=====
-Importing 2500 hands (mixed sites+types): 6m15s or 31k/hr (ran twice)
-Of these 230 were skipped as duplicate or partial so counting 2270 hands
-
-svn53 (whilst watching movie in a small window)
-=====
-Importing the 2270 hands from svn52: 1m50 or 74k/hr (82 if counting dupes/partial)
-Importing my 35661 (plus 427 dupe/part) hands: 51m51s or 41k/hr (ran once)
-
-The dbsize still has a significant impact, but with these sizes certainly it's
-just not a problem. If anyone runs a larger database let me know how long it takes.
-Thanks bwarycha for the tip with the foreign keys!
-
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/codingstyle.txt b/docs/codingstyle.txt
deleted file mode 100644
index 31c113f9..00000000
--- a/docs/codingstyle.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-This is just a loose collection of things so far, but might as well make a start :)
-
-A word on wrapping: Please avoid making manual line breaks, the computer can and therefore should do it. Whether people use a phone or a 40" super-uber-HD screen, they should be allowed to use as much of it as they wish/can. Incidentially, if anyone knows how to activate line wrap in Eclipse I'd really appreciate if you let me know.
-
-Comments (or prints) with todo are things that are missing, bugs, or just messy code.
-
-After every def (ie. at the end of the method) there should be a comment including the name, e.g.
-#def end of parseActionLine
-
-If you don't mind make names in java style, ie.:
-Classes, files or tables like this: MyClassName
-Methods and variables like this: myMethodName
-
-I'll eventually change all my code to that style, too.
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/db-todo.txt b/docs/db-todo.txt
deleted file mode 100644
index 9d8c0042..00000000
--- a/docs/db-todo.txt
+++ /dev/null
@@ -1,22 +0,0 @@
-stats to add
-============
-*CC,TotalColdCalls,TimesFacingRaisePreflop
-**Folded to 3-Bet,FoldedToThreeBetPreflop,FacedThreeBetPreflop
-Called 3-Bet,CalledThreeBetPreflop,FacedThreeBetPreflop
-*Winning %,wonhand,TotalHands
-**Flop Aggression Factor,timesaggressiveflop,timescalledflop
-**Turn Aggression Factor,timesaggressiveturn,timescalledturn
-**River Aggression Factor,timesaggressiveriver,timescalledriver
-scoopedPot (useful for hi/lo split games)
-
-couldSqueeze, didSqueeze, facedSqueeze, calledSqueeze -> if (player raises from EP) and (someone after him calls) and (someone after that goes all in)
-Donk Bet Turn,DidDonkBetTurn,CouldDonkBetTurn -> EP raises, LP reraises, EP calls. If EP bets out after the flop, it is considered a donk bet
-Float Turn,DidFloatTurn,CouldFloatTurn ->
-
-other
-=====
-look at PT3 and HM tables see if i forgot anything
-store all-in somewhere
-add somewhere: mixed flag to denote that the game is part of a mixed game rotation
-
-add tables for single draw (5card draw, 2-7 single draw, badugi) and tripple draw (2-7 tripple draw)
diff --git a/docs/install-in-ubuntu.txt b/docs/install-in-ubuntu.txt
deleted file mode 100644
index b3843eca..00000000
--- a/docs/install-in-ubuntu.txt
+++ /dev/null
@@ -1,46 +0,0 @@
-Last checked: 1 Sep, p74
-
-These instructions are for any Ubuntu Linux, but except for the name of the package management software it should be identical on other Linux distributions.
-
-Using the package manager (I think it's called synaptics) install the dependencies: mysql, python, mysql-python, pygtk
-I don't use ubuntu but I'd imagine it will at some point prompt you for a MySQL root password enter one and when it's done installing everything open a shell/terminal and type this:
-mysql --user=root --password=YourMysqlRootPassword
-It should say something like this:
-
-Welcome to the MySQL monitor. Commands end with ; or \g.
-Your MySQL connection id is 4
-Server version: 5.0.60-log Ubuntu Linux mysql-5.0.60-r1
-
-Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
-
-mysql>
-
-Now type this:
-CREATE DATABASE fpdb;
-
-Next you need to create a user. Type this (replacing newPassword with the password you want the fpdb user to have - this can, but for security shouldn't, be the same as the root mysql password):
-GRANT ALL PRIVILEGES ON fpdb.* TO 'fpdb'@'localhost' IDENTIFIED BY 'newPassword' WITH GRANT OPTION;
-
-Then download one of the alpha2 archives from the sourceforge page at https://sourceforge.net/projects/fpdb/ and unpack it into a folder of your choice.
-
-Next create a directory called .fpdb (the . at the beginning is important) in your home directory, e.g. /home/steffen/.fpdb
-Then copy the default.conf file from the docs directory of the archive into this new folder.
-Finally edit default.conf with any texteditor and enter the fpdb password you entered above (in the GRANT ALL... command).
-
-This should be it, try double clicking pyfpdb/fpdb.py or open it from a shell with python /path/to/fpdb/pyfpdb/fpdb.py
-
-Now see readme-user.txt for usage instructions.
-
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/known-bugs-and-planned-features.txt b/docs/known-bugs-and-planned-features.txt
deleted file mode 100644
index a8a3f988..00000000
--- a/docs/known-bugs-and-planned-features.txt
+++ /dev/null
@@ -1,58 +0,0 @@
-Everything is subject to change and the order does not indicate priority. Patches for any of these or other features are very welcome, see readme-overview.txt for contacts.
-Please also see db-todo.txt
-
-before beta
-===========
-change to savannah?
-
-
-
-Any comment or print with "todo" in it in the sourcecode except what is marked todo in the menu
-make a quick benchmark of mysql and postgresql: import of my whole db, some tableviewer refreshes with and without updated file
-Make tab and enter work as sensible in GUIs and implement Ctrl+Q, Ctrl+X and Alt+F4 for close.
-use profile file for bulk import and table viewer settings and pathes
-check that we read sitout correctly in: Full Tilt Poker Game #6150325318: Table Bogside
-verify at least 2 or 3 sng hands
-
-no rush but before 1.0RC
-========================
-improve handling of dead hand before BB, see git101/7bd1631
-make DB version error offer reimport, recreation and continue.
-In many places there are unnecessary database accesses or it regenerates information it already had before or just generally does things in obscenely inefficient ways. Optimise this
-multi-select in bulk importer
-cut down action_types array size to appropriate length
-make the gui display errors
-log file
-move directory import code from gui to backend
-convert fpdb_import to not require passing "self", generally clean the parameter passing
-Doesn't handle Daylight Saving Time (I don't think at least)
-ensure that refresh still takes no more than 10 seks on my P3M-800 (a quick run on git15 indicates this is ok now), or 5 with remote DB
-select range of stakes and sng/mtt values and types for hud
-recognise somewhere if a file is still active and if so keep it open and only read new hands rather than detecting dupes
-return full ftp functionality
-
-can wait till 1.x
-=================
-in all importer: stop doing if site=="ftp", make class constants for site_id instead
-It treats fold due to disconnect as voluntary fold which is not ideal
-aliases
-repair hands where the seat lines are missing, happens when observing at FTP
-flags for storing the reason for winning (best hi, tie for best low, etc.) to DB. not sure actually if this is such a good idea remember that there can be multiple reasons for the same player in the same hand
-benchmark properly on mysql innodb, postgresql, more?
-rename things like this: ClassName.methodName and variableName. update codingstyle
-CLI (not ncurses, normal CLI) equivalent for fpdb.py
-optimise/simplify storing by creating the SQL statements depending on hand rather than calling different methods
-make range of activeSeats configurable for tv/hud
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/readme-dev.txt b/docs/readme-dev.txt
deleted file mode 100644
index c8b5cd3f..00000000
--- a/docs/readme-dev.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-Hi,
-This document is to serve as a little overview (later: full technical doc) for current and prospective developers with:
-a) introduction into the code structure
-b) organisational/legal things
-
-What to do?
-===========
-- Anything you want.
-- The most useful (because it's the most boring) would be to update print_hand.py, update the expected files (testdata/*.found.txt) and create more .found.txt to ensure import processing is running correctly.
-- There's a list of various bugs, deficiencies and important missing features in known_bugs_and_planned_features.txt.
-- In the main GUI there's various menu points marked with todo - all of these will have to be done eventually.
-
-If you want to take a look at coding-style.txt.
-Ideally use git (see git-instructions.txt for some commands) and let me know where to pull from, alternatively feel free to send patches or even just changed file in whatever code layout or naming convention you like best. I will, of course, still give you full credit.
-
-Contact/Communication
-=====================
-If you start working on something please open a bug or feature request at sf to avoid someone else from doing the same
-Please see readme-overview
-
-Dependencies
-============
-Please let me know before you add any new dependencies and ensure that they are source-compatible between *nix and Windows
-
-Code/File/Class Structure
-=========================
-Basically the code runs like this
-
-fpdb.py -> bulk importer tab (import_threaded.py) -> fpdb_import.py -> fpdb_parse_logic.py -> fpdb_save_to_db.py
-or
-fpdb.py -> table viewer tab (table_viewer.py) (todo: -> libTableViewer)
-
-All files call the simple methods that I just collected in fpdb_simple.py, to abstract the other files off the nitty gritty details as I was learning python.
-I'm currently working on (amongst other things) integrating everything into the fpdb.py GUI with a view to allow easy creation of a CLI client, too.
-
-Also see filelist.txt.
-
-How to Commit
-=============
-Please make sure you read and accept the copyright policy as stated in this file. Then see git-instructions.txt. Don't get me wrong, I hate all this legalese, but unfortunately it's kinda necessary.
-
-Copyright/Licensing
-===================
-Copyright by default is handled on a per-file basis. If you send in a patch or make a commit to an existing file it is done on the understanding that you transfer all rights (as far as legally possible in your jurisdiction) to the current copyright holder of that file, unless otherwise stated. If you create a new file please ensure to include a copyright and license statement.
-
-The licenses used by this project are the AGPL3 for code and FDL1.2 for documentation. See readme-overview.txt for reasons and if you wish to use fpdb with different licensing.
-
-Preferred File Formats
-======================
-Preferred: Where possible simple text-based formats, e.g. plain text (with Unix end of line char) or (X)HTML. Preferred picture format is PNG. IE-compability for HTML files is optional as IE was never meant to be a real web browser, if it were they would've implemented web standards.
-
-Also good: Other free and open formats, e.g. ODF.
-
-Not good: Any format that doesn't have full documentation freely and publicly available with a proper license for anyone to implement it. Sadly, Microsoft has chosen not fulfil these requirements for ISO MS OOXML to become a truly open standard.
-
-License (of this file)
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/readme-overview.txt b/docs/readme-overview.txt
deleted file mode 100644
index 825a61de..00000000
--- a/docs/readme-overview.txt
+++ /dev/null
@@ -1,86 +0,0 @@
-Summary
-=======
-A database program to track your online poker games, the behaviour of the other players and your winnings/losses. Supports Holdem, Omaha, Stud and Razz for cash games as well as SnG and MTT tournaments with more possibly coming in the future. Some of this is not yet working though, please see status.txt and known-bugs-and-planned-features.txt
-
-Contact
-=======
-Please note that this project has two hostings: one at assembla.com which holds are version control "central tree" (irrelevant for users) and everything else at http://sourceforge.net/projects/fpdb/.
-
-The best means of contact are the sourceforge page: Use the bug, feature request or patch functions or just post in the forum.
-
-Alternatively feel free to contact me directly:
-
-mail: steffen(at)sycamoretest.info
-jabber/xmpp/Google Talk: as above
-ICQ: 7806355
-MSN: steffenjf@gmx.de (don't email that)
-
-But you could send all my hand histories to yourself!
-=====================================================
-At the end of the day this comes down to a question of trust, but unlike Windows and the poker client software you don't have to trust fpdb blindly. You can:
-- Verify the source code yourself.
-- Convince or pay someone to verify the source code for you.
-- Use a personal firewall to completely block fpdb from the Internet
-- (for the uber-paranoid) Get yourself the free virtualisation software VirtualBox, set up a VM (virtual machine) to run fpdb but run the poker software on your real PC. Then cut the VM off the Internet, fpdb doesn't need it. If you have a PC made in the last few years this should run fast enough as well. Note that most Windows licenses do NOT permit you to use two Windows installations at once, even if they are on the same PC.
-
-Installing
-==========
-See the install-*.txt for your operating system. If your OS is missing or if you have problems let me know (contacts are further below). In particular I'd be happy to provide packages for GNU/Linux and *BSD distributions.
-
-Using it
-========
-See readme-user.txt
-If you have a problem, request or question see the contacts section below
-
-Changing it
-===========
-See readme-dev.txt
-
-Requirements
-============
-Software requirements are listed in requirements.txt
-As for hardware, my main test machine is a Pentium 3-M 800 with 256 RAM and Gentoo GNU/Linux
-(running the poker client through what most people will call emulation). So this
-program will have to work on that. If you run an even more ancient machine and
-its too slow let me know and I'll see what I can do :)
-
-Why Free Software?
-==================
-This program is released under the terms of the free/libre software license AGPL3 as released by the FSF. The AGPL3 protects your rights and those of the wider community. As Richard Stallman, one of the founders of the free software movement, put it: "Free software is a matter of liberty, not price. To understand the concept, you should think of free as in free speech, not as in free beer." (well, it is both really, like the right to vote used to be free)
-
-For example, a "pirated" copy of proprietary software X is free of charge, but you don't actually have a legal right to use it, you don't have any possibility to fix its bugs and you certainly don't have any legal right to share it with your friends. You also won't be able to get support, often not even security fixes. Actually, even if you pay hundreds of pounds for your program they deny your right to fix their errors for them. Imagine buying a car where you're not permitted (under threat of jail) to replace broken parts..
-
-With free/libre software (also known as open source software, or short FOSS or FLOSS) on the other hand you get all these freedoms:
-(note: the legally binding terms are in the license text, this is merely an amateur summary so normal people don't have to read pages of legalese)
-
-Freedom 0: The freedom to use: To run the program, for any purpose. Free of Charge.
-Freedom 1: The freedom to study and help yourself. This freedom guarantees your right to study and learn from the source code of the program, and to fix it if it is broken. If you're not a programmer yourself the developers will generally be happy to fix it for you, often even for free. Failing that you can always pay someone from the money you saved on not having to pay for it.
-Freedom 2: The freedom to be a decent human being and help your neighbour: I don't threaten you with lawsuits or jail time if you share with your friends and neighbours, subject to the very modest restrictions of the AGPL3.
-Freedom 3: The freedom to improve the program and release your improvements to the public (or parts thereof) so that the whole community benefits. Note that you are PERMITTED, but not REQUIRED to distribute your changes. If you do distribute your changes you must do so under the terms of the AGPL3 however.
-
-Note that this is the license - I retain full copyright over my code, including the right to change the license for future versions. I do not intend to do this however. In any case, any version I released under AGPL3 remains available under that license forever, or more accurately until my copyright expires at which point it goes into the public domain.
-
-I reject the concept of software patents as a crime and under the European Patent Agreement software patents - even if you mislabel them as "computer-implemented inventions" or whatever - are explicitly prohibited.
-
-Can I get/use this under a different license?
-=============================================
-The short answer: Maybe.
-The long one: As detailed, I fully support what the FSF does and aims to achieve with the GPL. However, I realise that many free software developers don't object to closed source, some don't even object to closed source profiteering of their charity, and I don't think I have any right to go and tell them they're wrong.
-So if anyone wishes to use all or part of my code in another free software/open source project with an AGPL3-incompatible license such as BSD then let me know and we'll figure out a solution that makes everyone happy.
-If you wish to use all or part of this in closed source let me know how much if anything that is worth to you and I'm sure we'll be able to reach an agreement. Note that you are NOT permitted to just use fpdb code in closed source development whether in-house or by an independent software developer, you will NEED an additionally agreement with me to get fpdb under different licensing conditions.
-
-
-License of this Document
-========================
-The views expressed in this document are those of Steffen Jobbagy-Felso, other members of the fpdb team and external contributors may or may not agree.
-
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/readme-user.txt b/docs/readme-user.txt
deleted file mode 100644
index 6d3d1f76..00000000
--- a/docs/readme-user.txt
+++ /dev/null
@@ -1,43 +0,0 @@
-Before you do this make sure you setup the dependencies, the database, user, tables and config file.
-
-Running it
-==========
-If you have python setup properly you can execute it by double clicking pyfpdb/fpdb.py.
-
-Note however that all error messages are currently only printed if you call it from a shell. It'll be much easier to diagnose possible problems (which are likely in alpha stage) if you run it from a shell. In Windows XP it seems to automatically open a shell window with the fpdb window where you can see the command line output.
-
-In Linux/MacOS/*BSD, e.g. if its in /home/sycamore/fpdb/, do this:
-cd /home/sycamore/fpdb/pyfpdb
-python fpdb.py
-
-
-That will start the main GUI.
-
-Have a look at the menus, the stuff that is marked todo is not yet implemented.
-
-The main things are the bulk importer and the table viewer. To use the importer open it from the menu (import files and directories). You can set a few options at the bottom, then select a folder or single file in the main are and click Import. Please report any errors by one of the contacts listed in readme-overview.txt.
-Currently this will block the interface, but you can open another instance of this program e.g. if you wanna play whilst a big import is running.
-
-Please check the output at the shell for errors, if there are any please get in touch by one of the methods listed in readme-overview.txt
-
-Table Viewer (tv)
-=================
-To use the table viewer open it from the menu, select the hand history file of the table you're at, and click the Import&Read&Refresh button. The abbreviations there are explained in abbreviations.txt, but feel free to ask. Note that most poker software will only create the file once the first hand you payed to play is finished.
-In each column there is either just the number (hand count for current stake, range of seats and type of game) or a percentage and the number of hands that this percentage is based on. For example, in W$@SD (won $ at shodown) the number in brackets is how many showdowns that player has seen.
-
-Reimporting
-===========
-Currently on most updates a reimport of the whole database is required. To do this open fpdb, click the menu Database and select Create/Recreate tables. Then import all your history files again.
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/docs/readme.txt b/docs/readme.txt
new file mode 100644
index 00000000..03e071d3
--- /dev/null
+++ b/docs/readme.txt
@@ -0,0 +1,64 @@
+README.txt
+updated 26 March 2009, REB
+
+fpdb - Free Poker Database
+
+The most accurate and up-to-date information on fpdb will be found in the wiki:
+http://fpdb.wiki.sourceforge.net/
+
+Other resources are:
+ Mailing list: http://sourceforge.net/mailarchive/forum.php?forum_name=fpdb-main
+ Chat room(irc): #fpdb on freenode.net
+
+fpdb is a free program for use with on line poker. It provides:
+ Tracking of your results and statistics.
+ Tracking of opponents' results statistics.
+ Win/loss graphing
+ Heads Up Display (HUD) with a variety of statistics
+ Display of mucked cards in the HUD
+
+fpdb supports:
+ Sites:
+ PokerStars
+ Full Tilt Poker
+ Everleaf Network
+ Other sites are under development and are easily added
+
+ Games:
+ Holdem
+ Omaha (incl Hi/low)
+ 7 Card Stud (incl Hi/low)
+ Razz
+ Draw support is under development
+ Mixed Games -- HUD under development
+
+ Operating Systems:
+ Linux and other Unix-like, using X
+ Windows
+ Mac OS/X -- no support for HUD
+
+ Databases:
+ MySQL
+ PostgreSQL
+ SQLite under development
+
+Downloads:
+ Releases: http://sourceforge.net/project/showfiles.php?group_id=226872
+ Development code via git: http://www.assembla.com/spaces/free_poker_tools/trac_git_tool
+
+Developers:
+ At least 7 people have contributed code or patches. Others are welcome.
+
+License
+=======
+Trademarks of third parties have been used under Fair Use or similar laws.
+
+Copyright 2008 Steffen Jobbagy-Felso
+Copyright 2009 Ray E. Barker
+Permission is granted to copy, distribute and/or modify this
+document under the terms of the GNU Free Documentation License,
+Version 1.2 as published by the Free Software Foundation; with
+no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
+Texts. A copy of the license can be found in fdl-1.2.txt
+
+fpdb itself is licensed under AGPLv3, see agpl-3.0.txt.
diff --git a/docs/status.txt b/docs/status.txt
deleted file mode 100644
index 3ab5fbf8..00000000
--- a/docs/status.txt
+++ /dev/null
@@ -1,76 +0,0 @@
-For all support please note that the tables WILL be changed, almost certainly without keeping backwards compatibility. Therefore you should keep your history files after import so you can re-import when necessary. Should you lose history files and need a "database updater" let me know.
-
-If support for another site/game would encourage you to help with this software please let me know at steffen@sycamoretest.info.
-
-IMPORTANT: There appears to be a bug in at least up to git34 in reading WtSD/W$wsF/W$SD
-
-Holdem/Omaha ring games on PokerStars
-======================================
-Works, quite well tested, works in table viewer and is useful now. Functionality is quite limited so far though. This includes the holdem/omaha parts of HORSE, HOSE and any other mixed game
-
-Stud/Razz ring games on PokerStars
-==================================
-Broken - used to work, hardly tested. Needs to be updated to new infrastructure using a HudData table rather than hands_players_flags. Will fix this shortly.
-
-Tournaments/SnGs
-================
-Broken - used to work, hardly tested. Needs to be updated to new infrastructure.. Will probably fix this shortly
-
-Full Tilt Poker
-===============
-Might work - used to work and was very well test. It should import them (except HudData), but I believe the table viewer won't work. Would be easy to fix I think, volunteers welcome. This used to work in a pre-alpha but basically was left behind during updates to the other stuff.
-
-Other Sites
-===========
-Patches/Volunteers welcome. Should be quite easy.
-
-GUI
-===
-Alpha - the infrastructure stands and is fast enough, now "just" need to add more functionality.
-
-HUD
-===
-Not started - volunteers welcome. I found a *nix utility based on xlib that does half the work for this (most of the other half is already in the table viewer), see http://www.roard.com/docs/cookbook/cbsu19.html. There's also a python implementation of xlib which should run even on Windows.
-
-Packaging
-=========
-Gentoo GNU/Linux: I'll make ebuilds, if you want one now let me know.
-Other free/libre systems (e.g. other GNU/Linux-Distros, *BSD, and I'd love to help in getting this to work on any Hurd based system): Let me know what you use (Distribution, version and CPU type) and I'll make a package.
-Windows/MacOSX: Manual installation of dependencies for now, integrated installer would be nice - volunteers welcome, but I'll do it eventually in any case.
-
-Regression Testing
-==================
-The query scripts are done-ish, need to verify more data so it can be used in automated regression testing.
-
-Database Backends
-=================
-- MySQL InnoDB is the default
-- PostgreSQL should work but I haven't tried it. If it doesn't please let me know.
-- MySQL ISAM won't be supported since it is not transactional
-
-Legal
-=====
-General: This will offer more or less the same kind of functionality as HM and PT so there shouldn't be any problem on any site that allows tracking.
-PS: I have asked them and they said that due to the fast changing nature
- of pre-release software they don't review that. However, looking at their
- posted guidelines we're fine
-FTP: I sent them an email and what I described there was ok for them.
-I will write them again for "certification" on release of 1.0
-
-To avoid any misunderstandings, PS and FTP obviously do not sponsor, endorse, or support fpdb. They allow using it, that's all. Any problems with fpdb should be reported to us, not the poker site.
-
-A note on viewing/tracking mucked hands. Many people will say this is cheating. I agree. However, I don't make the rules on these sites. The sites that store mucked hands into the history file clearly think that being able to see other people's mucked hands is ok. This software - like HM and PT - merely takes info provided by the poker site and makes it more easily accessible.
-Apparently PS has now turned this off :)
-
-License
-=======
-Trademarks of third parties have been used under Fair Use or similar laws.
-
-Copyright 2008 Steffen Jobbagy-Felso
-Permission is granted to copy, distribute and/or modify this
-document under the terms of the GNU Free Documentation License,
-Version 1.2 as published by the Free Software Foundation; with
-no Invariant Sections, no Front-Cover Texts, and with no Back-Cover
-Texts. A copy of the license can be found in fdl-1.2.txt
-
-The program itself is licensed under AGPLv3, see agpl-3.0.txt
diff --git a/packaging/gentoo/fpdb-1.0_alpha8_p137.ebuild b/packaging/gentoo/fpdb-0.10.ebuild
similarity index 94%
rename from packaging/gentoo/fpdb-1.0_alpha8_p137.ebuild
rename to packaging/gentoo/fpdb-0.10.ebuild
index c55903f3..a41f653b 100644
--- a/packaging/gentoo/fpdb-1.0_alpha8_p137.ebuild
+++ b/packaging/gentoo/fpdb-0.10.ebuild
@@ -1,7 +1,7 @@
# Copyright 1999-2008 Gentoo Foundation
# Gentoo had nothing to do with the production of this ebuild, but I'm pre-emptively transferring all copyrights (as far as legally possible under my local jurisdiction) to them.
# Distributed under the terms of the GNU General Public License v2
-# $Header: /var/cvsroot/gentoo-x86/games-util/fpdb/fpdb-1.0_alpha8_p137.ebuild,v 1.0 2008/10/17 steffen@sycamoretest.info Exp $
+# $Header: /var/cvsroot/gentoo-x86/games-util/fpdb/fpdb-0.10.ebuild,v 1.0 2009/1/30 steffen@sycamoretest.info Exp $
NEED_PYTHON=2.3
diff --git a/packaging/gentoo/fpdb-1.0_alpha9_p142.ebuild b/packaging/gentoo/fpdb-1.0_alpha9_p142.ebuild
deleted file mode 100644
index c55903f3..00000000
--- a/packaging/gentoo/fpdb-1.0_alpha9_p142.ebuild
+++ /dev/null
@@ -1,62 +0,0 @@
-# Copyright 1999-2008 Gentoo Foundation
-# Gentoo had nothing to do with the production of this ebuild, but I'm pre-emptively transferring all copyrights (as far as legally possible under my local jurisdiction) to them.
-# Distributed under the terms of the GNU General Public License v2
-# $Header: /var/cvsroot/gentoo-x86/games-util/fpdb/fpdb-1.0_alpha8_p137.ebuild,v 1.0 2008/10/17 steffen@sycamoretest.info Exp $
-
-NEED_PYTHON=2.3
-
-#inherit distutils
-
-MY_P="fpdb-${PV}"
-DESCRIPTION="A database program to track your online poker games"
-HOMEPAGE="https://sourceforge.net/projects/fpdb/"
-SRC_URI="mirror://sourceforge/fpdb/${MY_P}.tar.bz2"
-
-LICENSE="AGPL-3"
-SLOT="0"
-KEYWORDS="~amd64 ~x86"
-#note: this should work on other architectures too, please send me your experiences
-IUSE=""
-
-RDEPEND="virtual/mysql
- dev-python/mysql-python
- >=x11-libs/gtk+-2.10
- dev-python/pygtk
- dev-python/numpy
- dev-python/matplotlib"
-
-DEPEND="${RDEPEND}"
-
-src_install() {
- DIRINST="${D}usr/share/games/fpdb/"
- mkdir -p "${DIRINST}"
- cp -R * "${DIRINST}" || die
-
- DIRBIN="${D}usr/games/bin/"
- mkdir -p "${DIRBIN}"
- #echo "pathes"
- #echo "${DIRINST}pyfpdb/fpdb.py"
- #echo "${DIRBIN}fpdb.py"
- #echo
- echo "cd /usr/share/games/fpdb/pyfpdb/ && python fpdb.py" > "${DIRBIN}fpdb" || die
- chmod 755 "${DIRBIN}fpdb" || die
-}
-
-#src_test() {
-#}
-
-pkg_postinst() {
- elog "Fpdb has been installed and can be called by executing /usr/games/bin/fpdb"
- elog "You need to perform a couple more steps manually."
- elog "Please also make sure you followed instructions from previous emerges, in particular make sure you configured mysql and set a root pw for it"
- elog "Now run this command to connect to MySQL: mysql --user=root --password=yourPassword"
- elog "In the mysql command line interface you need to type these two lines (make sure you get the ; at the end)"
- elog "In the second line replace \"newPassword\" with a password of your choice"
- elog "CREATE DATABASE fpdb;"
- elog "GRANT ALL PRIVILEGES ON fpdb.* TO 'fpdb'@'localhost' IDENTIFIED BY 'newPassword' WITH GRANT OPTION;"
- elog "Finally copy the default config file from ${DIRINST}docs/default.conf to ~/.fpdb/ for every user that is to use fpdb."
- elog "You will need to edit the default.conf, in particular you need to replace the password with what you entered in the \"GRANT ALL...\""
- elog "Finally run the GUI and click the menu database -> recreate tables"
- elog "That's it! See our webpage at http://fpdb.sourceforge.net for more documentation"
- elog " "
-}
diff --git a/pyfpdb/BetfairToFpdb.py b/pyfpdb/BetfairToFpdb.py
new file mode 100755
index 00000000..bc1d17c9
--- /dev/null
+++ b/pyfpdb/BetfairToFpdb.py
@@ -0,0 +1,241 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright 2008, Carl Gherardi
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+########################################################################
+
+import sys
+import logging
+from HandHistoryConverter import *
+
+# Betfair HH format
+
+class Betfair(HandHistoryConverter):
+
+ # Static regexes
+ re_GameInfo = re.compile("^(?PNL|PL|) (?P\$|)?(?P[.0-9]+)/\$?(?P[.0-9]+) (?P(Texas Hold\'em|Omaha Hi|Razz))", re.MULTILINE)
+ re_SplitHands = re.compile(r'\n\n+')
+ re_HandInfo = re.compile("\*\*\*\*\* Betfair Poker Hand History for Game (?P[0-9]+) \*\*\*\*\*\n(?PNL|PL|) (?P\$|)?(?P[.0-9]+)/\$?(?P[.0-9]+) (?P(Texas Hold\'em|Omaha Hi|Razz)) - (?P[a-zA-Z]+, [a-zA-Z]+ \d+, \d\d:\d\d:\d\d GMT \d\d\d\d)\nTable (?P[ a-zA-Z0-9]+) \d-max \(Real Money\)\nSeat (?P[0-9]+)", re.MULTILINE)
+ re_Button = re.compile(ur"^Seat (?P\d+) is the button", re.MULTILINE)
+ re_PlayerInfo = re.compile("Seat (?P[0-9]+): (?P.*)\s\(\s(\$(?P[.0-9]+)) \)")
+ re_Board = re.compile(ur"\[ (?P.+) \]")
+
+ def __init__(self, in_path = '-', out_path = '-', follow = False, autostart=True):
+ """\
+in_path (default '-' = sys.stdin)
+out_path (default '-' = sys.stdout)
+follow : whether to tail -f the input"""
+ HandHistoryConverter.__init__(self, in_path, out_path, sitename="Betfair", follow=follow) # Call super class init.
+ logging.info("Initialising Betfair converter class")
+ self.filetype = "text"
+ self.codepage = "cp1252"
+ if autostart:
+ self.start()
+
+
+ def compilePlayerRegexs(self, hand):
+ players = set([player[1] for player in hand.players])
+ if not players <= self.compiledPlayers: # x <= y means 'x is subset of y'
+ # we need to recompile the player regexs.
+ self.compiledPlayers = players
+ player_re = "(?P" + "|".join(map(re.escape, players)) + ")"
+ logging.debug("player_re: " + player_re)
+ self.re_PostSB = re.compile("^%s posts small blind \[\$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_PostBB = re.compile("^%s posts big blind \[\$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_Antes = re.compile("^%s antes asdf sadf sadf" % player_re, re.MULTILINE)
+ self.re_BringIn = re.compile("^%s antes asdf sadf sadf" % player_re, re.MULTILINE)
+ self.re_PostBoth = re.compile("^%s posts small \& big blinds \[\$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_HeroCards = re.compile("^Dealt to %s \[ (?P.*) \]" % player_re, re.MULTILINE)
+ self.re_Action = re.compile("^%s (?Pbets|checks|raises to|raises|calls|folds)(\s\[\$(?P[.\d]+)\])?" % player_re, re.MULTILINE)
+ self.re_ShowdownAction = re.compile("^%s shows \[ (?P.*) \]" % player_re, re.MULTILINE)
+ self.re_CollectPot = re.compile("^%s wins \$(?P[.\d]+) (.*?\[ (?P.*?) \])?" % player_re, re.MULTILINE)
+ self.re_SitsOut = re.compile("^%s sits out" % player_re, re.MULTILINE)
+ self.re_ShownCards = re.compile(r"%s (?P[0-9]+) (?Padsfasdf)" % player_re, re.MULTILINE)
+
+ def readSupportedGames(self):
+ return [["ring", "hold", "nl"]
+ ]
+
+ def determineGameType(self, handText):
+ info = {'type':'ring'}
+
+ m = self.re_GameInfo.search(handText)
+ if not m:
+ logging.info('GameInfo regex did not match')
+ return None
+
+ mg = m.groupdict()
+
+ # translations from captured groups to our info strings
+ limits = { 'NL':'nl', 'PL':'pl', 'Limit':'fl' }
+ games = { # base, category
+ "Texas Hold'em" : ('hold','holdem'),
+ 'Omaha Hi' : ('hold','omahahi'),
+ 'Razz' : ('stud','razz'),
+ '7 Card Stud' : ('stud','studhi')
+ }
+ currencies = { u' €':'EUR', '$':'USD', '':'T$' }
+ if 'LIMIT' in mg:
+ info['limitType'] = limits[mg['LIMIT']]
+ if 'GAME' in mg:
+ (info['base'], info['category']) = games[mg['GAME']]
+ if 'SB' in mg:
+ info['sb'] = mg['SB']
+ if 'BB' in mg:
+ info['bb'] = mg['BB']
+ if 'CURRENCY' in mg:
+ info['currency'] = currencies[mg['CURRENCY']]
+ # NB: SB, BB must be interpreted as blinds or bets depending on limit type.
+
+ return info
+
+ def readHandInfo(self, hand):
+ m = self.re_HandInfo.search(hand.handText)
+ if(m == None):
+ logging.info("Didn't match re_HandInfo")
+ logging.info(hand.handText)
+ return None
+ logging.debug("HID %s, Table %s" % (m.group('HID'), m.group('TABLE')))
+ hand.handid = m.group('HID')
+ hand.tablename = m.group('TABLE')
+ hand.starttime = time.strptime(m.group('DATETIME'), "%A, %B %d, %H:%M:%S GMT %Y")
+ #hand.buttonpos = int(m.group('BUTTON'))
+
+ def readPlayerStacks(self, hand):
+ m = self.re_PlayerInfo.finditer(hand.handText)
+ for a in m:
+ hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
+
+ #Shouldn't really dip into the Hand object, but i've no idea how to tell the length of iter m
+ if len(hand.players) < 2:
+ logging.info("readPlayerStacks: Less than 2 players found in a hand")
+
+ def markStreets(self, hand):
+ m = re.search(r"\*\* Dealing down cards \*\*(?P.+(?=\*\* Dealing Flop \*\*)|.+)"
+ r"(\*\* Dealing Flop \*\*(?P \[ \S\S, \S\S, \S\S \].+(?=\*\* Dealing Turn \*\*)|.+))?"
+ r"(\*\* Dealing Turn \*\*(?P \[ \S\S \].+(?=\*\* Dealing River \*\*)|.+))?"
+ r"(\*\* Dealing River \*\*(?P \[ \S\S \].+))?", hand.handText,re.DOTALL)
+
+ hand.addStreets(m)
+
+
+ def readCommunityCards(self, hand, street): # street has been matched by markStreets, so exists in this hand
+ if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
+ m = self.re_Board.search(hand.streets[street])
+ hand.setCommunityCards(street, m.group('CARDS').split(', '))
+
+ def readBlinds(self, hand):
+ try:
+ m = self.re_PostSB.search(hand.handText)
+ hand.addBlind(m.group('PNAME'), 'small blind', m.group('SB'))
+ except: # no small blind
+ hand.addBlind(None, None, None)
+ for a in self.re_PostBB.finditer(hand.handText):
+ hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
+ for a in self.re_PostBoth.finditer(hand.handText):
+ hand.addBlind(a.group('PNAME'), 'small & big blinds', a.group('SBBB'))
+
+ def readAntes(self, hand):
+ logging.debug("reading antes")
+ for player in m:
+ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
+ hand.addAnte(player.group('PNAME'), player.group('ANTE'))
+
+ def readBringIn(self, hand):
+ m = self.re_BringIn.search(hand.handText,re.DOTALL)
+ if m:
+ logging.debug("Player bringing in: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
+ hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
+ else:
+ logging.warning("No bringin found")
+
+ def readButton(self, hand):
+ hand.buttonpos = int(self.re_Button.search(hand.handText).group('BUTTON'))
+
+ def readHeroCards(self, hand):
+ m = self.re_HeroCards.search(hand.handText)
+ if(m == None):
+ #Not involved in hand
+ hand.involved = False
+ else:
+ hand.hero = m.group('PNAME')
+ # "2c, qh" -> set(["2c","qc"])
+ # Also works with Omaha hands.
+ cards = m.group('CARDS')
+ cards = [c.strip() for c in cards.split(',')]
+ hand.addHoleCards(cards, m.group('PNAME'))
+
+ def readStudPlayerCards(self, hand, street):
+ # balh blah blah
+ pass
+
+ def readAction(self, hand, street):
+ m = self.re_Action.finditer(hand.streets[street])
+ for action in m:
+ if action.group('ATYPE') == 'raises to':
+ hand.addRaiseTo( street, action.group('PNAME'), action.group('BET') )
+# elif action.group('ATYPE') == ' completes it to':
+# hand.addComplete( street, action.group('PNAME'), action.group('BET') )
+ elif action.group('ATYPE') == 'calls':
+ hand.addCall( street, action.group('PNAME'), action.group('BET') )
+ elif action.group('ATYPE') == 'bets':
+ hand.addBet( street, action.group('PNAME'), action.group('BET') )
+ elif action.group('ATYPE') == 'folds':
+ hand.addFold( street, action.group('PNAME'))
+ elif action.group('ATYPE') == 'checks':
+ hand.addCheck( street, action.group('PNAME'))
+ else:
+ print "DEBUG: unimplemented readAction: '%s' '%s'" %(action.group('PNAME'),action.group('ATYPE'),)
+
+
+ def readShowdownActions(self, hand):
+ for shows in self.re_ShowdownAction.finditer(hand.handText):
+ cards = shows.group('CARDS')
+ cards = cards.split(', ')
+ hand.addShownCards(cards, shows.group('PNAME'))
+
+ def readCollectPot(self,hand):
+ for m in self.re_CollectPot.finditer(hand.handText):
+ hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT'))
+
+ def readShownCards(self,hand):
+ for m in self.re_ShownCards.finditer(hand.handText):
+ if m.group('CARDS') is not None:
+ cards = m.group('CARDS')
+ cards = cards.split(', ')
+ hand.addShownCards(cards=None, player=m.group('PNAME'), holeandboard=cards)
+
+
+if __name__ == "__main__":
+ parser = OptionParser()
+ parser.add_option("-i", "--input", dest="ipath", help="parse input hand history", default="regression-test-files/betfair/befair.02.04.txt")
+ parser.add_option("-o", "--output", dest="opath", help="output translation to", default="-")
+ parser.add_option("-f", "--follow", dest="follow", help="follow (tail -f) the input", action="store_true", default=False)
+ parser.add_option("-q", "--quiet",
+ action="store_const", const=logging.CRITICAL, dest="verbosity", default=logging.INFO)
+ parser.add_option("-v", "--verbose",
+ action="store_const", const=logging.INFO, dest="verbosity")
+ parser.add_option("--vv",
+ action="store_const", const=logging.DEBUG, dest="verbosity")
+
+ (options, args) = parser.parse_args()
+
+ LOG_FILENAME = './logging.out'
+ logging.basicConfig(filename=LOG_FILENAME,level=options.verbosity)
+
+ e = Betfair(in_path = options.ipath, out_path = options.opath, follow = options.follow)
+
diff --git a/pyfpdb/Cards0-HMHUD.png b/pyfpdb/Cards0-HMHUD.png
new file mode 100644
index 00000000..2c64fc9e
Binary files /dev/null and b/pyfpdb/Cards0-HMHUD.png differ
diff --git a/pyfpdb/Configuration.py b/pyfpdb/Configuration.py
index 9b8f4f08..47617023 100755
--- a/pyfpdb/Configuration.py
+++ b/pyfpdb/Configuration.py
@@ -3,7 +3,7 @@
Handles HUD configuration files.
"""
-# Copyright 2008, Ray E. Barker
+# Copyright 2008, 2009, Ray E. Barker
#
# This program is free software; you can redistribute it and/or modify
@@ -32,14 +32,39 @@ import shutil
import xml.dom.minidom
from xml.dom.minidom import Node
+def fix_tf(x, default = True):
+# The xml parser doesn't translate "True" to True. Therefore, we never get
+# True or False from the parser only "True" or "False". So translate the
+# string to the python boolean representation.
+ if x == "1" or x == 1 or string.lower(x) == "true" or string.lower(x) == "t":
+ return True
+ if x == "0" or x == 0 or string.lower(x) == "false" or string.lower(x) == "f":
+ return False
+ return default
+
class Layout:
- def __init__(self, max):
- self.max = int(max)
- self.location = []
- for i in range(self.max + 1): self.location.append(None)
+ def __init__(self, node):
+
+ self.max = int( node.getAttribute('max') )
+ if node.hasAttribute('fav_seat'): self.fav_seat = int( node.getAttribute('fav_seat') )
+ self.width = int( node.getAttribute('width') )
+ self.height = int( node.getAttribute('height') )
+ self.location = []
+ self.location = map(lambda x: None, range(self.max+1)) # fill array with max seats+1 empty entries
+
+ for location_node in node.getElementsByTagName('location'):
+ if location_node.getAttribute('seat') != "":
+ self.location[int( location_node.getAttribute('seat') )] = (int( location_node.getAttribute('x') ), int( location_node.getAttribute('y')))
+ elif location_node.getAttribute('common') != "":
+ self.common = (int( location_node.getAttribute('x') ), int( location_node.getAttribute('y')))
+
def __str__(self):
- temp = " Layout = %d max, width= %d, height = %d, fav_seat = %d\n" % (self.max, self.width, self.height, self.fav_seat)
+ temp = " Layout = %d max, width= %d, height = %d" % (self.max, self.width, self.height)
+ if hasattr(self, 'fav_seat'): temp = temp + ", fav_seat = %d\n" % self.fav_seat
+ else: temp = temp + "\n"
+ if hasattr(self, "common"):
+ temp = temp + " Common = (%d, %d)\n" % (self.common[0], self.common[1])
temp = temp + " Locations = "
for i in range(1, len(self.location)):
temp = temp + "(%d,%d)" % self.location[i]
@@ -58,22 +83,15 @@ class Site:
self.hudbgcolor = node.getAttribute("bgcolor")
self.hudfgcolor = node.getAttribute("fgcolor")
self.converter = node.getAttribute("converter")
- self.enabled = node.getAttribute("enabled")
self.aux_window = node.getAttribute("aux_window")
self.font = node.getAttribute("font")
self.font_size = node.getAttribute("font_size")
+ self.use_frames = node.getAttribute("use_frames")
+ self.enabled = fix_tf(node.getAttribute("enabled"), default = True)
self.layout = {}
-
+
for layout_node in node.getElementsByTagName('layout'):
- max = int( layout_node.getAttribute('max') )
- lo = Layout(max)
- lo.fav_seat = int( layout_node.getAttribute('fav_seat') )
- lo.width = int( layout_node.getAttribute('width') )
- lo.height = int( layout_node.getAttribute('height') )
-
- for location_node in layout_node.getElementsByTagName('location'):
- lo.location[int( location_node.getAttribute('seat') )] = (int( location_node.getAttribute('x') ), int( location_node.getAttribute('y')))
-
+ lo = Layout(layout_node)
self.layout[lo.max] = lo
def __str__(self):
@@ -104,7 +122,12 @@ class Game:
self.db = node.getAttribute("db")
self.rows = int( node.getAttribute("rows") )
self.cols = int( node.getAttribute("cols") )
- self.aux = node.getAttribute("aux")
+
+ aux_text = node.getAttribute("aux")
+ aux_list = aux_text.split(',')
+ for i in range(0, len(aux_list)):
+ aux_list[i] = aux_list[i].strip()
+ self.aux = aux_list
self.stats = {}
for stat_node in node.getElementsByTagName('stat'):
@@ -155,21 +178,23 @@ class Aux_window:
def __init__(self, node):
for (name, value) in node.attributes.items():
setattr(self, name, value)
-# self.name = node.getAttribute("mw_name")
-# self.cards = node.getAttribute("deck")
-# self.card_wd = node.getAttribute("card_wd")
-# self.card_ht = node.getAttribute("card_ht")
-# self.rows = node.getAttribute("rows")
-# self.cols = node.getAttribute("cols")
-# self.format = node.getAttribute("stud")
+
+ self.layout = {}
+ for layout_node in node.getElementsByTagName('layout'):
+ lo = Layout(layout_node)
+ self.layout[lo.max] = lo
def __str__(self):
temp = 'Aux = ' + self.name + "\n"
for key in dir(self):
if key.startswith('__'): continue
+ if key == 'layout': continue
value = getattr(self, key)
if callable(value): continue
temp = temp + ' ' + key + " = " + value + "\n"
+
+ for layout in self.layout:
+ temp = temp + "%s" % self.layout[layout]
return temp
class Popup:
@@ -189,10 +214,13 @@ class Import:
def __init__(self, node):
self.interval = node.getAttribute("interval")
self.callFpdbHud = node.getAttribute("callFpdbHud")
- self.hhArchiveBase = node.getAttribute("hhArchiveBase")
+ self.hhArchiveBase = node.getAttribute("hhArchiveBase")
+ self.saveActions = fix_tf(node.getAttribute("saveActions"), True)
+ self.fastStoreHudCache = fix_tf(node.getAttribute("fastStoreHudCache"), False)
def __str__(self):
- return " interval = %s\n callFpdbHud = %s\n hhArchiveBase = %s" % (self.interval, self.callFpdbHud, self.hhArchiveBase)
+ return " interval = %s\n callFpdbHud = %s\n hhArchiveBase = %s\n saveActions = %s\n fastStoreHudCache = %s\n" \
+ % (self.interval, self.callFpdbHud, self.hhArchiveBase, self.saveActions, self.fastStoreHudCache)
class Tv:
def __init__(self, node):
@@ -205,13 +233,14 @@ class Tv:
(self.combinedStealFold, self.combined2B3B, self.combinedPostflop) )
class Config:
- def __init__(self, file = None):
+ def __init__(self, file = None, dbname = 'fpdb'):
# "file" is a path to an xml file with the fpdb/HUD configuration
# we check the existence of "file" and try to recover if it doesn't exist
+ self.dbname = dbname
self.default_config_path = self.get_default_config_path()
- if not file == None: # configuration file path has been passed
+ if file != None: # configuration file path has been passed
if not os.path.exists(file):
print "Configuration file %s not found. Using defaults." % (file)
sys.stderr.write("Configuration file %s not found. Using defaults." % (file))
@@ -222,7 +251,7 @@ class Config:
if file == None: # no config file in the normal places
file = self.find_example_config() #Look for an example file to edit
- if not file == None:
+ if file != None:
pass
if file == None: # that didn't work either, just die
@@ -283,7 +312,7 @@ class Config:
tv = Tv(node = tv_node)
self.tv = tv
- db = self.get_db_parameters('fpdb')
+ db = self.get_db_parameters()
if db['db-password'] == 'YOUR MYSQL PASSWORD':
df_file = self.find_default_conf()
if df_file == None: # this is bad
@@ -357,6 +386,11 @@ class Config:
if site_node.getAttribute("site_name") == site:
return site_node
+ def get_aux_node(self, aux):
+ for aux_node in self.doc.getElementsByTagName("aw"):
+ if aux_node.getAttribute("name") == aux:
+ return aux_node
+
def get_db_node(self, db_name):
for db_node in self.doc.getElementsByTagName("database"):
if db_node.getAttribute("db_name") == db_name:
@@ -371,12 +405,17 @@ class Config:
return layout_node
def get_location_node(self, layout_node, seat):
- for location_node in layout_node.getElementsByTagName("location"):
- if int( location_node.getAttribute("seat") ) == int( seat ):
- return location_node
+ if seat == "common":
+ for location_node in layout_node.getElementsByTagName("location"):
+ if location_node.hasAttribute("common"):
+ return location_node
+ else:
+ for location_node in layout_node.getElementsByTagName("location"):
+ if int( location_node.getAttribute("seat") ) == int( seat ):
+ return location_node
def save(self, file = None):
- if not file == None:
+ if file != None:
f = open(file, 'w')
self.doc.writexml(f)
f.close()
@@ -397,63 +436,92 @@ class Config:
location_node.setAttribute("y", str( locations[i-1][1] ))
self.supported_sites[site_name].layout[max].location[i] = ( locations[i-1][0], locations[i-1][1] )
- def get_db_parameters(self, name = None):
- if name == None: name = 'fpdb'
+ def edit_aux_layout(self, aux_name, max, width = None, height = None, locations = None):
+ aux_node = self.get_aux_node(aux_name)
+ layout_node = self.get_layout_node(aux_node, max)
+ if layout_node == None:
+ print "aux node not found"
+ return
+ print "editing locations =", locations
+ for (i, pos) in locations.iteritems():
+ location_node = self.get_location_node(layout_node, i)
+ location_node.setAttribute("x", str( locations[i][0] ))
+ location_node.setAttribute("y", str( locations[i][1] ))
+ if i == "common":
+ self.aux_windows[aux_name].layout[max].common = ( locations[i][0], locations[i][1] )
+ else:
+ self.aux_windows[aux_name].layout[max].location[i] = ( locations[i][0], locations[i][1] )
+
+ def get_db_parameters(self):
db = {}
- try:
- db['db-databaseName'] = name
- db['db-host'] = self.supported_databases[name].db_ip
- db['db-user'] = self.supported_databases[name].db_user
- db['db-password'] = self.supported_databases[name].db_pass
- db['db-server'] = self.supported_databases[name].db_server
- if string.lower(self.supported_databases[name].db_server) == 'mysql':
- db['db-backend'] = 2
- elif string.lower(self.supported_databases[name].db_server) == 'postgresql':
- db['db-backend'] = 3
- else: db['db-backend'] = None # this is big trouble
- except:
- pass
+ name = self.dbname
+ try: db['db-databaseName'] = name
+ except: pass
+
+ try: db['db-host'] = self.supported_databases[name].db_ip
+ except: pass
+
+ try: db['db-user'] = self.supported_databases[name].db_user
+ except: pass
+
+ try: db['db-password'] = self.supported_databases[name].db_pass
+ except: pass
+
+ try: db['db-server'] = self.supported_databases[name].db_server
+ except: pass
+
+ if string.lower(self.supported_databases[name].db_server) == 'mysql':
+ db['db-backend'] = 2
+ elif string.lower(self.supported_databases[name].db_server) == 'postgresql':
+ db['db-backend'] = 3
+ else: db['db-backend'] = None # this is big trouble
return db
def set_db_parameters(self, db_name = 'fpdb', db_ip = None, db_user = None,
db_pass = None, db_server = None, db_type = None):
db_node = self.get_db_node(db_name)
- if not db_node == None:
- if not db_ip == None: db_node.setAttribute("db_ip", db_ip)
- if not db_user == None: db_node.setAttribute("db_user", db_user)
- if not db_pass == None: db_node.setAttribute("db_pass", db_pass)
- if not db_server == None: db_node.setAttribute("db_server", db_server)
- if not db_type == None: db_node.setAttribute("db_type", db_type)
+ if db_node != None:
+ if db_ip != None: db_node.setAttribute("db_ip", db_ip)
+ if db_user != None: db_node.setAttribute("db_user", db_user)
+ if db_pass != None: db_node.setAttribute("db_pass", db_pass)
+ if db_server != None: db_node.setAttribute("db_server", db_server)
+ if db_type != None: db_node.setAttribute("db_type", db_type)
if self.supported_databases.has_key(db_name):
- if not db_ip == None: self.supported_databases[db_name].dp_ip = db_ip
- if not db_user == None: self.supported_databases[db_name].dp_user = db_user
- if not db_pass == None: self.supported_databases[db_name].dp_pass = db_pass
- if not db_server == None: self.supported_databases[db_name].dp_server = db_server
- if not db_type == None: self.supported_databases[db_name].dp_type = db_type
+ if db_ip != None: self.supported_databases[db_name].dp_ip = db_ip
+ if db_user != None: self.supported_databases[db_name].dp_user = db_user
+ if db_pass != None: self.supported_databases[db_name].dp_pass = db_pass
+ if db_server != None: self.supported_databases[db_name].dp_server = db_server
+ if db_type != None: self.supported_databases[db_name].dp_type = db_type
return
def get_tv_parameters(self):
tv = {}
- try:
- tv['combinedStealFold'] = self.tv.combinedStealFold
- tv['combined2B3B'] = self.tv.combined2B3B
- tv['combinedPostflop'] = self.tv.combinedPostflop
- except: # Default tv parameters
- tv['combinedStealFold'] = True
- tv['combined2B3B'] = True
- tv['combinedPostflop'] = True
+ try: tv['combinedStealFold'] = self.tv.combinedStealFold
+ except: tv['combinedStealFold'] = True
+
+ try: tv['combined2B3B'] = self.tv.combined2B3B
+ except: tv['combined2B3B'] = True
+
+ try: tv['combinedPostflop'] = self.tv.combinedPostflop
+ except: tv['combinedPostflop'] = True
return tv
def get_import_parameters(self):
imp = {}
- try:
- imp['callFpdbHud'] = self.imp.callFpdbHud
- imp['interval'] = self.imp.interval
- imp['hhArchiveBase'] = self.imp.hhArchiveBase
- except: # Default params
- imp['callFpdbHud'] = True
- imp['interval'] = 10
- imp['hhArchiveBase'] = "~/.fpdb/HandHistories/"
+ try: imp['callFpdbHud'] = self.imp.callFpdbHud
+ except: imp['callFpdbHud'] = True
+
+ try: imp['interval'] = self.imp.interval
+ except: imp['interval'] = 10
+
+ try: imp['hhArchiveBase'] = self.imp.hhArchiveBase
+ except: imp['hhArchiveBase'] = "~/.fpdb/HandHistories/"
+
+ try: imp['saveActions'] = self.imp.saveActions
+ except: imp['saveActions'] = True
+
+ try: imp['fastStoreHudCache'] = self.imp.fastStoreHudCache
+ except: imp['fastStoreHudCache'] = True
return imp
def get_default_paths(self, site = "PokerStars"):
@@ -465,6 +533,9 @@ class Config:
paths['hud-defaultPath'] = "default"
paths['bulkImport-defaultPath'] = "default"
return paths
+
+ def get_frames(self, site = "PokerStars"):
+ return self.supported_sites[site].use_frames == True
def get_default_colors(self, site = "PokerStars"):
colors = {}
@@ -505,14 +576,27 @@ class Config:
( 0, 280), (121, 280), ( 46, 30) )
return locations
- def get_supported_sites(self):
+ def get_aux_locations(self, aux = "mucked", max = "9"):
+
+ try:
+ locations = self.aux_windows[aux].layout[max].location
+ except:
+ locations = ( ( 0, 0), (684, 61), (689, 239), (692, 346),
+ (586, 393), (421, 440), (267, 440), ( 0, 361),
+ ( 0, 280), (121, 280), ( 46, 30) )
+ return locations
+
+ def get_supported_sites(self, all = False):
"""Returns the list of supported sites."""
- return self.supported_sites.keys()
+ the_sites = []
+ for site in self.supported_sites.keys():
+ params = self.get_site_parameters(site)
+ if all or params['enabled']:
+ the_sites.append(site)
+ return the_sites
def get_site_parameters(self, site):
"""Returns a dict of the site parameters for the specified site"""
- if not self.supported_sites.has_key(site):
- return None
parms = {}
parms["converter"] = self.supported_sites[site].converter
parms["decoder"] = self.supported_sites[site].decoder
@@ -524,10 +608,10 @@ class Config:
parms["table_finder"] = self.supported_sites[site].table_finder
parms["HH_path"] = self.supported_sites[site].HH_path
parms["site_name"] = self.supported_sites[site].site_name
- parms["enabled"] = self.supported_sites[site].enabled
parms["aux_window"] = self.supported_sites[site].aux_window
parms["font"] = self.supported_sites[site].font
parms["font_size"] = self.supported_sites[site].font_size
+ parms["enabled"] = self.supported_sites[site].enabled
return parms
def set_site_parameters(self, site_name, converter = None, decoder = None,
@@ -538,31 +622,19 @@ class Config:
font = None, font_size = None):
"""Sets the specified site parameters for the specified site."""
site_node = self.get_site_node(site_name)
- if not db_node == None:
- if not converter == None: site_node.setAttribute("converter", converter)
- if not decoder == None: site_node.setAttribute("decoder", decoder)
- if not hudbgcolor == None: site_node.setAttribute("hudbgcolor", hudbgcolor)
- if not hudfgcolor == None: site_node.setAttribute("hudfgcolor", hudfgcolor)
- if not hudopacity == None: site_node.setAttribute("hudopacity", hudopacity)
- if not screen_name == None: site_node.setAttribute("screen_name", screen_name)
- if not site_path == None: site_node.setAttribute("site_path", site_path)
- if not table_finder == None: site_node.setAttribute("table_finder", table_finder)
- if not HH_path == None: site_node.setAttribute("HH_path", HH_path)
- if not enabled == None: site_node.setAttribute("enabled", enabled)
- if not font == None: site_node.setAttribute("font", font)
- if not font_size == None: site_node.setAttribute("font_size", font_size)
-
-# if self.supported_databases.has_key(db_name):
-# if not converter == None: self.supported_sites[site].converter = converter
-# if not decoder == None: self.supported_sites[site].decoder = decoder
-# if not hudbgcolor == None: self.supported_sites[site].hudbgcolor = hudbgcolor
-# if not hudfgcolor == None: self.supported_sites[site].hudfgcolor = hudfgcolor
-# if not hudopacity == None: self.supported_sites[site].hudopacity = hudopacity
-# if not screen_name == None: self.supported_sites[site].screen_name = screen_name
-# if not site_path == None: self.supported_sites[site].site_path = site_path
-# if not table_finder == None: self.supported_sites[site].table_finder = table_finder
-# if not HH_path == None: self.supported_sites[site].HH_path = HH_path
-# if not enabled == None: self.supported_sites[site].enabled = enabled
+ if db_node != None:
+ if converter != None: site_node.setAttribute("converter", converter)
+ if decoder != None: site_node.setAttribute("decoder", decoder)
+ if hudbgcolor != None: site_node.setAttribute("hudbgcolor", hudbgcolor)
+ if hudfgcolor != None: site_node.setAttribute("hudfgcolor", hudfgcolor)
+ if hudopacity != None: site_node.setAttribute("hudopacity", hudopacity)
+ if screen_name != None: site_node.setAttribute("screen_name", screen_name)
+ if site_path != None: site_node.setAttribute("site_path", site_path)
+ if table_finder != None: site_node.setAttribute("table_finder", table_finder)
+ if HH_path != None: site_node.setAttribute("HH_path", HH_path)
+ if enabled != None: site_node.setAttribute("enabled", enabled)
+ if font != None: site_node.setAttribute("font", font)
+ if font_size != None: site_node.setAttribute("font_size", font_size)
return
def get_aux_windows(self):
@@ -605,7 +677,7 @@ class Config:
def execution_path(self, filename):
"""Join the fpdb path to filename."""
- return os.path.join(os.path.dirname(inspect.getfile(sys._getframe(1))), filename)
+ return os.path.join(os.path.dirname(inspect.getfile(sys._getframe(0))), filename)
if __name__== "__main__":
c = Config()
@@ -656,7 +728,12 @@ if __name__== "__main__":
print "locs = ", c.get_locations("PokerStars", 8)
for mw in c.get_aux_windows():
print c.get_aux_parameters(mw)
-
+
+ print "mucked locations =", c.get_aux_locations('mucked', 9)
+# c.edit_aux_layout('mucked', 9, locations = [(487, 113), (555, 469), (572, 276), (522, 345),
+# (333, 354), (217, 341), (150, 273), (150, 169), (230, 115)])
+# print "mucked locations =", c.get_aux_locations('mucked', 9)
+
for site in c.supported_sites.keys():
print "site = ", site,
print c.get_site_parameters(site)
@@ -665,4 +742,4 @@ if __name__== "__main__":
for game in c.get_supported_games():
print c.get_game_parameters(game)
- print "start up path = ", c.execution_path("")
\ No newline at end of file
+ print "start up path = ", c.execution_path("")
diff --git a/pyfpdb/Database.py b/pyfpdb/Database.py
index f575266a..a0b08992 100644
--- a/pyfpdb/Database.py
+++ b/pyfpdb/Database.py
@@ -116,31 +116,53 @@ class Database:
row = c.fetchone()
return row[0]
-# def get_cards(self, hand):
-# this version is for the PTrackSv2 db
-# c = self.connection.cursor()
-# c.execute(self.sql.query['get_cards'], hand)
-# colnames = [desc[0] for desc in c.description]
-# cards = {}
-# for row in c.fetchall():
-# s_dict = {}
-# for name, val in zip(colnames, row):
-# s_dict[name] = val
-# cards[s_dict['seat_number']] = s_dict
-# return (cards)
-
def get_cards(self, hand):
-# this version is for the fpdb db
+ """Get and return the cards for each player in the hand."""
+ cards = {} # dict of cards, the key is the seat number example: {1: 'AcQd9hTs5d'}
c = self.connection.cursor()
c.execute(self.sql.query['get_cards'], hand)
colnames = [desc[0] for desc in c.description]
- cards = {}
for row in c.fetchall():
s_dict = {}
for name, val in zip(colnames, row):
s_dict[name] = val
- cards[s_dict['seat_number']] = s_dict
- return (cards)
+ cards[s_dict['seat_number']] = (self.convert_cards(s_dict))
+ return cards
+
+ def get_common_cards(self, hand):
+ """Get and return the community cards for the specified hand."""
+ cards = {}
+ c = self.connection.cursor()
+ c.execute(self.sql.query['get_common_cards'], hand)
+ colnames = [desc[0] for desc in c.description]
+ for row in c.fetchall():
+ s_dict = {}
+ for name, val in zip(colnames, row):
+ s_dict[name] = val
+ cards['common'] = (self.convert_cards(s_dict))
+ return cards
+
+ def convert_cards(self, d):
+ ranks = ('', '', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
+ cards = ""
+ for i in xrange(1, 8):
+# key = 'card' + str(i) + 'Value'
+# if not d.has_key(key): continue
+# if d[key] == None:
+# break
+# elif d[key] == 0:
+# cards += "xx"
+# else:
+# cards += ranks[d['card' + str(i) + 'Value']] + d['card' +str(i) + 'Suit']
+ cv = "card%dValue" % i
+ if cv not in d or d[cv] == None:
+ break
+ elif d[cv] == 0:
+ cards += "xx"
+ else:
+ cs = "card%dSuit" % i
+ cards = "%s%s%s" % (cards, ranks[d[cv]], d[cs])
+ return cards
def get_action_from_hand(self, hand_no):
action = [ [], [], [], [], [] ]
@@ -165,19 +187,11 @@ class Database:
c = self.connection.cursor()
if aggregate:
- query = 'get_stats_from_hand'
- subs = (hand, hand)
- else:
query = 'get_stats_from_hand_aggregated'
subs = (hand, hand, hand)
-
-# get the players in the hand and their seats
- c.execute(self.sql.query['get_players_from_hand'], (hand, ))
- names = {}
- seats = {}
- for row in c.fetchall():
- names[row[0]] = row[2]
- seats[row[0]] = row[1]
+ else:
+ query = 'get_stats_from_hand'
+ subs = (hand, hand)
# now get the stats
c.execute(self.sql.query[query], subs)
@@ -187,9 +201,6 @@ class Database:
t_dict = {}
for name, val in zip(colnames, row):
t_dict[name.lower()] = val
-# print t_dict
- t_dict['screen_name'] = names[t_dict['player_id']]
- t_dict['seat'] = seats[t_dict['player_id']]
stat_dict[t_dict['player_id']] = t_dict
return stat_dict
@@ -225,6 +236,7 @@ if __name__=="__main__":
for p in stat_dict.keys():
print p, " ", stat_dict[p]
+ print "cards =", db_connection.get_cards(73525)
db_connection.close_connection
print "press enter to continue"
diff --git a/pyfpdb/DerivedStats.py b/pyfpdb/DerivedStats.py
new file mode 100644
index 00000000..b526632a
--- /dev/null
+++ b/pyfpdb/DerivedStats.py
@@ -0,0 +1,91 @@
+#!/usr/bin/python
+
+#Copyright 2008 Carl Gherardi
+#This program is free software: you can redistribute it and/or modify
+#it under the terms of the GNU Affero General Public License as published by
+#the Free Software Foundation, version 3 of the License.
+#
+#This program is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+#GNU General Public License for more details.
+#
+#You should have received a copy of the GNU Affero General Public License
+#along with this program. If not, see .
+#In the "official" distribution you can find the license in
+#agpl-3.0.txt in the docs folder of the package.
+
+class DerivedStats():
+ def __init__(self, hand):
+ self.hand = hand
+
+ self.activeSeats = 0
+ self.position = 0
+ self.tourneyTypeId = 0
+
+ self.HDs = 0
+ self.street0VPI = 0
+ self.street0Aggr = 0
+ self.street0_3B4BChance = 0
+ self.street0_3B4BDone = 0
+
+ self.street1Seen = 0
+ self.street2Seen = 0
+ self.street3Seen = 0
+ self.street4Seen = 0
+ self.sawShowdown = 0
+
+ self.street1Aggr = 0
+ self.street2Aggr = 0
+ self.street3Aggr = 0
+ self.street4Aggr = 0
+
+ self.otherRaisedStreet1 = 0
+ self.otherRaisedStreet2 = 0
+ self.otherRaisedStreet3 = 0
+ self.otherRaisedStreet4 = 0
+ self.foldToOtherRaisedStreet1 = 0
+ self.foldToOtherRaisedStreet2 = 0
+ self.foldToOtherRaisedStreet3 = 0
+ self.foldToOtherRaisedStreet4 = 0
+ self.wonWhenSeenStreet1 = 0
+ self.wonAtSD = 0
+
+ self.stealAttemptChance = 0
+ self.stealAttempted = 0
+ self.foldBbToStealChance = 0
+ self.foldedBbToSteal = 0
+ self.foldSbToStealChance = 0
+ self.foldedSbToSteal = 0
+
+ self.street1CBChance = 0
+ self.street1CBDone = 0
+ self.street2CBChance = 0
+ self.street2CBDone = 0
+ self.street3CBChance = 0
+ self.street3CBDone = 0
+ self.street4CBChance = 0
+ self.street4CBDone = 0
+
+ self.foldToStreet1CBChance = 0
+ self.foldToStreet1CBDone = 0
+ self.foldToStreet2CBChance = 0
+ self.foldToStreet2CBDone = 0
+ self.foldToStreet3CBChance = 0
+ self.foldToStreet3CBDone = 0
+ self.foldToStreet4CBChance = 0
+ self.foldToStreet4CBDone = 0
+
+ self.totalProfit = 0
+
+ self.street1CheckCallRaiseChance = 0
+ self.street1CheckCallRaiseDone = 0
+ self.street2CheckCallRaiseChance = 0
+ self.street2CheckCallRaiseDone = 0
+ self.street3CheckCallRaiseChance = 0
+ self.street3CheckCallRaiseDone = 0
+ self.street4CheckCallRaiseChance = 0
+ self.street4CheckCallRaiseDone = 0
+
+ def getStats():
+ pass
diff --git a/pyfpdb/EverleafToFpdb.py b/pyfpdb/EverleafToFpdb.py
index 41052f66..29808295 100755
--- a/pyfpdb/EverleafToFpdb.py
+++ b/pyfpdb/EverleafToFpdb.py
@@ -1,4 +1,6 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
# Copyright 2008, Carl Gherardi
#
# This program is free software; you can redistribute it and/or modify
@@ -10,165 +12,246 @@
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
-#
+#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
########################################################################
import sys
-import Configuration
+import logging
from HandHistoryConverter import *
-# Everleaf HH format
-
-# Everleaf Gaming Game #55208539
-# ***** Hand history for game #55208539 *****
-# Blinds $0.50/$1 NL Hold'em - 2008/09/01 - 13:35:01
-# Table Speed Kuala
-# Seat 1 is the button
-# Total number of players: 9
-# Seat 1: BadBeatBox ( $ 98.97 USD )
-# Seat 3: EricBlade ( $ 73.96 USD )
-# Seat 4: randy888 ( $ 196.50 USD )
-# Seat 5: BaronSengir ( $ 182.80 USD )
-# Seat 6: dogge ( $ 186.06 USD )
-# Seat 7: wings ( $ 50 USD )
-# Seat 8: schoffeltje ( $ 282.05 USD )
-# Seat 9: harrydebeng ( $ 109.45 USD )
-# Seat 10: smaragdar ( $ 96.50 USD )
-# EricBlade: posts small blind [$ 0.50 USD]
-# randy888: posts big blind [$ 1 USD]
-# wings: posts big blind [$ 1 USD]
-# ** Dealing down cards **
-# Dealt to EricBlade [ qc, 3c ]
-# BaronSengir folds
-# dogge folds
-# wings raises [$ 2.50 USD]
-# schoffeltje folds
-# harrydebeng calls [$ 3.50 USD]
-# smaragdar raises [$ 15.50 USD]
-# BadBeatBox folds
-# EricBlade folds
-# randy888 folds
-# wings calls [$ 12 USD]
-# harrydebeng folds
-# ** Dealing Flop ** [ qs, 3d, 8h ]
-# wings: bets [$ 34.50 USD]
-# smaragdar calls [$ 34.50 USD]
-# ** Dealing Turn ** [ 2d ]
-# ** Dealing River ** [ 6c ]
-# dogge shows [ 9h, 9c ]a pair of nines
-# spicybum shows [ 5d, 6d ]a straight, eight high
-# harrydebeng does not show cards
-# smaragdar wins $ 102 USD from main pot with a pair of aces [ ad, ah, qs, 8h, 6c ]
+# Class for converting Everleaf HH format.
class Everleaf(HandHistoryConverter):
- def __init__(self, config, file):
- print "Initialising Everleaf converter class"
- HandHistoryConverter.__init__(self, config, file, sitename="Everleaf") # Call super class init.
- self.sitename = "Everleaf"
- self.setFileType("text", "cp1252")
- self.rexx.setGameInfoRegex('.*Blinds \$?(?P[.0-9]+)/\$?(?P[.0-9]+)')
- self.rexx.setSplitHandRegex('\n\n+')
- self.rexx.setHandInfoRegex('.*#(?P[0-9]+)\n.*\nBlinds \$?(?P[.0-9]+)/\$?(?P[.0-9]+) (?P.*) - (?P\d\d\d\d/\d\d/\d\d - \d\d:\d\d:\d\d)\nTable (?P[ a-zA-Z]+)\nSeat (?P[0-9]+)')
- self.rexx.setPlayerInfoRegex('Seat (?P[0-9]+): (?P.*) \(\s+(\$ (?P[.0-9]+) USD|€ (?P[.0-9]+) EUR|new player|All-in) \)')
- self.rexx.setPostSbRegex('.*\n(?P.*): posts small blind \[\$? (?P[.0-9]+)')
- self.rexx.setPostBbRegex('.*\n(?P.*): posts big blind \[\$? (?P[.0-9]+)')
- self.rexx.setPostBothRegex('.*\n(?P.*): posts small \& big blinds \[\$? (?P[.0-9]+)')
- self.rexx.setHeroCardsRegex('.*\nDealt\sto\s(?P.*)\s\[ (?P.*) \]')
- self.rexx.setActionStepRegex('.*\n(?P.*)(?P: bets| checks| raises| calls| folds)(\s\[\$ (?P[.\d]+) (USD|EUR)\])?')
- self.rexx.setShowdownActionRegex('.*\n(?P.*) shows \[ (?P.*) \]')
- self.rexx.setCollectPotRegex('.*\n(?P.*) wins \$ (?P[.\d]+) (USD|EUR)(.*?\[ (?P.*?) \])?')
- #self.rexx.setCollectPotRegex('.*\n(?P.*) wins \$ (?P[.\d]+) USD(.*\[ (?P) \S\S, \S\S, \S\S, \S\S, \S\S \])?')
- self.rexx.sits_out_re = re.compile('(?P.*) sits out')
- self.rexx.compileRegexes()
+
+ # Static regexes
+ re_SplitHands = re.compile(r"(\n\n\n+)")
+ re_GameInfo = re.compile(ur"^(Blinds )?(?P\$| €|)(?P[.0-9]+)/(?:\$| €)?(?P[.0-9]+) (?PNL|PL|) ?(?P(Hold\'em|Omaha|7 Card Stud))", re.MULTILINE)
+ #re.compile(ur"^(Blinds )?(?P\$| €|)(?P[.0-9]+)/(?:\$| €)?(?P[.0-9]+) (?PNL|PL|) (?P(Hold\'em|Omaha|7 Card Stud))", re.MULTILINE)
+ re_HandInfo = re.compile(ur".*#(?P[0-9]+)\n.*\n(Blinds )?(?:\$| €|)(?P[.0-9]+)/(?:\$| €|)(?P[.0-9]+) (?P.*) - (?P\d\d\d\d/\d\d/\d\d - \d\d:\d\d:\d\d)\nTable (?P.+$)", re.MULTILINE)
+ re_Button = re.compile(ur"^Seat (?P\d+) is the button", re.MULTILINE)
+ re_PlayerInfo = re.compile(ur"^Seat (?P[0-9]+): (?P.*) \(\s+((?:\$| €|) (?P[.0-9]+) (USD|EUR|)|new player|All-in) \)", re.MULTILINE)
+ re_Board = re.compile(ur"\[ (?P.+) \]")
+
+
+ def __init__(self, in_path = '-', out_path = '-', follow = False, autostart=True, debugging=False):
+ """\
+in_path (default '-' = sys.stdin)
+out_path (default '-' = sys.stdout)
+follow : whether to tail -f the input
+autostart: whether to run the thread (or you can call start() yourself)
+debugging: if False, pass on partially supported game types. If true, have a go and error..."""
+ print "DEBUG: XXXXXXXXXXXXXXX"
+ HandHistoryConverter.__init__(self, in_path, out_path, sitename="Everleaf", follow=follow)
+ logging.info("Initialising Everleaf converter class")
+ self.filetype = "text"
+ self.codepage = "cp1252"
+ self.debugging = debugging
+ if autostart:
+ self.start()
+ # otherwise you need to call start yourself.
+
+ def compilePlayerRegexs(self, hand):
+ players = set([player[1] for player in hand.players])
+ if not players <= self.compiledPlayers: # x <= y means 'x is subset of y'
+ # we need to recompile the player regexs.
+ self.compiledPlayers = players
+ player_re = "(?P" + "|".join(map(re.escape, players)) + ")"
+ logging.debug("player_re: "+ player_re)
+ self.re_PostSB = re.compile(ur"^%s: posts small blind \[(?:\$| €|) (?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_PostBB = re.compile(ur"^%s: posts big blind \[(?:\$| €|) (?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_PostBoth = re.compile(ur"^%s: posts both blinds \[(?:\$| €|) (?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_Antes = re.compile(ur"^%s: posts ante \[(?:\$| €|) (?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_BringIn = re.compile(ur"^%s posts bring-in (?:\$| €|)(?P[.0-9]+)\." % player_re, re.MULTILINE)
+ self.re_HeroCards = re.compile(ur"^Dealt to %s \[ (?P.*) \]" % player_re, re.MULTILINE)
+ self.re_Action = re.compile(ur"^%s(?P: bets| checks| raises| calls| folds)(\s\[(?:\$| €|) (?P[.\d]+) (USD|EUR|)\])?" % player_re, re.MULTILINE)
+ #self.re_Action = re.compile(ur"^%s(?P: bets| checks| raises| calls| folds| complete to)(\s\[?(?:\$| €|) ?(?P\d+\.?\d*)\.?\s?(USD|EUR|)\]?)?" % player_re, re.MULTILINE)
+ self.re_ShowdownAction = re.compile(ur"^%s shows \[ (?P.*) \]" % player_re, re.MULTILINE)
+ self.re_CollectPot = re.compile(ur"^%s wins (?:\$| €|) (?P[.\d]+) (USD|EUR|chips)(.*?\[ (?P.*?) \])?" % player_re, re.MULTILINE)
+ self.re_SitsOut = re.compile(ur"^%s sits out" % player_re, re.MULTILINE)
def readSupportedGames(self):
- pass
+ return [["ring", "hold", "nl"],
+ ["ring", "hold", "pl"],
+ ["ring", "hold", "fl"],
+ ["ring", "studhi", "fl"],
+ ["ring", "omahahi", "pl"]
+ ]
- def determineGameType(self):
- # Cheating with this regex, only support nlhe at the moment
- gametype = ["ring", "hold", "nl"]
-
- m = self.rexx.game_info_re.search(self.obs)
- gametype = gametype + [m.group('SB')]
- gametype = gametype + [m.group('BB')]
+ def determineGameType(self, handText):
+ """return dict with keys/values:
+ 'type' in ('ring', 'tour')
+ 'limitType' in ('nl', 'cn', 'pl', 'cp', 'fl')
+ 'base' in ('hold', 'stud', 'draw')
+ 'category' in ('holdem', 'omahahi', omahahilo', 'razz', 'studhi', 'studhilo', 'fivedraw', '27_1draw', '27_3draw', 'badugi')
+ 'hilo' in ('h','l','s')
+ 'smallBlind' int?
+ 'bigBlind' int?
+ 'smallBet'
+ 'bigBet'
+ 'currency' in ('USD', 'EUR', 'T$', )
+or None if we fail to get the info """
+ #(TODO: which parts are optional/required?)
+
+ # Blinds $0.50/$1 PL Omaha - 2008/12/07 - 21:59:48
+ # Blinds $0.05/$0.10 NL Hold'em - 2009/02/21 - 11:21:57
+ # $0.25/$0.50 7 Card Stud - 2008/12/05 - 21:43:59
- return gametype
+ # Tourney:
+ # Everleaf Gaming Game #75065769
+ # ***** Hand history for game #75065769 *****
+ # Blinds 10/20 NL Hold'em - 2009/02/25 - 17:30:32
+ # Table 2
+ info = {'type':'ring'}
+
+ m = self.re_GameInfo.search(handText)
+ if not m:
+ return None
+
+ mg = m.groupdict()
+
+ # translations from captured groups to our info strings
+ limits = { 'NL':'nl', 'PL':'pl', '':'fl' }
+ games = { # base, category
+ "Hold'em" : ('hold','holdem'),
+ 'Omaha' : ('hold','omahahi'),
+ 'Razz' : ('stud','razz'),
+ '7 Card Stud' : ('stud','studhi')
+ }
+ currencies = { u' €':'EUR', '$':'USD', '':'T$' }
+ if 'LIMIT' in mg:
+ info['limitType'] = limits[mg['LIMIT']]
+ if 'GAME' in mg:
+ (info['base'], info['category']) = games[mg['GAME']]
+ if 'SB' in mg:
+ info['sb'] = mg['SB']
+ if 'BB' in mg:
+ info['bb'] = mg['BB']
+ if 'CURRENCY' in mg:
+ info['currency'] = currencies[mg['CURRENCY']]
+ if info['currency'] == 'T$':
+ info['type'] = 'tour'
+ # NB: SB, BB must be interpreted as blinds or bets depending on limit type.
+
+ return info
+
def readHandInfo(self, hand):
- m = self.rexx.hand_info_re.search(hand.string)
- hand.handid = m.group('HID')
+ m = self.re_HandInfo.search(hand.handText)
+ if(m == None):
+ logging.info("Didn't match re_HandInfo")
+ logging.info(hand.handText)
+ return None
+ logging.debug("HID %s, Table %s" % (m.group('HID'), m.group('TABLE')))
+ hand.handid = m.group('HID')
hand.tablename = m.group('TABLE')
-# These work, but the info is already in the Hand class - should be used for tourneys though.
-# m.group('SB')
-# m.group('BB')
-# m.group('GAMETYPE')
+ hand.maxseats = 6 # assume 6-max unless we have proof it's a larger/smaller game, since everleaf doesn't give seat max info
-# Believe Everleaf time is GMT/UTC, no transation necessary
-# Stars format (Nov 10 2008): 2008/11/07 12:38:49 CET [2008/11/07 7:38:49 ET]
-# or : 2008/11/07 12:38:49 ET
-# Not getting it in my HH files yet, so using
-# 2008/11/10 3:58:52 ET
-#TODO: Do conversion from GMT to ET
-#TODO: Need some date functions to convert to different timezones (Date::Manip for perl rocked for this)
+ # Believe Everleaf time is GMT/UTC, no transation necessary
+ # Stars format (Nov 10 2008): 2008/11/07 12:38:49 CET [2008/11/07 7:38:49 ET]
+ # or : 2008/11/07 12:38:49 ET
+ # Not getting it in my HH files yet, so using
+ # 2008/11/10 3:58:52 ET
+ #TODO: Do conversion from GMT to ET
+ #TODO: Need some date functions to convert to different timezones (Date::Manip for perl rocked for this)
hand.starttime = time.strptime(m.group('DATETIME'), "%Y/%m/%d - %H:%M:%S")
- hand.buttonpos = int(m.group('BUTTON'))
+ return
def readPlayerStacks(self, hand):
- m = self.rexx.player_info_re.finditer(hand.string)
- players = []
+ m = self.re_PlayerInfo.finditer(hand.handText)
for a in m:
- hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
-
+ seatnum = int(a.group('SEAT'))
+ hand.addPlayer(seatnum, a.group('PNAME'), a.group('CASH'))
+ if seatnum > 6:
+ hand.maxseats = 10 # everleaf currently does 2/6/10 games, so if seats > 6 are in use, it must be 10-max.
+ # TODO: implement lookup list by table-name to determine maxes, then fall back to 6 default/10 here, if there's no entry in the list?
+
+
def markStreets(self, hand):
# PREFLOP = ** Dealing down cards **
# This re fails if, say, river is missing; then we don't get the ** that starts the river.
- #m = re.search('(\*\* Dealing down cards \*\*\n)(?P.*?\n\*\*)?( Dealing Flop \*\* \[ (?P\S\S), (?P\S\S), (?P\S\S) \])?(?P.*?\*\*)?( Dealing Turn \*\* \[ (?P\S\S) \])?(?P.*?\*\*)?( Dealing River \*\* \[ (?P\S\S) \])?(?P.*)', hand.string,re.DOTALL)
-
- m = re.search(r"\*\* Dealing down cards \*\*(?P.+(?=\*\* Dealing Flop \*\*)|.+)"
+ #m = re.search('(\*\* Dealing down cards \*\*\n)(?P.*?\n\*\*)?( Dealing Flop \*\* \[ (?P\S\S), (?P\S\S), (?P\S\S) \])?(?P.*?\*\*)?( Dealing Turn \*\* \[ (?P\S\S) \])?(?P.*?\*\*)?( Dealing River \*\* \[ (?P\S\S) \])?(?P.*)', hand.handText,re.DOTALL)
+ if hand.gametype['base'] == 'hold':
+ m = re.search(r"\*\* Dealing down cards \*\*(?P.+(?=\*\* Dealing Flop \*\*)|.+)"
r"(\*\* Dealing Flop \*\*(?P \[ \S\S, \S\S, \S\S \].+(?=\*\* Dealing Turn \*\*)|.+))?"
r"(\*\* Dealing Turn \*\*(?P \[ \S\S \].+(?=\*\* Dealing River \*\*)|.+))?"
- r"(\*\* Dealing River \*\*(?P \[ \S\S \].+))?", hand.string,re.DOTALL)
-
+ r"(\*\* Dealing River \*\*(?P \[ \S\S \].+))?", hand.handText,re.DOTALL)
+ elif hand.gametype['base'] == 'stud':
+ m = re.search(r"(?P.+(?=\*\* Dealing down cards \*\*)|.+)"
+ r"(\*\* Dealing down cards \*\*(?P.+(?=\*\*\*\* dealing 4th street \*\*\*\*)|.+))?"
+ r"(\*\*\*\* dealing 4th street \*\*\*\*(?P.+(?=\*\*\*\* dealing 5th street \*\*\*\*)|.+))?"
+ r"(\*\*\*\* dealing 5th street \*\*\*\*(?P.+(?=\*\*\*\* dealing 6th street \*\*\*\*)|.+))?"
+ r"(\*\*\*\* dealing 6th street \*\*\*\*(?P.+(?=\*\*\*\* dealing river \*\*\*\*)|.+))?"
+ r"(\*\*\*\* dealing river \*\*\*\*(?P.+))?", hand.handText,re.DOTALL)
hand.addStreets(m)
-
def readCommunityCards(self, hand, street): # street has been matched by markStreets, so exists in this hand
- self.rexx.board_re = re.compile(r"\[ (?P.+) \]")
- print hand.streets.group(street)
- if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
- m = self.rexx.board_re.search(hand.streets.group(street))
- hand.setCommunityCards(street, m.group('CARDS').split(', '))
+ # If this has been called, street is a street which gets dealt community cards by type hand
+ # but it might be worth checking somehow.
+# if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
+ logging.debug("readCommunityCards (%s)" % street)
+ m = self.re_Board.search(hand.streets[street])
+ cards = m.group('CARDS')
+ cards = [card.strip() for card in cards.split(',')]
+ hand.setCommunityCards(street=street, cards=cards)
+
+ def readAntes(self, hand):
+ logging.debug("reading antes")
+ m = self.re_Antes.finditer(hand.handText)
+ for player in m:
+ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
+ hand.addAnte(player.group('PNAME'), player.group('ANTE'))
+
+ def readBringIn(self, hand):
+ m = self.re_BringIn.search(hand.handText,re.DOTALL)
+ if m:
+ logging.debug("Player bringing in: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
+ hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
+ else:
+ logging.warning("No bringin found.")
def readBlinds(self, hand):
- try:
- m = self.rexx.small_blind_re.search(hand.string)
+ m = self.re_PostSB.search(hand.handText)
+ if m is not None:
hand.addBlind(m.group('PNAME'), 'small blind', m.group('SB'))
- except: # no small blind
+ else:
+ logging.debug("No small blind")
hand.addBlind(None, None, None)
- for a in self.rexx.big_blind_re.finditer(hand.string):
+ for a in self.re_PostBB.finditer(hand.handText):
hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
- for a in self.rexx.both_blinds_re.finditer(hand.string):
- hand.addBlind(a.group('PNAME'), 'small & big blinds', a.group('SBBB'))
+ for a in self.re_PostBoth.finditer(hand.handText):
+ hand.addBlind(a.group('PNAME'), 'both', a.group('SBBB'))
+
+ def readButton(self, hand):
+ hand.buttonpos = int(self.re_Button.search(hand.handText).group('BUTTON'))
def readHeroCards(self, hand):
- m = self.rexx.hero_cards_re.search(hand.string)
- if(m == None):
- #Not involved in hand
- hand.involved = False
- else:
+ m = self.re_HeroCards.search(hand.handText)
+ if m:
hand.hero = m.group('PNAME')
- # "2c, qh" -> set(["2c","qc"])
+ # "2c, qh" -> ["2c","qc"]
# Also works with Omaha hands.
cards = m.group('CARDS')
- cards = set(cards.split(', '))
+ cards = [card.strip() for card in cards.split(',')]
hand.addHoleCards(cards, m.group('PNAME'))
+ else:
+ #Not involved in hand
+ hand.involved = False
+
+ def readStudPlayerCards(self, hand, street):
+ # lol. see Plymouth.txt
+ logging.warning("Everleaf readStudPlayerCards is only a stub.")
+ #~ if street in ('THIRD', 'FOURTH', 'FIFTH', 'SIXTH'):
+ #~ hand.addPlayerCards(player = player.group('PNAME'), street = street, closed = [], open = [])
+
def readAction(self, hand, street):
- m = self.rexx.action_re.finditer(hand.streets.group(street))
+ logging.debug("readAction (%s)" % street)
+ m = self.re_Action.finditer(hand.streets[street])
for action in m:
+ logging.debug("%s %s" % (action.group('ATYPE'), action.groupdict()))
if action.group('ATYPE') == ' raises':
hand.addCallandRaise( street, action.group('PNAME'), action.group('BET') )
elif action.group('ATYPE') == ' calls':
@@ -179,35 +262,54 @@ class Everleaf(HandHistoryConverter):
hand.addFold( street, action.group('PNAME'))
elif action.group('ATYPE') == ' checks':
hand.addCheck( street, action.group('PNAME'))
+ elif action.group('ATYPE') == ' complete to':
+ hand.addComplete( street, action.group('PNAME'), action.group('BET'))
else:
- print "DEBUG: unimplemented readAction: %s %s" %(action.group('PNAME'),action.group('ATYPE'),)
+ logging.debug("Unimplemented readAction: %s %s" %(action.group('PNAME'),action.group('ATYPE'),))
def readShowdownActions(self, hand):
- for shows in self.rexx.showdown_action_re.finditer(hand.string):
+ """Reads lines where holecards are reported in a showdown"""
+ logging.debug("readShowdownActions")
+ for shows in self.re_ShowdownAction.finditer(hand.handText):
cards = shows.group('CARDS')
- cards = set(cards.split(', '))
+ cards = cards.split(', ')
+ logging.debug("readShowdownActions %s %s" %(cards, shows.group('PNAME')))
hand.addShownCards(cards, shows.group('PNAME'))
+
def readCollectPot(self,hand):
- for m in self.rexx.collect_pot_re.finditer(hand.string):
+ for m in self.re_CollectPot.finditer(hand.handText):
hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT'))
def readShownCards(self,hand):
- for m in self.rexx.collect_pot_re.finditer(hand.string):
+ """Reads lines where hole & board cards are mixed to form a hand (summary lines)"""
+ for m in self.re_CollectPot.finditer(hand.handText):
if m.group('CARDS') is not None:
cards = m.group('CARDS')
- cards = set(cards.split(', '))
+ cards = cards.split(', ')
+ player = m.group('PNAME')
+ logging.debug("readShownCards %s cards=%s" % (player, cards))
hand.addShownCards(cards=None, player=m.group('PNAME'), holeandboard=cards)
if __name__ == "__main__":
- c = Configuration.Config()
- if len(sys.argv) == 1:
- testfile = "regression-test-files/everleaf/Speed_Kuala_full.txt"
- else:
- testfile = sys.argv[1]
- e = Everleaf(c, testfile)
- e.processFile()
- print str(e)
+ parser = OptionParser()
+ parser.add_option("-i", "--input", dest="ipath", help="parse input hand history", default="-")
+ parser.add_option("-o", "--output", dest="opath", help="output translation to", default="-")
+ parser.add_option("-f", "--follow", dest="follow", help="follow (tail -f) the input", action="store_true", default=False)
+ parser.add_option("-q", "--quiet",
+ action="store_const", const=logging.CRITICAL, dest="verbosity", default=logging.INFO)
+ parser.add_option("-v", "--verbose",
+ action="store_const", const=logging.INFO, dest="verbosity")
+ parser.add_option("--vv",
+ action="store_const", const=logging.DEBUG, dest="verbosity")
+
+ (options, args) = parser.parse_args()
+
+ LOG_FILENAME = './logging.out'
+ logging.basicConfig(filename=LOG_FILENAME,level=options.verbosity)
+
+ e = Everleaf(in_path = options.ipath, out_path = options.opath, follow = options.follow, autostart=True, debugging=True)
+
diff --git a/pyfpdb/Exceptions.py b/pyfpdb/Exceptions.py
new file mode 100644
index 00000000..fa76f3cd
--- /dev/null
+++ b/pyfpdb/Exceptions.py
@@ -0,0 +1 @@
+class FpdbParseError(Exception): pass
diff --git a/pyfpdb/FpdbSQLQueries.py b/pyfpdb/FpdbSQLQueries.py
index fe170c8c..24948986 100644
--- a/pyfpdb/FpdbSQLQueries.py
+++ b/pyfpdb/FpdbSQLQueries.py
@@ -599,37 +599,6 @@ class FpdbSQLQueries:
################################
- # Returns all cash game handIds and the money won(winnings is the final pot)
- # by the playerId for a single site.
- if(self.dbname == 'MySQL InnoDB') or (self.dbname == 'PostgreSQL'):
- self.query['getRingWinningsAllGamesPlayerIdSite'] = """SELECT handId, winnings FROM HandsPlayers
- INNER JOIN Players ON HandsPlayers.playerId = Players.id
- INNER JOIN Hands ON Hands.id = HandsPlayers.handId
- WHERE Players.name = %s AND Players.siteId = %s AND (tourneysPlayersId IS NULL)
- ORDER BY handStart"""
- elif(self.dbname == 'SQLite'):
- #Probably doesn't work.
- self.query['getRingWinningsAllGamesPlayerIdSite'] = """SELECT handId, winnings FROM HandsPlayers
- INNER JOIN Players ON HandsPlayers.playerId = Players.id
- INNER JOIN Hands ON Hands.id = HandsPlayers.handId
- WHERE Players.name = %s AND Players.siteId = %s AND (tourneysPlayersId IS NULL)
- ORDER BY handStart"""
-
- # Returns the profit for a given ring game handId, Total pot - money invested by playerId
- if(self.dbname == 'MySQL InnoDB') or (self.dbname == 'PostgreSQL'):
- self.query['getRingProfitFromHandId'] = """SELECT SUM(amount) FROM HandsActions
- INNER JOIN HandsPlayers ON HandsActions.handPlayerId = HandsPlayers.id
- INNER JOIN Players ON HandsPlayers.playerId = Players.id
- WHERE Players.name = %s AND HandsPlayers.handId = %s
- AND Players.siteId = %s AND (tourneysPlayersId IS NULL)"""
- elif(self.dbname == 'SQLite'):
- #Probably doesn't work.
- self.query['getRingProfitFromHandId'] = """SELECT SUM(amount) FROM HandsActions
- INNER JOIN HandsPlayers ON HandsActions.handPlayerId = HandsPlayers.id
- INNER JOIN Players ON HandsPlayers.playerId = Players.id
- WHERE Players.name = %s AND HandsPlayers.handId = %s
- AND Players.siteId = %s AND (tourneysPlayersId IS NULL)"""
-
if(self.dbname == 'MySQL InnoDB') or (self.dbname == 'PostgreSQL'):
self.query['getPlayerId'] = """SELECT id from Players where name = %s"""
elif(self.dbname == 'SQLite'):
@@ -1054,6 +1023,137 @@ class FpdbSQLQueries:
elif(self.dbname == 'SQLite'):
self.query['playerStatsByPosition'] = """ """
+ if(self.dbname == 'MySQL InnoDB'):
+ self.query['playerStatsByPositionAndHoleCards'] = """
+ SELECT
+ concat(upper(stats.limitType), ' '
+ ,concat(upper(substring(stats.category,1,1)),substring(stats.category,2) ), ' '
+ ,stats.name, ' $'
+ ,cast(trim(leading ' ' from
+ case when stats.bigBlind < 100 then format(stats.bigBlind/100.0,2)
+ else format(stats.bigBlind/100.0,0)
+ end ) as char)
+ ) AS Game
+ ,case when stats.PlPosition = -2 then 'BB'
+ when stats.PlPosition = -1 then 'SB'
+ when stats.PlPosition = 0 then 'Btn'
+ when stats.PlPosition = 1 then 'CO'
+ when stats.PlPosition = 2 then 'MP'
+ when stats.PlPosition = 5 then 'EP'
+ else '??'
+ end AS PlPosition
+ /*,stats.n*/,hprof2.n
+ /*,stats.vpip*/,0
+ /*,stats.pfr*/,0
+ /*,stats.saw_f*/,0
+ /*,stats.sawsd*/,0
+ /*,stats.wtsdwsf*/,0
+ /*,stats.wmsd*/,0
+ /*,stats.FlAFq*/,0
+ /*,stats.TuAFq*/,0
+ /*,stats.RvAFq*/,0
+ /*,stats.PoFAFq*/,0
+ /* if you have handsactions data the next 3 fields should give same answer as
+ following 3 commented out fields */
+ /*,stats.Net
+ ,stats.BBper100
+ ,stats.Profitperhand*/
+ ,format(hprof2.sum_profit/100.0,2) AS Net
+ /*,format((hprof2.sum_profit/(stats.bigBlind+0.0)) / (stats.n/100.0),2)*/,0
+ AS BBlPer100
+ ,hprof2.profitperhand AS Profitperhand
+ ,format(hprof2.variance,2) AS Variance
+ FROM
+ (select /* stats from hudcache */
+ gt.base
+ ,gt.category
+ ,upper(gt.limitType) as limitType
+ ,s.name
+ ,gt.bigBlind
+ ,hc.gametypeId
+ ,case when hc.position = 'B' then -2
+ when hc.position = 'S' then -1
+ when hc.position = 'D' then 0
+ when hc.position = 'C' then 1
+ when hc.position = 'M' then 2
+ when hc.position = 'E' then 5
+ else 9
+ end as PlPosition
+ ,sum(HDs) AS n
+ ,format(100.0*sum(street0VPI)/sum(HDs),1) AS vpip
+ ,format(100.0*sum(street0Aggr)/sum(HDs),1) AS pfr
+ ,format(100.0*sum(street1Seen)/sum(HDs),1) AS saw_f
+ ,format(100.0*sum(sawShowdown)/sum(HDs),1) AS sawsd
+ ,case when sum(street1Seen) = 0 then 'oo'
+ else format(100.0*sum(sawShowdown)/sum(street1Seen),1)
+ end AS wtsdwsf
+ ,case when sum(sawShowdown) = 0 then 'oo'
+ end AS wtsdwsf
+ ,case when sum(sawShowdown) = 0 then 'oo'
+ else format(100.0*sum(wonAtSD)/sum(sawShowdown),1)
+ end AS wmsd
+ ,case when sum(street1Seen) = 0 then 'oo'
+ else format(100.0*sum(street1Aggr)/sum(street1Seen),1)
+ end AS FlAFq
+ ,case when sum(street2Seen) = 0 then 'oo'
+ else format(100.0*sum(street2Aggr)/sum(street2Seen),1)
+ end AS TuAFq
+ ,case when sum(street3Seen) = 0 then 'oo'
+ else format(100.0*sum(street3Aggr)/sum(street3Seen),1)
+ end AS RvAFq
+ ,case when sum(street1Seen)+sum(street2Seen)+sum(street3Seen) = 0 then 'oo'
+ else format(100.0*(sum(street1Aggr)+sum(street2Aggr)+sum(street3Aggr))
+ /(sum(street1Seen)+sum(street2Seen)+sum(street3Seen)),1)
+ end AS PoFAFq
+ ,format(sum(totalProfit)/100.0,2) AS Net
+ ,format((sum(totalProfit)/(gt.bigBlind+0.0)) / (sum(HDs)/100.0),2)
+ AS BBper100
+ ,format( (sum(totalProfit)/100.0) / sum(HDs), 4) AS Profitperhand
+ from Gametypes gt
+ inner join Sites s on s.Id = gt.siteId
+ inner join HudCache hc on hc.gameTypeId = gt.Id
+ where hc.playerId in
+ # use here ?
+ group by gt.base
+ ,gt.category
+ ,upper(gt.limitType)
+ ,s.name
+ ,gt.bigBlind
+ ,hc.gametypeId
+ ,PlPosition
+ ) stats
+ inner join
+ ( select # profit from handsplayers/handsactions
+ hprof.gameTypeId,
+ case when hprof.position = 'B' then -2
+ when hprof.position = 'S' then -1
+ when hprof.position in ('3','4') then 2
+ when hprof.position in ('6','7') then 5
+ else hprof.position
+ end as PlPosition,
+ sum(hprof.profit) as sum_profit,
+ avg(hprof.profit/100.0) as profitperhand,
+ variance(hprof.profit/100.0) as variance,
+ count(*) as n
+ from
+ (select hp.handId, h.gameTypeId, hp.position, hp.winnings, SUM(ha.amount)
+ costs, hp.winnings - SUM(ha.amount) profit
+ from HandsPlayers hp
+ inner join Hands h ON h.id = hp.handId
+ left join HandsActions ha ON ha.handPlayerId = hp.id
+ where hp.playerId in
+ # use here ?
+ and hp.tourneysPlayersId IS NULL
+ and ((hp.card1Value = and hp.card2Value = ) or (hp.card1Value = and hp.card2Value = ))
+ group by hp.handId, h.gameTypeId, hp.position, hp.winnings
+ ) hprof
+ group by hprof.gameTypeId, PlPosition
+ ) hprof2
+ on ( hprof2.gameTypeId = stats.gameTypeId
+ and hprof2.PlPosition = stats.PlPosition)
+ order by stats.category, stats.limittype, stats.bigBlind, cast(stats.PlPosition as signed)
+ """
+
if __name__== "__main__":
from optparse import OptionParser
diff --git a/pyfpdb/FulltiltToFpdb.py b/pyfpdb/FulltiltToFpdb.py
index 8a4436fd..f3d30229 100755
--- a/pyfpdb/FulltiltToFpdb.py
+++ b/pyfpdb/FulltiltToFpdb.py
@@ -1,4 +1,6 @@
#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
# Copyright 2008, Carl Gherardi
#
# This program is free software; you can redistribute it and/or modify
@@ -17,102 +19,117 @@
########################################################################
import sys
-import Configuration
+import logging
from HandHistoryConverter import *
-# FullTilt HH Format
+# Fulltilt HH Format converter
-#Full Tilt Poker Game #9403951181: Table CR - tay - $0.05/$0.10 - No Limit Hold'em - 9:40:20 ET - 2008/12/09
-#Seat 1: rigoise ($15.95)
-#Seat 2: K2dream ($6.70)
-#Seat 4: ravens2216 ($10)
-#Seat 5: rizkouner ($4)
-#Seat 6: Sorrowful ($8.35)
-#rigoise posts the small blind of $0.05
-#K2dream posts the big blind of $0.10
-#5 seconds left to act
-#rizkouner posts $0.10
-#The button is in seat #6
-#*** HOLE CARDS ***
-#Dealt to Sorrowful [8h Qc]
-#ravens2216 folds
-#rizkouner checks
-#Sorrowful has 15 seconds left to act
-#Sorrowful folds
-#rigoise folds
-#K2dream checks
-#*** FLOP *** [9d Kc 5c]
-#K2dream checks
-#rizkouner checks
-#*** TURN *** [9d Kc 5c] [5h]
-#K2dream has 15 seconds left to act
-#K2dream bets $0.20
-#rizkouner calls $0.20
-#*** RIVER *** [9d Kc 5c 5h] [6h]
-#K2dream checks
-#rizkouner has 15 seconds left to act
-#rizkouner bets $0.20
-#K2dream folds
-#Uncalled bet of $0.20 returned to rizkouner
-#rizkouner mucks
-#rizkouner wins the pot ($0.60)
-#*** SUMMARY ***
-#Total pot $0.65 | Rake $0.05
-#Board: [9d Kc 5c 5h 6h]
-#Seat 1: rigoise (small blind) folded before the Flop
-#Seat 2: K2dream (big blind) folded on the River
-#Seat 4: ravens2216 didn't bet (folded)
-#Seat 5: rizkouner collected ($0.60), mucked
-#Seat 6: Sorrowful (button) didn't bet (folded)
-#Seat N: rizkouner (button) showed [Jh Ah] and won ($0.70) with a pair of Threes
+class Fulltilt(HandHistoryConverter):
+
+ # Static regexes
+ re_GameInfo = re.compile('- (?P\$|)?(?P[.0-9]+)/\$?(?P[.0-9]+) (Ante \$(?P[.0-9]+) )?- (?P(No Limit|Pot Limit|Limit))? (?P(Hold\'em|Omaha Hi|Razz))')
+ re_SplitHands = re.compile(r"(\n\n+)")
+ re_HandInfo = re.compile('.*#(?P[0-9]+): Table (?P[- a-zA-Z]+) (\((?P.+)\) )?- \$?(?P[.0-9]+)/\$?(?P[.0-9]+) (Ante \$(?P[.0-9]+) )?- (?P[a-zA-Z\' ]+) - (?P.*)')
+ re_Button = re.compile('^The button is in seat #(?P\d+)', re.MULTILINE)
+ re_PlayerInfo = re.compile('Seat (?P[0-9]+): (?P.*) \(\$(?P[.0-9]+)\)\n')
+ re_Board = re.compile(r"\[(?P.+)\]")
+
+ def __init__(self, in_path = '-', out_path = '-', follow = False, autostart=True):
+ """\
+in_path (default '-' = sys.stdin)
+out_path (default '-' = sys.stdout)
+follow : whether to tail -f the input"""
+ HandHistoryConverter.__init__(self, in_path, out_path, sitename="Fulltilt", follow=follow)
+ logging.info("Initialising Fulltilt converter class")
+ self.filetype = "text"
+ self.codepage = "cp1252"
+ if autostart:
+ self.start()
+
+
+ def compilePlayerRegexs(self, hand):
+ players = set([player[1] for player in hand.players])
+ if not players <= self.compiledPlayers: # x <= y means 'x is subset of y'
+ # we need to recompile the player regexs.
+ self.compiledPlayers = players
+ player_re = "(?P" + "|".join(map(re.escape, players)) + ")"
+ logging.debug("player_re: " + player_re)
+ self.re_PostSB = re.compile(r"^%s posts the small blind of \$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_PostBB = re.compile(r"^%s posts (the big blind of )?\$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_Antes = re.compile(r"^%s antes \$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_BringIn = re.compile(r"^%s brings in for \$?(?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_PostBoth = re.compile(r"^%s posts small \& big blinds \[\$? (?P[.0-9]+)" % player_re, re.MULTILINE)
+ self.re_HeroCards = re.compile(r"^Dealt to %s(?: \[(?P.+?)\])?( \[(?P.+?)\])" % player_re, re.MULTILINE)
+ self.re_Action = re.compile(r"^%s(?P bets| checks| raises to| completes it to| calls| folds)(\s\$(?P[.\d]+))?" % player_re, re.MULTILINE)
+ self.re_ShowdownAction = re.compile(r"^%s shows \[(?P.*)\]" % player_re, re.MULTILINE)
+ self.re_CollectPot = re.compile(r"^Seat (?P[0-9]+): %s (\(button\) |\(small blind\) |\(big blind\) )?(collected|showed \[.*\] and won) \(\$(?P[.\d]+)\)(, mucked| with.*)" % player_re, re.MULTILINE)
+ self.re_SitsOut = re.compile(r"^%s sits out" % player_re, re.MULTILINE)
+ self.re_ShownCards = re.compile(r"^Seat (?P[0-9]+): %s \(.*\) showed \[(?P.*)\].*" % player_re, re.MULTILINE)
-class FullTilt(HandHistoryConverter):
- def __init__(self, config, file):
- print "Initialising FullTilt converter class"
- HandHistoryConverter.__init__(self, config, file, sitename="FullTilt") # Call super class init.
- self.sitename = "FullTilt"
- self.setFileType("text", "cp1252")
- self.rexx.setGameInfoRegex('- \$?(?P[.0-9]+)/\$?(?P[.0-9]+) -')
- self.rexx.setSplitHandRegex('\n\n+')
- self.rexx.setHandInfoRegex('.*#(?P[0-9]+): Table (?P[- a-zA-Z]+) (\((?P.+)\) )?- \$?(?P[.0-9]+)/\$?(?P[.0-9]+) - (?P[a-zA-Z\' ]+) - (?P.*)')
-# self.rexx.setHandInfoRegex('.*#(?P[0-9]+): Table (?P[ a-zA-Z]+) - \$?(?P[.0-9]+)/\$?(?P[.0-9]+) - (?P.*) - (?P [0-9]+):(?P[0-9]+) ET - (?P[0-9]+)/(?P[0-9]+)/(?P[0-9]+)Table (?P[ a-zA-Z]+)\nSeat (?P[0-9]+)')
- self.rexx.button_re = re.compile('The button is in seat #(?P\d+)')
- self.rexx.setPlayerInfoRegex('Seat (?P[0-9]+): (?P.*) \(\$(?P[.0-9]+)\)\n')
- self.rexx.setPostSbRegex('.*\n(?P.*) posts the small blind of \$?(?P[.0-9]+)')
- self.rexx.setPostBbRegex('.*\n(?P.*) posts (the big blind of )?\$?(?P[.0-9]+)')
- self.rexx.setPostBothRegex('.*\n(?P.*) posts small \& big blinds \[\$? (?P[.0-9]+)')
- self.rexx.setHeroCardsRegex('.*\nDealt\sto\s(?P.*)\s\[(?P.*)\]')
- self.rexx.setActionStepRegex('.*\n(?P.*)(?P bets| checks| raises to| calls| folds)(\s\$(?P[.\d]+))?')
- self.rexx.setShowdownActionRegex('.*\n(?P.*) shows \[(?P.*)\]')
- self.rexx.setCollectPotRegex(r"Seat (?P[0-9]+): (?P.*?) (\(button\) |\(small blind\) |\(big blind\) )?(collected|showed \[.*\] and won) \(\$(?P[.\d]+)\)(, mucked| with.*)")
- self.rexx.shown_cards_re = re.compile('Seat (?P[0-9]+): (?P.*) \(.*\) showed \[(?P.*)\].*')
- self.rexx.sits_out_re = re.compile('(?P.*) sits out')
- self.rexx.compileRegexes()
def readSupportedGames(self):
- pass
+ return [["ring", "hold", "nl"],
+ ["ring", "hold", "pl"],
+ ["ring", "hold", "fl"],
+ ["ring", "stud", "fl"],
+ ["ring", "omaha", "pl"]
+ ]
- def determineGameType(self):
- # Cheating with this regex, only support nlhe at the moment
- gametype = ["ring", "hold", "nl"]
-
- m = self.rexx.game_info_re.search(self.obs)
- gametype = gametype + [m.group('SB')]
- gametype = gametype + [m.group('BB')]
+ def determineGameType(self, handText):
+ # Full Tilt Poker Game #10777181585: Table Deerfly (deep 6) - $0.01/$0.02 - Pot Limit Omaha Hi - 2:24:44 ET - 2009/02/22
+ # Full Tilt Poker Game #10773265574: Table Butte (6 max) - $0.01/$0.02 - Pot Limit Hold'em - 21:33:46 ET - 2009/02/21
+ # Full Tilt Poker Game #9403951181: Table CR - tay - $0.05/$0.10 - No Limit Hold'em - 9:40:20 ET - 2008/12/09
+ # Full Tilt Poker Game #10809877615: Table Danville - $0.50/$1 Ante $0.10 - Limit Razz - 21:47:27 ET - 2009/02/23
+ info = {'type':'ring'}
- return gametype
+ m = self.re_GameInfo.search(handText)
+ if not m:
+ return None
+
+ mg = m.groupdict()
+
+ # translations from captured groups to our info strings
+ limits = { 'No Limit':'nl', 'Pot Limit':'pl', 'Limit':'fl' }
+ games = { # base, category
+ "Hold'em" : ('hold','holdem'),
+ 'Omaha Hi' : ('hold','omahahi'),
+ 'Razz' : ('stud','razz'),
+ '7 Card Stud' : ('stud','studhi')
+ }
+ currencies = { u' €':'EUR', '$':'USD', '':'T$' }
+ if 'LIMIT' in mg:
+ info['limitType'] = limits[mg['LIMIT']]
+ if 'GAME' in mg:
+ (info['base'], info['category']) = games[mg['GAME']]
+ if 'SB' in mg:
+ info['sb'] = mg['SB']
+ if 'BB' in mg:
+ info['bb'] = mg['BB']
+ if 'CURRENCY' in mg:
+ info['currency'] = currencies[mg['CURRENCY']]
+ # NB: SB, BB must be interpreted as blinds or bets depending on limit type.
+
+ return info
def readHandInfo(self, hand):
- m = self.rexx.hand_info_re.search(hand.string,re.DOTALL)
- #print m.groups()
+ m = self.re_HandInfo.search(hand.handText,re.DOTALL)
+
+ if(m == None):
+ logging.info("Didn't match re_HandInfo")
+ logging.info(hand.handText)
+ return None
+
hand.handid = m.group('HID')
hand.tablename = m.group('TABLE')
- hand.buttonpos = int(self.rexx.button_re.search(hand.string).group('BUTTON'))
hand.starttime = time.strptime(m.group('DATETIME'), "%H:%M:%S ET - %Y/%m/%d")
+ hand.maxseats = 8 # assume 8-max until we see otherwise
+ if m.group('TABLEATTRIBUTES'):
+ m2 = re.search("(deep )?(\d+)( max)?", m.group('TABLEATTRIBUTES'))
+ hand.maxseats = int(m2.group(2))
# These work, but the info is already in the Hand class - should be used for tourneys though.
-# m.group('SB')
-# m.group('BB')
-# m.group('GAMETYPE')
+# m.group('SB')
+# m.group('BB')
+# m.group('GAMETYPE')
# Stars format (Nov 10 2008): 2008/11/07 12:38:49 CET [2008/11/07 7:38:49 ET]
# or : 2008/11/07 12:38:49 ET
@@ -125,43 +142,66 @@ class FullTilt(HandHistoryConverter):
#FIXME: hand.buttonpos = int(m.group('BUTTON'))
def readPlayerStacks(self, hand):
- m = self.rexx.player_info_re.finditer(hand.string)
+ m = self.re_PlayerInfo.finditer(hand.handText)
players = []
for a in m:
hand.addPlayer(int(a.group('SEAT')), a.group('PNAME'), a.group('CASH'))
def markStreets(self, hand):
# PREFLOP = ** Dealing down cards **
- # This re fails if, say, river is missing; then we don't get the ** that starts the river.
- m = re.search(r"\*\*\* HOLE CARDS \*\*\*(?P.+(?=\*\*\* FLOP \*\*\*)|.+)"
+ if hand.gametype['base'] == 'hold':
+ m = re.search(r"\*\*\* HOLE CARDS \*\*\*(?P.+(?=\*\*\* FLOP \*\*\*)|.+)"
r"(\*\*\* FLOP \*\*\*(?P \[\S\S \S\S \S\S\].+(?=\*\*\* TURN \*\*\*)|.+))?"
r"(\*\*\* TURN \*\*\* \[\S\S \S\S \S\S] (?P\[\S\S\].+(?=\*\*\* RIVER \*\*\*)|.+))?"
- r"(\*\*\* RIVER \*\*\* \[\S\S \S\S \S\S \S\S] (?P\[\S\S\].+))?", hand.string,re.DOTALL)
-
+ r"(\*\*\* RIVER \*\*\* \[\S\S \S\S \S\S \S\S] (?P\[\S\S\].+))?", hand.handText,re.DOTALL)
+ elif hand.gametype['base'] == "stud": # or should this be gametype['category'] == 'razz'
+ m = re.search(r"(?P.+(?=\*\*\* 3RD STREET \*\*\*)|.+)"
+ r"(\*\*\* 3RD STREET \*\*\*(?P.+(?=\*\*\* 4TH STREET \*\*\*)|.+))?"
+ r"(\*\*\* 4TH STREET \*\*\*(?P.+(?=\*\*\* 5TH STREET \*\*\*)|.+))?"
+ r"(\*\*\* 5TH STREET \*\*\*(?P.+(?=\*\*\* 6TH STREET \*\*\*)|.+))?"
+ r"(\*\*\* 6TH STREET \*\*\*(?P.+(?=\*\*\* 7TH STREET \*\*\*)|.+))?"
+ r"(\*\*\* 7TH STREET \*\*\*(?P.+))?", hand.handText,re.DOTALL)
hand.addStreets(m)
def readCommunityCards(self, hand, street): # street has been matched by markStreets, so exists in this hand
if street in ('FLOP','TURN','RIVER'): # a list of streets which get dealt community cards (i.e. all but PREFLOP)
- self.rexx.board_re = re.compile(r"\[(?P.+)\]")
#print "DEBUG readCommunityCards:", street, hand.streets.group(street)
- m = self.rexx.board_re.search(hand.streets.group(street))
+ m = self.re_Board.search(hand.streets[street])
hand.setCommunityCards(street, m.group('CARDS').split(' '))
def readBlinds(self, hand):
try:
- m = self.rexx.small_blind_re.search(hand.string)
+ m = self.re_PostSB.search(hand.handText)
hand.addBlind(m.group('PNAME'), 'small blind', m.group('SB'))
except: # no small blind
hand.addBlind(None, None, None)
- for a in self.rexx.big_blind_re.finditer(hand.string):
+ for a in self.re_PostBB.finditer(hand.handText):
hand.addBlind(a.group('PNAME'), 'big blind', a.group('BB'))
- for a in self.rexx.both_blinds_re.finditer(hand.string):
+ for a in self.re_PostBoth.finditer(hand.handText):
hand.addBlind(a.group('PNAME'), 'small & big blinds', a.group('SBBB'))
+ def readAntes(self, hand):
+ logging.debug("reading antes")
+ m = self.re_Antes.finditer(hand.handText)
+ for player in m:
+ logging.debug("hand.addAnte(%s,%s)" %(player.group('PNAME'), player.group('ANTE')))
+ hand.addAnte(player.group('PNAME'), player.group('ANTE'))
+
+ def readBringIn(self, hand):
+ m = self.re_BringIn.search(hand.handText,re.DOTALL)
+ if m:
+ logging.debug("Player bringing in: %s for %s" %(m.group('PNAME'), m.group('BRINGIN')))
+ hand.addBringIn(m.group('PNAME'), m.group('BRINGIN'))
+ else:
+ logging.warning("No bringin found")
+
+ def readButton(self, hand):
+ hand.buttonpos = int(self.re_Button.search(hand.handText).group('BUTTON'))
+
def readHeroCards(self, hand):
- m = self.rexx.hero_cards_re.search(hand.string)
+ m = self.re_HeroCards.search(hand.handText)
if(m == None):
#Not involved in hand
hand.involved = False
@@ -169,15 +209,73 @@ class FullTilt(HandHistoryConverter):
hand.hero = m.group('PNAME')
# "2c, qh" -> set(["2c","qc"])
# Also works with Omaha hands.
- cards = m.group('CARDS')
- cards = set(cards.split(' '))
+ cards = m.group('NEWCARDS')
+ cards = [c.strip() for c in cards.split(' ')]
hand.addHoleCards(cards, m.group('PNAME'))
+ def readStudPlayerCards(self, hand, street):
+ # This could be the most tricky one to get right.
+ # It looks for cards dealt in 'street',
+ # which may or may not be in the section of the hand designated 'street' by markStreets earlier.
+ # Here's an example at FTP of what 'THIRD' and 'FOURTH' look like to hero PokerAscetic
+ #
+ #"*** 3RD STREET ***
+ #Dealt to BFK23 [Th]
+ #Dealt to cutiepr1nnymaid [8c]
+ #Dealt to PokerAscetic [7c 8s] [3h]
+ #..."
+ #
+ #"*** 4TH STREET ***
+ #Dealt to cutiepr1nnymaid [8c] [2s]
+ #Dealt to PokerAscetic [7c 8s 3h] [5s]
+ #..."
+ #Note that hero's first two holecards are only reported at 3rd street as 'old' cards.
+ logging.debug("readStudPlayerCards")
+ m = self.re_HeroCards.finditer(hand.streets[street])
+ for player in m:
+ logging.debug(player.groupdict())
+ (pname, oldcards, newcards) = (player.group('PNAME'), player.group('OLDCARDS'), player.group('NEWCARDS'))
+ if oldcards:
+ oldcards = [c.strip() for c in oldcards.split(' ')]
+ if newcards:
+ newcards = [c.strip() for c in newcards.split(' ')]
+ # options here:
+ # (1) we trust the hand will know what to do -- probably check that the old cards match what it already knows, and add the newcards to this street.
+ # (2) we're the experts at this particular history format and we know how we're going to be called (once for each street in Hand.streetList)
+ # so call addPlayerCards with the appropriate information.
+ # I favour (2) here but I'm afraid it is rather stud7-specific.
+ # in the following, the final list of cards will be in 'newcards' whilst if the first list exists (most of the time it does) it will be in 'oldcards'
+ if street=='ANTES':
+ return
+ elif street=='THIRD':
+ # we'll have observed hero holecards in CARDS and thirdstreet open cards in 'NEWCARDS'
+ # hero: [xx][o]
+ # others: [o]
+ hand.addPlayerCards(player = player.group('PNAME'), street = street, closed = oldcards, open = newcards)
+ elif street in ('FOURTH', 'FIFTH', 'SIXTH'):
+ # 4th:
+ # hero: [xxo] [o]
+ # others: [o] [o]
+ # 5th:
+ # hero: [xxoo] [o]
+ # others: [oo] [o]
+ # 6th:
+ # hero: [xxooo] [o]
+ # others: [ooo] [o]
+ hand.addPlayerCards(player = player.group('PNAME'), street = street, open = newcards)
+ # we may additionally want to check the earlier streets tally with what we have but lets trust it for now.
+ elif street=='SEVENTH' and newcards:
+ # hero: [xxoooo] [x]
+ # others: not reported.
+ hand.addPlayerCards(player = player.group('PNAME'), street = street, closed = newcards)
+
def readAction(self, hand, street):
- m = self.rexx.action_re.finditer(hand.streets.group(street))
+ m = self.re_Action.finditer(hand.streets[street])
for action in m:
if action.group('ATYPE') == ' raises to':
hand.addRaiseTo( street, action.group('PNAME'), action.group('BET') )
+ elif action.group('ATYPE') == ' completes it to':
+ hand.addComplete( street, action.group('PNAME'), action.group('BET') )
elif action.group('ATYPE') == ' calls':
hand.addCall( street, action.group('PNAME'), action.group('BET') )
elif action.group('ATYPE') == ' bets':
@@ -187,34 +285,42 @@ class FullTilt(HandHistoryConverter):
elif action.group('ATYPE') == ' checks':
hand.addCheck( street, action.group('PNAME'))
else:
- print "DEBUG: unimplemented readAction: %s %s" %(action.group('PNAME'),action.group('ATYPE'),)
+ print "DEBUG: unimplemented readAction: '%s' '%s'" %(action.group('PNAME'),action.group('ATYPE'),)
def readShowdownActions(self, hand):
- for shows in self.rexx.showdown_action_re.finditer(hand.string):
+ for shows in self.re_ShowdownAction.finditer(hand.handText):
cards = shows.group('CARDS')
- cards = set(cards.split(' '))
+ cards = cards.split(' ')
hand.addShownCards(cards, shows.group('PNAME'))
def readCollectPot(self,hand):
- for m in self.rexx.collect_pot_re.finditer(hand.string):
+ for m in self.re_CollectPot.finditer(hand.handText):
hand.addCollectPot(player=m.group('PNAME'),pot=m.group('POT'))
def readShownCards(self,hand):
- for m in self.rexx.shown_cards_re.finditer(hand.string):
+ for m in self.re_ShownCards.finditer(hand.handText):
if m.group('CARDS') is not None:
cards = m.group('CARDS')
- cards = set(cards.split(' '))
+ cards = cards.split(' ')
hand.addShownCards(cards=cards, player=m.group('PNAME'))
if __name__ == "__main__":
- c = Configuration.Config()
- if len(sys.argv) == 1:
- testfile = "regression-test-files/FT20081209 CR - tay - $0.05-$0.10 - No Limit Hold'em.txt"
- else:
- testfile = sys.argv[1]
- print "Converting: ", testfile
- e = FullTilt(c, testfile)
- e.processFile()
- print str(e)
+ parser = OptionParser()
+ parser.add_option("-i", "--input", dest="ipath", help="parse input hand history", default="regression-test-files/fulltilt/razz/FT20090223 Danville - $0.50-$1 Ante $0.10 - Limit Razz.txt")
+ parser.add_option("-o", "--output", dest="opath", help="output translation to", default="-")
+ parser.add_option("-f", "--follow", dest="follow", help="follow (tail -f) the input", action="store_true", default=False)
+ parser.add_option("-q", "--quiet",
+ action="store_const", const=logging.CRITICAL, dest="verbosity", default=logging.INFO)
+ parser.add_option("-v", "--verbose",
+ action="store_const", const=logging.INFO, dest="verbosity")
+ parser.add_option("--vv",
+ action="store_const", const=logging.DEBUG, dest="verbosity")
+
+ (options, args) = parser.parse_args()
+
+ LOG_FILENAME = './logging.out'
+ logging.basicConfig(filename=LOG_FILENAME,level=options.verbosity)
+
+ e = Fulltilt(in_path = options.ipath, out_path = options.opath, follow = options.follow)
diff --git a/pyfpdb/GuiAutoImport.py b/pyfpdb/GuiAutoImport.py
old mode 100644
new mode 100755
index 38535ad1..872c5c67
--- a/pyfpdb/GuiAutoImport.py
+++ b/pyfpdb/GuiAutoImport.py
@@ -26,7 +26,8 @@ import os
import sys
import time
import fpdb_import
-
+from optparse import OptionParser
+import Configuration
class GuiAutoImport (threading.Thread):
def __init__(self, settings, config):
@@ -44,7 +45,7 @@ class GuiAutoImport (threading.Thread):
self.importer = fpdb_import.Importer(self,self.settings, self.config)
self.importer.setCallHud(True)
- self.importer.setMinPrint(30)
+ self.importer.setMinPrint(settings['minPrint'])
self.importer.setQuiet(False)
self.importer.setFailOnError(False)
self.importer.setHandCount(0)
@@ -106,7 +107,8 @@ class GuiAutoImport (threading.Thread):
"""Callback for timer to do an import iteration."""
if self.doAutoImportBool:
self.importer.runUpdated()
- print "GuiAutoImport.import_dir done"
+ sys.stdout.write(".")
+ sys.stdout.flush()
return True
else:
return False
@@ -128,12 +130,13 @@ class GuiAutoImport (threading.Thread):
widget.set_label(u'Stop Autoimport')
if self.pipe_to_hud is None:
if os.name == 'nt':
- command = "python HUD_run_me.py" + " %s" % (self.database)
+ command = "python HUD_main.py" + " %s" % (self.database)
bs = 0 # windows is not happy with line buffing here
self.pipe_to_hud = subprocess.Popen(command, bufsize = bs, stdin = subprocess.PIPE,
universal_newlines=True)
else:
- command = self.config.execution_path('HUD_run_me.py')
+ command = os.path.join(sys.path[0], 'HUD_main.py')
+ #command = self.config.execution_path('HUD_main.py') # Hi Ray. Sorry about this, kludging.
bs = 1
self.pipe_to_hud = subprocess.Popen((command, self.database), bufsize = bs, stdin = subprocess.PIPE,
universal_newlines=True)
@@ -199,13 +202,14 @@ class GuiAutoImport (threading.Thread):
filter.show()
def addSites(self, vbox):
- for site in self.config.supported_sites.keys():
+ the_sites = self.config.get_supported_sites()
+ for site in the_sites:
pathHBox = gtk.HBox(False, 0)
vbox.pack_start(pathHBox, False, True, 0)
pathHBox.show()
-
- paths = self.config.get_default_paths(site)
+
params = self.config.get_site_parameters(site)
+ paths = self.config.get_default_paths(site)
self.createSiteLine(pathHBox, site, False, paths['hud-defaultPath'], params['converter'], params['enabled'])
self.input_settings[site] = [paths['hud-defaultPath']] + [params['converter']]
@@ -213,18 +217,41 @@ if __name__== "__main__":
def destroy(*args): # call back for terminating the main eventloop
gtk.main_quit()
- settings = {}
- settings['db-host'] = "192.168.1.100"
- settings['db-user'] = "mythtv"
- settings['db-password'] = "mythtv"
- settings['db-databaseName'] = "fpdb"
- settings['hud-defaultInterval'] = 10
- settings['hud-defaultPath'] = 'C:/Program Files/PokerStars/HandHistory/nutOmatic'
- settings['callFpdbHud'] = True
+# settings = {}
+# settings['db-host'] = "192.168.1.100"
+# settings['db-user'] = "mythtv"
+# settings['db-password'] = "mythtv"
+# settings['db-databaseName'] = "fpdb"
+# settings['hud-defaultInterval'] = 10
+# settings['hud-defaultPath'] = 'C:/Program Files/PokerStars/HandHistory/nutOmatic'
+# settings['callFpdbHud'] = True
- i = GuiAutoImport(settings)
- main_window = gtk.Window()
- main_window.connect("destroy", destroy)
- main_window.add(i.mainVBox)
- main_window.show()
- gtk.main()
+ parser = OptionParser()
+ parser.add_option("-q", "--quiet", action="store_false", dest="gui", default=True, help="don't start gui")
+ parser.add_option("-m", "--minPrint", "--status", dest="minPrint", default="0", type="int",
+ help="How often to print a one-line status report (0 (default) means never)")
+ (options, sys.argv) = parser.parse_args()
+
+ config = Configuration.Config()
+# db = fpdb_db.fpdb_db()
+
+ settings = {}
+ settings['minPrint'] = options.minPrint
+ if os.name == 'nt': settings['os'] = 'windows'
+ else: settings['os'] = 'linuxmac'
+
+ settings.update(config.get_db_parameters('fpdb'))
+ settings.update(config.get_tv_parameters())
+ settings.update(config.get_import_parameters())
+ settings.update(config.get_default_paths())
+
+ if(options.gui == True):
+ i = GuiAutoImport(settings, config)
+ main_window = gtk.Window()
+ main_window.connect('destroy', destroy)
+ main_window.add(i.mainVBox)
+ main_window.show()
+ gtk.main()
+ else:
+ pass
+
diff --git a/pyfpdb/GuiBulkImport.py b/pyfpdb/GuiBulkImport.py
index e3bee81c..5284ae9e 100644
--- a/pyfpdb/GuiBulkImport.py
+++ b/pyfpdb/GuiBulkImport.py
@@ -1,156 +1,267 @@
#!/usr/bin/python
+# -*- coding: utf-8 -*-
-#Copyright 2008 Steffen Jobbagy-Felso
-#This program is free software: you can redistribute it and/or modify
-#it under the terms of the GNU Affero General Public License as published by
-#the Free Software Foundation, version 3 of the License.
+# Copyright 2008 Steffen Jobbagy-Felso
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU Affero General Public License as published by
+# the Free Software Foundation, version 3 of the License.
#
-#This program is distributed in the hope that it will be useful,
-#but WITHOUT ANY WARRANTY; without even the implied warranty of
-#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-#GNU General Public License for more details.
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
#
-#You should have received a copy of the GNU Affero General Public License
-#along with this program. If not, see .
-#In the "official" distribution you can find the license in
-#agpl-3.0.txt in the docs folder of the package.
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see .
+# In the "official" distribution you can find the license in
+# agpl-3.0.txt in the docs folder of the package.
-import threading
-import fpdb_simple
-import fpdb_import
+# Standard Library modules
+import os
+import sys
+from time import time
+from optparse import OptionParser
+
+# pyGTK modules
import pygtk
pygtk.require('2.0')
import gtk
-import os #todo: remove this once import_dir is in fpdb_import
-from time import time
-class GuiBulkImport (threading.Thread):
- def import_dir(self):
- """imports a directory, non-recursive. todo: move this to fpdb_import so CLI can use it"""
- self.path=self.inputFile
- self.importer.addImportDirectory(self.path)
- self.importer.setCallHud(False)
- starttime = time()
- self.importer.runImport()
- print "GuiBulkImport.import_dir done in %s" %(time() - starttime)
-
- def load_clicked(self, widget, data=None):
- self.inputFile=self.chooser.get_filename()
-
- self.handCount=self.hand_count_tbuffer.get_text(self.hand_count_tbuffer.get_start_iter(), self.hand_count_tbuffer.get_end_iter())
- if (self.handCount=="unlimited" or self.handCount=="Unlimited"):
- self.importer.setHandCount(0)
- else:
- self.importer.setHandCount(int(self.handCount))
+# fpdb/FreePokerTools modules
+import fpdb_simple
+import fpdb_import
+import fpdb_db
+import Configuration
- self.errorFile="failed.txt"
-
- self.minPrint=self.min_print_tbuffer.get_text(self.min_print_tbuffer.get_start_iter(), self.min_print_tbuffer.get_end_iter())
- if (self.minPrint=="never" or self.minPrint=="Never"):
- self.importer.setMinPrint(0)
- else:
- self.importer.setMinPrint=int(self.minPrint)
-
- self.quiet=self.info_tbuffer.get_text(self.info_tbuffer.get_start_iter(), self.info_tbuffer.get_end_iter())
- if (self.quiet=="yes"):
- self.importer.setQuiet(False)
- else:
- self.importer.setQuiet(True)
-
- self.failOnError=self.fail_error_tbuffer.get_text(self.fail_error_tbuffer.get_start_iter(), self.fail_error_tbuffer.get_end_iter())
- if (self.failOnError=="no"):
- self.importer.setFailOnError(False)
- else:
- self.importer.setFailOnError(True)
-
- if os.path.isdir(self.inputFile):
- self.import_dir()
- else:
- self.importer.addImportFile(self.inputFile)
- self.importer.setCallHud(False)
- self.importer.runImport()
- self.importer.clearFileList()
-
- def get_vbox(self):
- """returns the vbox of this thread"""
- return self.vbox
- #end def get_vbox
-
- def run (self):
- print "todo: implement bulk import thread"
- #end def run
-
- def __init__(self, db, settings, config):
- self.db=db
- self.settings=settings
- self.config=config
- self.importer = fpdb_import.Importer(self,self.settings, config)
-
- self.vbox=gtk.VBox(False,1)
- self.vbox.show()
-
- self.chooser = gtk.FileChooserWidget()
- self.chooser.set_filename(self.settings['bulkImport-defaultPath'])
- #chooser.set_default_response(gtk.RESPONSE_OK)
- #self.filesel.ok_button.connect_object("clicked", gtk.Widget.destroy, self.filesel)
- self.vbox.add(self.chooser)
- self.chooser.show()
-
-
- self.settings_hbox = gtk.HBox(False, 0)
- self.vbox.pack_end(self.settings_hbox, False, True, 0)
- self.settings_hbox.show()
-
- self.hand_count_label = gtk.Label("Hands to import per file")
- self.settings_hbox.add(self.hand_count_label)
- self.hand_count_label.show()
-
- self.hand_count_tbuffer=gtk.TextBuffer()
- self.hand_count_tbuffer.set_text("unlimited")
- self.hand_count_tview=gtk.TextView(self.hand_count_tbuffer)
- self.settings_hbox.add(self.hand_count_tview)
- self.hand_count_tview.show()
-
- self.min_hands_label = gtk.Label("Status every")
- self.settings_hbox.add(self.min_hands_label)
- self.min_hands_label.show()
-
- self.min_print_tbuffer=gtk.TextBuffer()
- self.min_print_tbuffer.set_text("never")
- self.min_print_tview=gtk.TextView(self.min_print_tbuffer)
- self.settings_hbox.add(self.min_print_tview)
- self.min_print_tview.show()
+class GuiBulkImport():
-
- self.toggles_hbox = gtk.HBox(False, 0)
- self.vbox.pack_end(self.toggles_hbox, False, True, 0)
- self.toggles_hbox.show()
+ def import_dir(self):
+ """imports a directory, non-recursive. todo: move this to fpdb_import so CLI can use it"""
- self.info_label = gtk.Label("Print start/end info:")
- self.toggles_hbox.add(self.info_label)
- self.info_label.show()
-
- self.info_tbuffer=gtk.TextBuffer()
- self.info_tbuffer.set_text("yes")
- self.info_tview=gtk.TextView(self.info_tbuffer)
- self.toggles_hbox.add(self.info_tview)
- self.info_tview.show()
-
- self.fail_error_label = gtk.Label("Fail on error:")
- self.toggles_hbox.add(self.fail_error_label)
- self.fail_error_label.show()
-
- self.fail_error_tbuffer=gtk.TextBuffer()
- self.fail_error_tbuffer.set_text("no")
- self.fail_error_tview=gtk.TextView(self.fail_error_tbuffer)
- self.toggles_hbox.add(self.fail_error_tview)
- self.fail_error_tview.show()
+ self.path = self.inputFile
+ self.importer.addImportDirectory(self.path)
+ self.importer.setCallHud(False)
+ starttime = time()
+ if not self.importer.settings['threads'] > 1:
+ (stored, dups, partial, errs, ttime) = self.importer.runImport()
+ print 'GuiBulkImport.import_dir done: Stored: %d Duplicates: %d Partial: %d Errors: %d in %s seconds - %d/sec'\
+ % (stored, dups, partial, errs, ttime, stored / ttime)
+ else:
+ self.importer.RunImportThreaded()
- self.load_button = gtk.Button("Import") #todo: rename variables to import too
- self.load_button.connect("clicked", self.load_clicked, "Import clicked")
- self.toggles_hbox.add(self.load_button)
- self.load_button.show()
+ def load_clicked(self, widget, data=None):
+# get the dir to import from the chooser
+ self.inputFile = self.chooser.get_filename()
+
+# get the import settings from the gui and save in the importer
+ self.importer.setHandCount(int(self.spin_hands.get_text()))
+ self.importer.setMinPrint(int(self.spin_hands.get_text()))
+ self.importer.setQuiet(self.chk_st_st.get_active())
+ self.importer.setFailOnError(self.chk_fail.get_active())
+ self.importer.setThreads(int(self.spin_threads.get_text()))
+ self.importer.setHandsInDB(self.n_hands_in_db)
+ cb_model = self.cb_dropindexes.get_model()
+ cb_index = self.cb_dropindexes.get_active()
+ if cb_index:
+ self.importer.setDropIndexes(cb_model[cb_index][0])
+ else:
+ self.importer.setDropIndexes("auto")
+ hhc=self.cbfilter.get_model()[self.cbfilter.get_active()][0]
+ self.lab_info.set_text("Importing")
+
+ self.importer.addBulkImportImportFileOrDir(self.inputFile,filter=hhc)
+ self.importer.setCallHud(False)
+ starttime = time()
+ (stored, dups, partial, errs, ttime) = self.importer.runImport()
+ print 'GuiBulkImport.import_dir done: Stored: %d \tDuplicates: %d \tPartial: %d \tErrors: %d in %s seconds - %d/sec'\
+ % (stored, dups, partial, errs, ttime, stored / ttime)
+ self.importer.clearFileList()
+
+ self.lab_info.set_text("Import finished")
+
+ def get_vbox(self):
+ """returns the vbox of this thread"""
+ return self.vbox
+
+ def __init__(self, db, settings, config):
+ self.db = db # this is an instance of fpdb_db
+ self.settings = settings
+ self.config = config
+ self.importer = fpdb_import.Importer(self, self.settings,
+ config)
+
+ self.vbox = gtk.VBox(False, 0)
+ self.vbox.show()
+
+ self.chooser = gtk.FileChooserWidget()
+ self.chooser.set_filename(self.settings['bulkImport-defaultPath'])
+ self.vbox.add(self.chooser)
+ self.chooser.show()
+
+# Table widget to hold the settings
+ self.table = gtk.Table(rows = 3, columns = 5, homogeneous = False)
+ self.vbox.add(self.table)
+ self.table.show()
+
+# checkbox - print start/stop?
+ self.chk_st_st = gtk.CheckButton('Print Start/Stop Info')
+ self.table.attach(self.chk_st_st, 0, 1, 0, 1, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK)
+ self.chk_st_st.show()
+ self.chk_st_st.set_active(True)
+
+# label - status
+ self.lab_status = gtk.Label("Hands/status print:")
+ self.table.attach(self.lab_status, 1, 2, 0, 1, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.lab_status.show()
+ self.lab_status.set_justify(gtk.JUSTIFY_RIGHT)
+
+# spin button - status
+ status_adj = gtk.Adjustment(value=100, lower=0, upper=300, step_incr=10, page_incr=1, page_size=0) #not sure what upper value should be!
+ self.spin_status = gtk.SpinButton(adjustment=status_adj, climb_rate=0.0, digits=0)
+ self.table.attach(self.spin_status, 2, 3, 0, 1, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK)
+ self.spin_status.show()
+
+# label - threads
+ self.lab_threads = gtk.Label("Number of threads:")
+ self.table.attach(self.lab_threads, 3, 4, 0, 1, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.lab_threads.show()
+ self.lab_threads.set_sensitive(False)
+ self.lab_threads.set_justify(gtk.JUSTIFY_RIGHT)
+
+# spin button - threads
+ threads_adj = gtk.Adjustment(value=0, lower=0, upper=10, step_incr=1, page_incr=1, page_size=0) #not sure what upper value should be!
+ self.spin_threads = gtk.SpinButton(adjustment=threads_adj, climb_rate=0.0, digits=0)
+ self.table.attach(self.spin_threads, 4, 5, 0, 1, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.spin_threads.show()
+ self.spin_threads.set_sensitive(False)
+
+# checkbox - fail on error?
+ self.chk_fail = gtk.CheckButton('Fail on error')
+ self.table.attach(self.chk_fail, 0, 1, 1, 2, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK)
+ self.chk_fail.show()
+
+# label - hands
+ self.lab_hands = gtk.Label("Hands/file:")
+ self.table.attach(self.lab_hands, 1, 2, 1, 2, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.lab_hands.show()
+ self.lab_hands.set_justify(gtk.JUSTIFY_RIGHT)
+
+# spin button - hands to import
+ hands_adj = gtk.Adjustment(value=0, lower=0, upper=10, step_incr=1, page_incr=1, page_size=0) #not sure what upper value should be!
+ self.spin_hands = gtk.SpinButton(adjustment=hands_adj, climb_rate=0.0, digits=0)
+ self.table.attach(self.spin_hands, 2, 3, 1, 2, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK)
+ self.spin_hands.show()
+
+# label - drop indexes
+ self.lab_drop = gtk.Label("Drop indexes:")
+ self.table.attach(self.lab_drop, 3, 4, 1, 2, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.lab_drop.show()
+ self.lab_drop.set_justify(gtk.JUSTIFY_RIGHT)
+
+# ComboBox - drop indexes
+ self.cb_dropindexes = gtk.combo_box_new_text()
+ self.cb_dropindexes.append_text('auto')
+ self.cb_dropindexes.append_text("don't drop")
+ self.cb_dropindexes.append_text('drop')
+ self.cb_dropindexes.set_active(0)
+ self.table.attach(self.cb_dropindexes, 4, 5, 1, 2, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK)
+ self.cb_dropindexes.show()
+
+# label - filter
+ self.lab_filter = gtk.Label("Site filter:")
+ self.table.attach(self.lab_filter, 2, 3, 2, 3, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.lab_filter.show()
+ self.lab_filter.set_justify(gtk.JUSTIFY_RIGHT)
+
+# ComboBox - filter
+ self.cbfilter = gtk.combo_box_new_text()
+ self.cbfilter.append_text("passthrough")
+ self.cbfilter.append_text("BetfairToFpdb")
+ self.cbfilter.append_text("EverleafToFpdb")
+ self.cbfilter.append_text("FulltiltToFpdb")
+ self.cbfilter.append_text("PokerStarsToFpdb")
+ self.cbfilter.set_active(0)
+ self.table.attach(self.cbfilter, 3, 4, 2, 3, xpadding = 10, ypadding = 0, yoptions=gtk.SHRINK)
+ self.cbfilter.show()
+
+# label - info
+ self.lab_info = gtk.Label()
+ self.table.attach(self.lab_info, 0, 4, 2, 3, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.lab_info.show()
+
+# button - Import
+ self.load_button = gtk.Button('Import') # todo: rename variables to import too
+ self.load_button.connect('clicked', self.load_clicked,
+ 'Import clicked')
+ self.table.attach(self.load_button, 4, 5, 2, 3, xpadding = 0, ypadding = 0, yoptions=gtk.SHRINK)
+ self.load_button.show()
+
+# see how many hands are in the db and adjust accordingly
+ tcursor = self.importer.fdb.db.cursor()
+ tcursor.execute("Select count(1) from Hands")
+ row = tcursor.fetchone()
+ tcursor.close()
+ self.n_hands_in_db = row[0]
+ if self.n_hands_in_db == 0:
+ self.cb_dropindexes.set_active(2)
+ self.cb_dropindexes.set_sensitive(False)
+ self.lab_drop.set_sensitive(False)
+
+def main(argv=None):
+ """main can also be called in the python interpreter, by supplying the command line as the argument."""
+ if argv is None:
+ argv = sys.argv[1:]
+
+ def destroy(*args): # call back for terminating the main eventloop
+ gtk.main_quit()
+
+ parser = OptionParser()
+ parser.add_option("-f", "--file", dest="filename", metavar="FILE", default=None,
+ help="Input file in quiet mode")
+ parser.add_option("-q", "--quiet", action="store_false", dest="gui", default=True,
+ help="don't start gui; deprecated (just give a filename with -f).")
+ parser.add_option("-c", "--convert", dest="filtername", default="passthrough", metavar="FILTER",
+ help="Conversion filter (*passthrough, FullTiltToFpdb, PokerStarsToFpdb, EverleafToFpdb)")
+ parser.add_option("-x", "--failOnError", action="store_true", default=False,
+ help="If this option is passed it quits when it encounters any error")
+ parser.add_option("-m", "--minPrint", "--status", dest="minPrint", default="0", type="int",
+ help="How often to print a one-line status report (0 (default) means never)")
+ (options, sys.argv) = parser.parse_args(args = argv)
+
+ config = Configuration.Config()
+ db = None
+
+ settings = {}
+ settings['minPrint'] = options.minPrint
+ if os.name == 'nt': settings['os'] = 'windows'
+ else: settings['os'] = 'linuxmac'
+
+ settings.update(config.get_db_parameters())
+ settings.update(config.get_tv_parameters())
+ settings.update(config.get_import_parameters())
+ settings.update(config.get_default_paths())
+
+ if not options.gui:
+ print '-q is deprecated. Just use "-f filename" instead'
+ # This is because -q on its own causes an error, so -f is necessary and sufficient for cmd line use
+ if not options.filename:
+ i = GuiBulkImport(db, settings, config)
+ main_window = gtk.Window()
+ main_window.connect('destroy', destroy)
+ main_window.add(i.vbox)
+ main_window.show()
+ gtk.main()
+ else:
+ #Do something useful
+ importer = fpdb_import.Importer(False,settings, config)
+ importer.setDropIndexes("auto")
+ importer.setFailOnError(options.failOnError)
+ importer.addBulkImportImportFileOrDir(os.path.expanduser(options.filename), filter=options.filtername)
+ importer.setCallHud(False)
+ importer.runImport()
+ importer.clearFileList()
+
+
+if __name__ == '__main__':
+ sys.exit(main())
- threading.Thread.__init__ ( self )
- print "initialised new bulk import thread (not actually a thread yet)"
-#end class import_threaded
diff --git a/pyfpdb/GuiGraphViewer.py b/pyfpdb/GuiGraphViewer.py
index 8026a2c7..5afc4a92 100644
--- a/pyfpdb/GuiGraphViewer.py
+++ b/pyfpdb/GuiGraphViewer.py
@@ -20,7 +20,7 @@ import pygtk
pygtk.require('2.0')
import gtk
import os
-from time import time
+from time import *
#import pokereval
try:
@@ -46,9 +46,15 @@ class GuiGraphViewer (threading.Thread):
return self.mainHBox
#end def get_vbox
+ def clearGraphData(self):
+ self.fig.clf()
+ if self.canvas is not None:
+ self.canvas.destroy()
+
+ self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea
+
def generateGraph(self, widget, data):
- try: self.canvas.destroy()
- except AttributeError: pass
+ self.clearGraphData()
sitenos = []
playerids = []
@@ -62,17 +68,16 @@ class GuiGraphViewer (threading.Thread):
if len(result) == 1:
playerids.append(result[0][0])
- if sitenos == []:
+ if not sitenos:
#Should probably pop up here.
print "No sites selected - defaulting to PokerStars"
sitenos = [2]
- if playerids == []:
+ if not playerids:
print "No player ids found"
return
- self.fig = Figure(figsize=(5,4), dpi=100)
#Set graph properties
self.ax = self.fig.add_subplot(111)
@@ -104,9 +109,9 @@ class GuiGraphViewer (threading.Thread):
#Draw plot
self.ax.plot(line,)
- self.canvas = FigureCanvas(self.fig) # a gtk.DrawingArea
self.graphBox.add(self.canvas)
self.canvas.show()
+ self.exportButton.set_sensitive(True)
#end of def showClicked
def getRingProfitGraph(self, names, sites):
@@ -279,16 +284,24 @@ class GuiGraphViewer (threading.Thread):
win.destroy()
def exportGraph (self, widget, data):
+ if self.fig is None:
+ return # Might want to disable export button until something has been generated.
dia_chooser = gtk.FileChooserDialog(title="Please choose the directory you wish to export to:",
action=gtk.FILE_CHOOSER_ACTION_OPEN,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
+ #TODO: Suggest path and filename to start with
response = dia_chooser.run()
if response == gtk.RESPONSE_OK:
self.exportDir = dia_chooser.get_filename()
+ print "DEBUG: self.exportDir = %s" %(self.exportDir)
elif response == gtk.RESPONSE_CANCEL:
print 'Closed, no graph exported'
dia_chooser.destroy()
+ #TODO: Check to see if file exists
+ #NOTE: Dangerous - will happily overwrite any file we have write access too
+ #TODO: This asks for a directory but will take a filename and overwrite it.
+ self.fig.savefig(self.exportDir, format="png")
def __init__(self, db, settings, querylist, config, debug=True):
"""Constructor for GraphViewer"""
@@ -354,8 +367,10 @@ class GuiGraphViewer (threading.Thread):
graphButton.connect("clicked", self.generateGraph, "cliced data")
graphButton.show()
+ self.fig = None
self.exportButton=gtk.Button("Export to File")
self.exportButton.connect("clicked", self.exportGraph, "show clicked")
+ self.exportButton.set_sensitive(False)
self.exportButton.show()
self.leftPanelBox.add(playerFrame)
@@ -366,3 +381,34 @@ class GuiGraphViewer (threading.Thread):
self.leftPanelBox.show()
self.graphBox.show()
+
+ self.fig = Figure(figsize=(5,4), dpi=100)
+ self.canvas = None
+
+#################################
+#
+# self.db.cursor.execute("""select UNIX_TIMESTAMP(handStart) as time, id from Hands ORDER BY time""")
+# THRESHOLD = 1800
+# hands = self.db.cursor.fetchall()
+#
+# times = map(lambda x:long(x[0]), hands)
+# handids = map(lambda x:int(x[1]), hands)
+# print "DEBUG: len(times) %s" %(len(times))
+# diffs = diff(times)
+# print "DEBUG: len(diffs) %s" %(len(diffs))
+# index = nonzero(diff(times) > THRESHOLD)
+# print "DEBUG: len(index[0]) %s" %(len(index[0]))
+# print "DEBUG: index %s" %(index)
+# print "DEBUG: index[0][0] %s" %(index[0][0])
+#
+# total = 0
+#
+# last_idx = 0
+# for i in range(len(index[0])):
+# print "Hands in session %4s: %4s Start: %s End: %s Total: %s" %(i, index[0][i] - last_idx, strftime("%d/%m/%Y %H:%M", localtime(times[last_idx])), strftime("%d/%m/%Y %H:%M", localtime(times[index[0][i]])), times[index[0][i]] - times[last_idx])
+# total = total + (index[0][i] - last_idx)
+# last_idx = index[0][i] + 1
+#
+# print "Total: ", total
+#################################
+
diff --git a/pyfpdb/GuiPlayerStats.py b/pyfpdb/GuiPlayerStats.py
index 1f1967e9..b2eb0108 100644
--- a/pyfpdb/GuiPlayerStats.py
+++ b/pyfpdb/GuiPlayerStats.py
@@ -67,7 +67,7 @@ class GuiPlayerStats (threading.Thread):
for t in titles:
l = gtk.Label(titles[col])
l.show()
- self.stats_table.attach(l, col, col+1, row, row+1)
+ self.stats_table.attach(l, col, col+1, row, row+1, yoptions=gtk.SHRINK)
col +=1
for row in range(rows-1):
@@ -87,7 +87,7 @@ class GuiPlayerStats (threading.Thread):
else:
l.set_alignment(xalign=1.0, yalign=0.5)
eb.add(l)
- self.stats_table.attach(eb, col, col+1, row+1, row+2)
+ self.stats_table.attach(eb, col, col+1, row+1, row+2, yoptions=gtk.SHRINK)
l.show()
eb.show()
self.fdb.db.commit()
diff --git a/pyfpdb/GuiPositionalStats.py b/pyfpdb/GuiPositionalStats.py
new file mode 100644
index 00000000..64828573
--- /dev/null
+++ b/pyfpdb/GuiPositionalStats.py
@@ -0,0 +1,211 @@
+#!/usr/bin/python
+
+#Copyright 2008 Steffen Jobbagy-Felso
+#This program is free software: you can redistribute it and/or modify
+#it under the terms of the GNU Affero General Public License as published by
+#the Free Software Foundation, version 3 of the License.
+#
+#This program is distributed in the hope that it will be useful,
+#but WITHOUT ANY WARRANTY; without even the implied warranty of
+#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+#GNU General Public License for more details.
+#
+#You should have received a copy of the GNU Affero General Public License
+#along with this program. If not, see .
+#In the "official" distribution you can find the license in
+#agpl-3.0.txt in the docs folder of the package.
+
+import threading
+import pygtk
+pygtk.require('2.0')
+import gtk
+import os
+
+import fpdb_import
+import fpdb_db
+import FpdbSQLQueries
+
+class GuiPositionalStats (threading.Thread):
+ def get_vbox(self):
+ """returns the vbox of this thread"""
+ return self.main_hbox
+
+ def toggleCallback(self, widget, data=None):
+# print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()])
+ self.activesite = data
+ print "DEBUG: activesite set to %s" %(self.activesite)
+
+ def cardCallback(self, widget, data=None):
+ print "DEBUG: %s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()])
+
+ def refreshStats(self, widget, data):
+ try: self.stats_table.destroy()
+ except AttributeError: pass
+ self.fillStatsFrame(self.stats_frame)
+
+ def fillStatsFrame(self, vbox):
+ # Get currently active site and grab playerid
+ print "DEBUG: attempting to fill stats frame"
+ tmp = self.sql.query['playerStatsByPosition']
+
+ result = self.cursor.execute(self.sql.query['getPlayerId'], (self.heroes[self.activesite],))
+ result = self.cursor.fetchall()
+ if not result == ():
+ pid = result[0][0]
+ pid = result[0][0]
+ tmp = tmp.replace("", "(" + str(pid) + ")")
+ self.cursor.execute(tmp)
+ result = self.cursor.fetchall()
+ cols = 16
+ rows = len(result)+1 # +1 for title row
+ self.stats_table = gtk.Table(rows, cols, False)
+ self.stats_table.set_col_spacings(4)
+ self.stats_table.show()
+ vbox.add(self.stats_table)
+
+ # Create header row
+ titles = ("Game", "Position", "#", "VPIP", "PFR", "Saw_F", "SawSD", "WtSDwsF", "W$SD", "FlAFq", "TuAFq", "RvAFq", "PoFAFq", "Net($)", "BB/100", "$/hand", "Variance")
+
+ col = 0
+ row = 0
+ for t in titles:
+ l = gtk.Label(titles[col])
+ l.show()
+ self.stats_table.attach(l, col, col+1, row, row+1, yoptions=gtk.SHRINK)
+ col +=1
+
+ for row in range(rows-1):
+ if(row%2 == 0):
+ bgcolor = "white"
+ else:
+ bgcolor = "lightgrey"
+ for col in range(cols):
+ eb = gtk.EventBox()
+ eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(bgcolor))
+ if result[row][col]:
+ l = gtk.Label(result[row][col])
+ else:
+ l = gtk.Label(' ')
+ if col == 0:
+ l.set_alignment(xalign=0.0, yalign=0.5)
+ else:
+ l.set_alignment(xalign=1.0, yalign=0.5)
+ eb.add(l)
+ self.stats_table.attach(eb, col, col+1, row+1, row+2, yoptions=gtk.SHRINK)
+ l.show()
+ eb.show()
+ self.fdb.db.commit()
+ #end def fillStatsFrame(self, vbox):
+
+ def fillPlayerFrame(self, vbox):
+ for site in self.conf.supported_sites.keys():
+ hbox = gtk.HBox(False, 0)
+ vbox.pack_start(hbox, False, True, 0)
+ hbox.show()
+
+ player = self.conf.supported_sites[site].screen_name
+ self.createPlayerLine(hbox, site, player)
+ hbox = gtk.HBox(False, 0)
+ button = gtk.Button("Refresh")
+ button.connect("clicked", self.refreshStats, False)
+ button.show()
+ hbox.add(button)
+ vbox.pack_start(hbox, False, True, 0)
+ hbox.show()
+
+ def fillCardsFrame(self, vbox):
+ hbox1 = gtk.HBox(True,0)
+ hbox1.show()
+ vbox.pack_start(hbox1, True, True, 0)
+
+ cards = [ "A", "K","Q","J","T","9","8","7","6","5","4","3","2" ]
+
+ for j in range(0, len(cards)):
+ hbox1 = gtk.HBox(True,0)
+ hbox1.show()
+ vbox.pack_start(hbox1, True, True, 0)
+ for i in range(0, len(cards)):
+ if i < (j + 1):
+ suit = "o"
+ else:
+ suit = "s"
+ button = gtk.ToggleButton("%s%s%s" %(cards[i], cards[j], suit))
+ button.connect("toggled", self.cardCallback, "%s%s%s" %(cards[i], cards[j], suit))
+ hbox1.pack_start(button, True, True, 0)
+ button.show()
+
+ def createPlayerLine(self, hbox, site, player):
+ if(self.buttongroup == None):
+ button = gtk.RadioButton(None, site + " id:")
+ button.set_active(True)
+ self.buttongroup = button
+ self.activesite = site
+ else:
+ button = gtk.RadioButton(self.buttongroup, site + " id:")
+ hbox.pack_start(button, True, True, 0)
+ button.connect("toggled", self.toggleCallback, site)
+ button.show()
+
+ pname = gtk.Entry()
+ pname.set_text(player)
+ pname.set_width_chars(20)
+ hbox.pack_start(pname, False, True, 0)
+ pname.connect("changed", self.__set_hero_name, site)
+ #TODO: Look at GtkCompletion - to fill out usernames
+ pname.show()
+ self.__set_hero_name(pname, site)
+
+ def __set_hero_name(self, w, site):
+ self.heroes[site] = w.get_text()
+
+ def __init__(self, db, config, querylist, debug=True):
+ self.debug=debug
+ self.conf=config
+
+ # create new db connection to avoid conflicts with other threads
+ self.fdb = fpdb_db.fpdb_db()
+ self.fdb.do_connect(self.conf)
+ self.cursor=self.fdb.cursor
+
+ self.sql = querylist
+
+ self.activesite = None
+ self.buttongroup = None
+
+ self.heroes = {}
+ self.stat_table = None
+ self.stats_frame = None
+
+ self.main_hbox = gtk.HBox(False, 0)
+ self.main_hbox.show()
+
+ playerFrame = gtk.Frame("Hero:")
+ playerFrame.set_label_align(0.0, 0.0)
+ playerFrame.show()
+ vbox = gtk.VBox(False, 0)
+ vbox.show()
+
+ self.fillPlayerFrame(vbox)
+ playerFrame.add(vbox)
+
+ cardsFrame = gtk.Frame("Cards:")
+ cardsFrame.set_label_align(0.0, 0.0)
+ cardsFrame.show()
+ vbox = gtk.VBox(False, 0)
+ vbox.show()
+
+ self.fillCardsFrame(vbox)
+ cardsFrame.add(vbox)
+
+ statsFrame = gtk.Frame("Stats:")
+ statsFrame.set_label_align(0.0, 0.0)
+ statsFrame.show()
+ self.stats_frame = gtk.VBox(False, 0)
+ self.stats_frame.show()
+
+ self.fillStatsFrame(self.stats_frame)
+ statsFrame.add(self.stats_frame)
+
+ self.main_hbox.pack_start(playerFrame)
+ self.main_hbox.pack_start(statsFrame)
+
diff --git a/pyfpdb/HUD_config.xml.example b/pyfpdb/HUD_config.xml.example
index 5e4e6f3d..e21f342a 100644
--- a/pyfpdb/HUD_config.xml.example
+++ b/pyfpdb/HUD_config.xml.example
@@ -1,19 +1,25 @@
+
+
+
-
+
+
@@ -60,18 +66,21 @@
-
+
+
@@ -106,46 +115,55 @@
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
@@ -153,6 +171,7 @@
+
@@ -161,7 +180,8 @@
-
+
+
@@ -169,7 +189,8 @@
-
+
+
@@ -177,6 +198,7 @@
+
@@ -185,6 +207,7 @@
+
@@ -194,6 +217,7 @@
+
@@ -220,15 +244,54 @@
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/pyfpdb/HUD_main.py b/pyfpdb/HUD_main.py
index 2e89492d..4501821a 100755
--- a/pyfpdb/HUD_main.py
+++ b/pyfpdb/HUD_main.py
@@ -4,7 +4,7 @@
Main for FreePokerTools HUD.
"""
-# Copyright 2008, Ray E. Barker
+# Copyright 2008, 2009, Ray E. Barker
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -26,10 +26,14 @@ Main for FreePokerTools HUD.
# to do hud to echo, but ignore non numbers
# to do no stat window for hero
# to do things to add to config.xml
-# to do font and size
# Standard Library modules
import sys
+
+# redirect the stderr
+errorfile = open('HUD-error.txt', 'w', 0)
+sys.stderr = errorfile
+
import os
import thread
import time
@@ -47,143 +51,163 @@ import Database
import Tables
import Hud
-# global dict for keeping the huds
-hud_dict = {}
-eb = 0 # our former event-box
+aggregate_stats = {"ring": False, "tour": False} # config file!
-db_connection = 0;
-config = 0;
+class HUD_main(object):
+ """A main() object to own both the read_stdin thread and the gui."""
+# This class mainly provides state for controlling the multiple HUDs.
-def destroy(*args): # call back for terminating the main eventloop
- gtk.main_quit()
+ def __init__(self, db_name = 'fpdb'):
+ self.db_name = db_name
+ self.config = Configuration.Config()
+ self.hud_dict = {}
-def create_HUD(new_hand_id, table, db_name, table_name, max, poker_game, db_connection, config, stat_dict):
- global hud_dict, eb
-
- def idle_func():
- global hud_dict, eb
+# a thread to read stdin
+ gobject.threads_init() # this is required
+ thread.start_new_thread(self.read_stdin, ()) # starts the thread
+
+# a main window
+ self.main_window = gtk.Window()
+ self.main_window.connect("destroy", self.destroy)
+ self.vb = gtk.VBox()
+ self.label = gtk.Label('Closing this window will exit from the HUD.')
+ self.vb.add(self.label)
+ self.main_window.add(self.vb)
+ self.main_window.set_title("HUD Main Window")
+ self.main_window.show_all()
+
+ def destroy(*args): # call back for terminating the main eventloop
+ gtk.main_quit()
+
+ def kill_hud(self, event, table):
+# called by an event in the HUD, to kill this specific HUD
+ self.hud_dict[table].kill()
+ self.hud_dict[table].main_window.destroy()
+ self.vb.remove(self.hud_dict[table].tablehudlabel)
+ del(self.hud_dict[table])
+ self.main_window.resize(1,1)
+
+ def create_HUD(self, new_hand_id, table, table_name, max, poker_game, stat_dict, cards):
- gtk.gdk.threads_enter()
- try:
- newlabel = gtk.Label(table_name)
- eb.add(newlabel)
- newlabel.show()
-
- hud_dict[table_name] = Hud.Hud(table, max, poker_game, config, db_connection)
- hud_dict[table_name].tablehudlabel = newlabel
- hud_dict[table_name].create(new_hand_id, config)
- for m in hud_dict[table_name].aux_windows:
- m.update_data(new_hand_id, db_connection)
- m.update_gui(new_hand_id)
- hud_dict[table_name].update(new_hand_id, config, stat_dict)
- hud_dict[table_name].reposition_windows()
- return False
- finally:
- gtk.gdk.threads_leave()
- gobject.idle_add(idle_func)
-
-def update_HUD(new_hand_id, table_name, config, stat_dict):
- global hud_dict
- def idle_func():
- gtk.gdk.threads_enter()
- try:
- hud_dict[table_name].update(new_hand_id, config, stat_dict)
- for m in hud_dict[table_name].aux_windows:
- m.update_gui(new_hand_id)
- return False
- finally:
- gtk.gdk.threads_leave()
- gobject.idle_add(idle_func)
-
-def HUD_removed(tablename):
- global hud_dict, eb
-
- if tablename in hud_dict and hud_dict[tablename].deleted:
- eb.remove(hud_dict[tablename].tablehudlabel)
- del(hud_dict[tablename])
- return False
-
- return True
-
-def read_stdin(): # This is the thread function
- global hud_dict, eb
-
- db_connection = Database.Database(config, db_name, 'temp')
- tourny_finder = re.compile('(\d+) (\d+)')
-
- while True: # wait for a new hand number on stdin
- new_hand_id = sys.stdin.readline()
- new_hand_id = string.rstrip(new_hand_id)
- if new_hand_id == "": # blank line means quit
- destroy()
- break # this thread is not always killed immediately with gtk.main_quit()
-
-# delete hud_dict entries for any HUD destroyed since last iteration
-# for h in hud_dict:
-# HUD_removed(h)
-# removing this function, we shouldn't need it anymore, since the hud should notify us anyway, right?
-
-# get basic info about the new hand from the db
- (table_name, max, poker_game) = db_connection.get_table_name(new_hand_id)
-
-# find out if this hand is from a tournament
- is_tournament = False
- (tour_number, tab_number) = (0, 0)
- mat_obj = tourny_finder.search(table_name)
- if mat_obj:
- is_tournament = True
- (tour_number, tab_number) = mat_obj.group(1, 2)
+ def idle_func():
- stat_dict = db_connection.get_stats_from_hand(new_hand_id)
+ gtk.gdk.threads_enter()
+ try:
+ newlabel = gtk.Label("%s - %s" % (table.site, table_name))
+ self.vb.add(newlabel)
+ newlabel.show()
+ self.main_window.resize_children()
+
+ self.hud_dict[table_name].tablehudlabel = newlabel
+ self.hud_dict[table_name].create(new_hand_id, self.config, stat_dict, cards)
+ for m in self.hud_dict[table_name].aux_windows:
+ m.create()
+ m.update_gui(new_hand_id)
+ self.hud_dict[table_name].update(new_hand_id, self.config)
+ self.hud_dict[table_name].reposition_windows()
+ return False
+ finally:
+ gtk.gdk.threads_leave()
-# if a hud for this CASH table exists, just update it
- if table_name in hud_dict:
-# update the data for the aux_windows
- for aw in hud_dict[table_name].aux_windows:
- aw.update_data(new_hand_id, db_connection)
- update_HUD(new_hand_id, table_name, config, stat_dict)
+ self.hud_dict[table_name] = Hud.Hud(self, table, max, poker_game, self.config, self.db_connection)
+ self.hud_dict[table_name].table_name = table_name
+ self.hud_dict[table_name].stat_dict = stat_dict
+ self.hud_dict[table_name].cards = cards
+ [aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[table_name].aux_windows]
+ gobject.idle_add(idle_func)
+
+ def update_HUD(self, new_hand_id, table_name, config):
+ """Update a HUD gui from inside the non-gui read_stdin thread."""
+# This is written so that only 1 thread can touch the gui--mainly
+# for compatibility with Windows. This method dispatches the
+# function idle_func() to be run by the gui thread, at its leisure.
+ def idle_func():
+ gtk.gdk.threads_enter()
+ try:
+ self.hud_dict[table_name].update(new_hand_id, config)
+ [aw.update_gui(new_hand_id) for aw in self.hud_dict[table_name].aux_windows]
+ return False
+ finally:
+ gtk.gdk.threads_leave()
+ gobject.idle_add(idle_func)
+
+ def read_stdin(self): # This is the thread function
+ """Do all the non-gui heavy lifting for the HUD program."""
-# if a hud for this TOURNAMENT table exists, just update it
- elif tour_number in hud_dict:
- update_HUD(new_hand_id, tour_number, config, stat_dict)
+# This db connection is for the read_stdin thread only. It should not
+# be passed to HUDs for use in the gui thread. HUD objects should not
+# need their own access to the database, but should open their own
+# if it is required.
+ self.db_connection = Database.Database(self.config, self.db_name, 'temp')
+ tourny_finder = re.compile('(\d+) (\d+)')
+
+ while 1: # wait for a new hand number on stdin
+ new_hand_id = sys.stdin.readline()
+ new_hand_id = string.rstrip(new_hand_id)
+ if new_hand_id == "": # blank line means quit
+ self.destroy()
+ break # this thread is not always killed immediately with gtk.main_quit()
+
+# get basic info about the new hand from the db
+# if there is a db error, complain, skip hand, and proceed
+ try:
+ (table_name, max, poker_game, type) = self.db_connection.get_table_name(new_hand_id)
+ stat_dict = self.db_connection.get_stats_from_hand(new_hand_id, aggregate = aggregate_stats[type])
+ cards = self.db_connection.get_cards(new_hand_id)
+ comm_cards = self.db_connection.get_common_cards(new_hand_id)
+ if comm_cards != {}: # stud!
+ cards['common'] = comm_cards['common']
+ except Exception, err:
+ print "db error: skipping ", new_hand_id, err
+ sys.stderr.write("Database error %s in hand %d. Skipping.\n" % (err, int(new_hand_id)))
+ continue
-# otherwise create a new hud
- else:
- if is_tournament:
- tablewindow = Tables.discover_tournament_table(config, tour_number, tab_number)
- if tablewindow == None:
- sys.stderr.write("tournament %s, table %s not found\n" % (tour_number, tab_number))
- else:
- create_HUD(new_hand_id, tablewindow, db_name, tour_number, max, poker_game, db_connection, config, stat_dict)
+ if type == "tour": # hand is from a tournament
+ mat_obj = tourny_finder.search(table_name)
+ if mat_obj:
+ (tour_number, tab_number) = mat_obj.group(1, 2)
+ temp_key = tour_number
+ else: # tourney, but can't get number and table
+ print "could not find tournamtne: skipping "
+ sys.stderr.write("Could not find tournament %d in hand %d. Skipping.\n" % (int(tour_number), int(new_hand_id)))
+ continue
+
else:
- tablewindow = Tables.discover_table_by_name(config, table_name)
- if tablewindow == None:
- sys.stderr.write("table name "+table_name+" not found\n")
+ temp_key = table_name
+
+# Update an existing HUD
+ if temp_key in self.hud_dict:
+ self.hud_dict[temp_key].stat_dict = stat_dict
+ self.hud_dict[temp_key].cards = cards
+ [aw.update_data(new_hand_id, self.db_connection) for aw in self.hud_dict[temp_key].aux_windows]
+ self.update_HUD(new_hand_id, temp_key, self.config)
+
+# Or create a new HUD
+ else:
+ if type == "tour":
+ tablewindow = Tables.discover_tournament_table(self.config, tour_number, tab_number)
else:
- create_HUD(new_hand_id, tablewindow, db_name, table_name, max, poker_game, db_connection, config, stat_dict)
+ tablewindow = Tables.discover_table_by_name(self.config, table_name)
+ if tablewindow == None:
+# If no client window is found on the screen, complain and continue
+ if type == "tour":
+ table_name = "%s %s" % (tour_number, tab_number)
+ sys.stderr.write("table name "+table_name+" not found, skipping.\n")
+ else:
+ self.create_HUD(new_hand_id, tablewindow, temp_key, max, poker_game, stat_dict, cards)
if __name__== "__main__":
sys.stderr.write("HUD_main starting\n")
+# database name can be passed on command line
try:
db_name = sys.argv[1]
except:
db_name = 'fpdb'
sys.stderr.write("Using db name = %s\n" % (db_name))
- config = Configuration.Config()
+# start the HUD_main object
+ hm = HUD_main(db_name = db_name)
- gobject.threads_init() # this is required
- thread.start_new_thread(read_stdin, ()) # starts the thread
-
- main_window = gtk.Window()
- main_window.connect("destroy", destroy)
- eb = gtk.VBox()
- label = gtk.Label('Closing this window will exit from the HUD.')
- eb.add(label)
- main_window.add(eb)
-
- main_window.set_title("HUD Main Window")
- main_window.show_all()
-
+# start the event loop
gtk.main()
diff --git a/pyfpdb/HUD_run_me.py b/pyfpdb/HUD_run_me.py
old mode 100644
new mode 100755
diff --git a/pyfpdb/Hand.py b/pyfpdb/Hand.py
index 24ccbe3f..17eefe12 100644
--- a/pyfpdb/Hand.py
+++ b/pyfpdb/Hand.py
@@ -15,35 +15,29 @@
#In the "official" distribution you can find the license in
#agpl-3.0.txt in the docs folder of the package.
-import Configuration
-import FpdbRegex
-import Hand
import re
import sys
import traceback
+import logging
import os
import os.path
-import xml.dom.minidom
-import codecs
from decimal import Decimal
import operator
import time
from copy import deepcopy
+from Exceptions import *
+
+import DerivedStats
class Hand:
-# def __init__(self, sitename, gametype, sb, bb, string):
-
UPS = {'a':'A', 't':'T', 'j':'J', 'q':'Q', 'k':'K', 'S':'s', 'C':'c', 'H':'h', 'D':'d'}
- def __init__(self, sitename, gametype, string):
+ LCS = {'H':'h', 'D':'d', 'C':'c', 'S':'s'}
+ def __init__(self, sitename, gametype, handText, builtFrom = "HHC"):
self.sitename = sitename
+ self.stats = DerivedStats.DerivedStats(self)
self.gametype = gametype
- self.string = string
-
- self.streetList = ['PREFLOP','FLOP','TURN','RIVER'] # a list of the observed street names in order
-
+ self.handText = handText
self.handid = 0
- self.sb = gametype[3]
- self.bb = gametype[4]
self.tablename = "Slartibartfast"
self.hero = "Hiro"
self.maxseats = 10
@@ -54,52 +48,58 @@ class Hand:
self.posted = []
self.involved = True
- self.pot = Pot()
-
- #
# Collections indexed by street names
- #
-
- # A MatchObject using a groupnames to identify streets.
- # filled by markStreets()
- self.streets = None
-
- # dict from street names to lists of tuples, such as
- # [['mct','bets','$10'],['mika','folds'],['carlg','raises','$20']]
- # actually they're clearly lists but they probably should be tuples.
- self.actions = {}
-
- # dict from street names to community cards
- self.board = {}
-
-
- #
- # Collections indexed by player names
- #
-
- # dict from player names to lists of hole cards
- self.holecards = {}
+ self.bets = {}
+ self.lastBet = {}
+ self.streets = {}
+ self.actions = {} # [['mct','bets','$10'],['mika','folds'],['carlg','raises','$20']]
+ self.board = {} # dict from street names to community cards
+ for street in self.streetList:
+ self.streets[street] = "" # portions of the handText, filled by markStreets()
+ self.bets[street] = {}
+ self.lastBet[street] = 0
+ self.actions[street] = []
+ self.board[street] = []
+ # Collections indexed by player names
+ self.holecards = {} # dict from player names to dicts by street ... of tuples ... of holecards
+ self.discards = {} # dict from player names to dicts by street ... of tuples ... of discarded holecards
self.stacks = {}
-
- # dict from player names to amounts collected
- self.collected = {}
+ self.collected = [] #list of ?
+ self.collectees = {} # dict from player names to amounts collected (?)
# Sets of players
self.shown = set()
self.folded = set()
- self.action = []
+# self.action = []
+ # Things to do with money
+ self.pot = Pot()
self.totalpot = None
self.totalcollected = None
-
self.rake = None
- self.bets = {}
- self.lastBet = {}
- for street in self.streetList:
- self.bets[street] = {}
- self.lastBet[street] = 0
+
+ def insert(self, db):
+ """ Function to insert Hand into database
+Should not commit, and do minimal selects. Callers may want to cache commits
+db: a connected fpdb_db object"""
+ # TODO:
+ # Players - base playerid and siteid tuple
+ # HudCache data to come from DerivedStats class
+ # HandsActions - all actions for all players for all streets - self.actions
+ # BoardCards - ?
+ # Hands - Summary information of hand indexed by handId - gameinfo
+ # HandsPlayers - ? ... Do we fix winnings?
+ # Tourneys ?
+ # TourneysPlayers
+
+ pass
+
+ def select(self, handId):
+ """ Function to create Hand object from database """
+ pass
+
def addPlayer(self, seat, name, chips):
"""\
@@ -108,70 +108,36 @@ seat (int) indicating the seat
name (string) player name
chips (string) the chips the player has at the start of the hand (can be None)
If a player has None chips he won't be added."""
+ logging.debug("addPlayer: %s %s (%s)" % (seat, name, chips))
if chips is not None:
self.players.append([seat, name, chips])
self.stacks[name] = Decimal(chips)
- self.holecards[name] = set()
+ self.holecards[name] = []
+ self.discards[name] = []
self.pot.addPlayer(name)
for street in self.streetList:
self.bets[street][name] = []
+ self.holecards[name] = {} # dict from street names.
+ self.discards[name] = {} # dict from street names.
def addStreets(self, match):
# go through m and initialise actions to empty list for each street.
- if match is not None:
- self.streets = match
- for street in match.groupdict():
- if match.group(street) is not None:
- self.actions[street] = []
-
+ if match:
+ self.streets.update(match.groupdict())
+ logging.debug("markStreets:\n"+ str(self.streets))
else:
- print "empty markStreets match" # better to raise exception and put process hand in a try block
-
- def addHoleCards(self, cards, player):
- """\
-Assigns observed holecards to a player.
-cards set of card bigrams e.g. set(['2h','Jc'])
-player (string) name of player
-"""
- print "DEBUG: addHoleCards", cards,player
- try:
- self.checkPlayerExists(player)
- cards = set([self.card(c) for c in cards])
- self.holecards[player].update(cards)
- except FpdbParseError, e:
- print "[ERROR] Tried to add holecards for unknown player: %s" % (player,)
-
- def addShownCards(self, cards, player, holeandboard=None):
- """\
-For when a player shows cards for any reason (for showdown or out of choice).
-Card ranks will be uppercased
-"""
- print "DEBUG: addShownCards", cards,player,holeandboard
- if cards is not None:
- self.shown.add(player)
- self.addHoleCards(cards,player)
- elif holeandboard is not None:
- holeandboard = set([self.card(c) for c in holeandboard])
- board = set([c for s in self.board.values() for c in s])
- self.addHoleCards(holeandboard.difference(board),player)
-
+ logging.error("markstreets didn't match")
def checkPlayerExists(self,player):
if player not in [p[1] for p in self.players]:
+ print "checkPlayerExists", player, "fail"
raise FpdbParseError
- def discardHoleCards(self, cards, player):
- try:
- self.checkPlayerExists(player)
- for card in cards:
- self.holecards[player].remove(card)
- except FpdbParseError, e:
- pass
- except ValueError:
- print "[ERROR] discardHoleCard tried to discard a card %s didn't have" % (player,)
+
def setCommunityCards(self, street, cards):
+ logging.debug("setCommunityCards %s %s" %(street, cards))
self.board[street] = [self.card(c) for c in cards]
def card(self,c):
@@ -180,42 +146,52 @@ Card ranks will be uppercased
c = c.replace(k,v)
return c
+ def addAnte(self, player, ante):
+ logging.debug("%s %s antes %s" % ('ANTES', player, ante))
+ if player is not None:
+ self.bets['ANTES'][player].append(Decimal(ante))
+ self.stacks[player] -= Decimal(ante)
+ act = (player, 'posts', "ante", ante, self.stacks[player]==0)
+ self.actions['ANTES'].append(act)
+ #~ self.lastBet['ANTES'] = Decimal(ante)
+ self.pot.addMoney(player, Decimal(ante))
+
def addBlind(self, player, blindtype, amount):
# if player is None, it's a missing small blind.
- # TODO:
# The situation we need to cover are:
# Player in small blind posts
# - this is a bet of 1 sb, as yet uncalled.
# Player in the big blind posts
- # - this is a bet of 1 bb and is the new uncalled
- #
- # If a player posts a big & small blind
+ # - this is a call of 1 sb and a raise to 1 bb
#
-
- print "DEBUG addBlind: %s posts %s, %s" % (player, blindtype, amount)
+
+ logging.debug("addBlind: %s posts %s, %s" % (player, blindtype, amount))
if player is not None:
self.bets['PREFLOP'][player].append(Decimal(amount))
self.stacks[player] -= Decimal(amount)
#print "DEBUG %s posts, stack %s" % (player, self.stacks[player])
act = (player, 'posts', blindtype, amount, self.stacks[player]==0)
- self.actions['PREFLOP'].append(act)
+ self.actions['BLINDSANTES'].append(act)
self.pot.addMoney(player, Decimal(amount))
if blindtype == 'big blind':
- self.lastBet['PREFLOP'] = Decimal(amount)
- elif blindtype == 'small & big blinds':
+ self.lastBet['PREFLOP'] = Decimal(amount)
+ elif blindtype == 'both':
# extra small blind is 'dead'
self.lastBet['PREFLOP'] = Decimal(self.bb)
- self.posted += [player]
+ self.posted = self.posted + [[player,blindtype]]
+ #print "DEBUG: self.posted: %s" %(self.posted)
+
def addCall(self, street, player=None, amount=None):
+ logging.debug("%s %s calls %s" %(street, player, amount))
# Potentially calculate the amount of the call if not supplied
# corner cases include if player would be all in
if amount is not None:
self.bets[street][player].append(Decimal(amount))
#self.lastBet[street] = Decimal(amount)
self.stacks[player] -= Decimal(amount)
- print "DEBUG %s calls %s, stack %s" % (player, amount, self.stacks[player])
+ #print "DEBUG %s calls %s, stack %s" % (player, amount, self.stacks[player])
act = (player, 'calls', amount, self.stacks[player]==0)
self.actions[street].append(act)
self.pot.addMoney(player, Decimal(amount))
@@ -242,10 +218,11 @@ Add a raise by amountBy on [street] by [player]
C = Bp - Bc
Rt = Bp + Rb
- self.bets[street][player].append(C + Rb)
- self.stacks[player] -= (C + Rb)
- self.actions[street] += [(player, 'raises', Rb, Rt, C, self.stacks[player]==0)]
- self.lastBet[street] = Rt
+ self._addRaise(street, player, C, Rb, Rt)
+ #~ self.bets[street][player].append(C + Rb)
+ #~ self.stacks[player] -= (C + Rb)
+ #~ self.actions[street] += [(player, 'raises', Rb, Rt, C, self.stacks[player]==0)]
+ #~ self.lastBet[street] = Rt
def addCallandRaise(self, street, player, amount):
"""\
@@ -264,7 +241,9 @@ For sites which by "raises x" mean "calls and raises putting a total of x in the
"""\
Add a raise on [street] by [player] to [amountTo]
"""
+ #CG - No idea if this function has been test/verified
self.checkPlayerExists(player)
+ Bp = self.lastBet[street]
Bc = reduce(operator.add, self.bets[street][player], 0)
Rt = Decimal(amountTo)
C = Bp - Bc
@@ -272,6 +251,7 @@ Add a raise on [street] by [player] to [amountTo]
self._addRaise(street, player, C, Rb, Rt)
def _addRaise(self, street, player, C, Rb, Rt):
+ logging.debug("%s %s raise %s" %(street, player, Rt))
self.bets[street][player].append(C + Rb)
self.stacks[player] -= (C + Rb)
act = (player, 'raises', Rb, Rt, C, self.stacks[player]==0)
@@ -282,18 +262,25 @@ Add a raise on [street] by [player] to [amountTo]
def addBet(self, street, player, amount):
+ logging.debug("%s %s bets %s" %(street, player, amount))
self.checkPlayerExists(player)
self.bets[street][player].append(Decimal(amount))
self.stacks[player] -= Decimal(amount)
- print "DEBUG %s bets %s, stack %s" % (player, amount, self.stacks[player])
+ #print "DEBUG %s bets %s, stack %s" % (player, amount, self.stacks[player])
act = (player, 'bets', amount, self.stacks[player]==0)
self.actions[street].append(act)
self.lastBet[street] = Decimal(amount)
self.pot.addMoney(player, Decimal(amount))
+
+
+ def addStandsPat(self, street, player):
+ self.checkPlayerExists(player)
+ act = (player, 'stands pat')
+ self.actions[street].append(act)
def addFold(self, street, player):
- print "DEBUG: %s %s folded" % (street, player)
+ logging.debug("%s %s folds" % (street, player))
self.checkPlayerExists(player)
self.folded.add(player)
self.pot.addFold(player)
@@ -301,17 +288,19 @@ Add a raise on [street] by [player] to [amountTo]
def addCheck(self, street, player):
- print "DEBUG: %s %s checked" % (street, player)
+ #print "DEBUG: %s %s checked" % (street, player)
self.checkPlayerExists(player)
self.actions[street].append((player, 'checks'))
+
def addCollectPot(self,player, pot):
- print "DEBUG: %s collected %s" % (player, pot)
+ logging.debug("%s collected %s" % (player, pot))
self.checkPlayerExists(player)
- if player not in self.collected:
- self.collected[player] = pot
+ self.collected = self.collected + [[player, pot]]
+ if player not in self.collectees:
+ self.collectees[player] = Decimal(pot)
else:
- print "[WARNING] %s collected pot more than once; avoidable by reading winnings only from summary lines?"
+ self.collectees[player] += Decimal(pot)
def totalPot(self):
@@ -325,8 +314,9 @@ Add a raise on [street] by [player] to [amountTo]
# This gives us the amount collected, i.e. after rake
if self.totalcollected is None:
self.totalcollected = 0;
- for amount in self.collected.values():
- self.totalcollected += Decimal(amount)
+ #self.collected looks like [[p1,amount][px,amount]]
+ for entry in self.collected:
+ self.totalcollected += Decimal(entry[1])
@@ -336,16 +326,16 @@ Add a raise on [street] by [player] to [amountTo]
Map the tuple self.gametype onto the pokerstars string describing it
"""
# currently it appears to be something like ["ring", "hold", "nl", sb, bb]:
- gs = {"hold" : "Hold'em",
- "omahahi" : "FIXME",
- "omahahilo" : "FIXME",
+ gs = {"holdem" : "Hold'em",
+ "omahahi" : "Omaha",
+ "omahahilo" : "Omaha Hi/Lo",
"razz" : "Razz",
- "studhi" : "FIXME",
+ "studhi" : "7 Card Stud",
"studhilo" : "FIXME",
"fivedraw" : "5 Card Draw",
"27_1draw" : "FIXME",
"27_3draw" : "Triple Draw 2-7 Lowball",
- "badugi" : "FIXME"
+ "badugi" : "Badugi"
}
ls = {"nl" : "No Limit",
"pl" : "Pot Limit",
@@ -354,55 +344,156 @@ Map the tuple self.gametype onto the pokerstars string describing it
"cp" : "Cap Pot Limit"
}
- string = "%s %s" %(gs[self.gametype[1]], ls[self.gametype[2]])
+ logging.debug("gametype: %s" %(self.gametype))
+ retstring = "%s %s" %(gs[self.gametype['category']], ls[self.gametype['limitType']])
+
+ return retstring
+
+
+ def writeHand(self, fh=sys.__stdout__):
+ print >>fh, "Override me"
+
+ def printHand(self):
+ self.writeHand(sys.stdout)
+
+ def printActionLine(self, act, fh):
+ if act[1] == 'folds':
+ print >>fh, _("%s: folds " %(act[0]))
+ elif act[1] == 'checks':
+ print >>fh, _("%s: checks " %(act[0]))
+ elif act[1] == 'calls':
+ print >>fh, _("%s: calls $%s%s" %(act[0], act[2], ' and is all-in' if act[3] else ''))
+ elif act[1] == 'bets':
+ print >>fh, _("%s: bets $%s%s" %(act[0], act[2], ' and is all-in' if act[3] else ''))
+ elif act[1] == 'raises':
+ print >>fh, _("%s: raises $%s to $%s%s" %(act[0], act[2], act[3], ' and is all-in' if act[5] else ''))
+ elif act[1] == 'completea':
+ print >>fh, _("%s: completes to $%s%s" %(act[0], act[2], ' and is all-in' if act[3] else ''))
+ elif act[1] == 'posts':
+ if(act[2] == "small blind"):
+ print >>fh, _("%s: posts small blind $%s%s" %(act[0], act[3], ' and is all-in' if act[4] else ''))
+ elif(act[2] == "big blind"):
+ print >>fh, _("%s: posts big blind $%s%s" %(act[0], act[3], ' and is all-in' if act[4] else ''))
+ elif(act[2] == "both"):
+ print >>fh, _("%s: posts small & big blinds $%s%s" %(act[0], act[3], ' and is all-in' if act[4] else ''))
+ elif act[1] == 'bringin':
+ print >>fh, _("%s: brings in for $%s%s" %(act[0], act[2], ' and is all-in' if act[3] else ''))
+ elif act[1] == 'discards':
+ print >>fh, _("%s: discards %s %s%s" %(act[0], act[2], 'card' if act[2] == 1 else 'cards' , " [" + " ".join(self.discards[act[0]]['DRAWONE']) + "]" if self.hero == act[0] else ''))
+ elif act[1] == 'stands pat':
+ print >>fh, _("%s: stands pat" %(act[0]))
+
+
+class HoldemOmahaHand(Hand):
+ def __init__(self, hhc, sitename, gametype, handText, builtFrom = "HHC"):
+ if gametype['base'] != 'hold':
+ pass # or indeed don't pass and complain instead
+ logging.debug("HoldemOmahaHand")
+ self.streetList = ['BLINDSANTES', 'DEAL', 'PREFLOP','FLOP','TURN','RIVER'] # a list of the observed street names in order
+ self.communityStreets = ['FLOP', 'TURN', 'RIVER']
+ self.actionStreets = ['PREFLOP','FLOP','TURN','RIVER']
+ Hand.__init__(self, sitename, gametype, handText, builtFrom = "HHC")
+ self.sb = gametype['sb']
+ self.bb = gametype['bb']
- return string
+ #Populate a HoldemOmahaHand
+ #Generally, we call 'read' methods here, which get the info according to the particular filter (hhc)
+ # which then invokes a 'addXXX' callback
+ if builtFrom == "HHC":
+ hhc.readHandInfo(self)
+ hhc.readPlayerStacks(self)
+ hhc.compilePlayerRegexs(self)
+ hhc.markStreets(self)
+ hhc.readBlinds(self)
+ hhc.readButton(self)
+ hhc.readHeroCards(self)
+ hhc.readShowdownActions(self)
+ # Read actions in street order
+ for street in self.communityStreets:
+ if self.streets[street]:
+ hhc.readCommunityCards(self, street)
+ for street in self.actionStreets:
+ if self.streets[street]:
+ hhc.readAction(self, street)
+ hhc.readCollectPot(self)
+ hhc.readShownCards(self)
+ self.totalPot() # finalise it (total the pot)
+ hhc.getRake(self)
+ elif builtFrom == "DB":
+ self.select("dummy") # Will need a handId
+
+ def addHoleCards(self, cards, player, shown=False):
+ """\
+Assigns observed holecards to a player.
+cards list of card bigrams e.g. ['2h','Jc']
+player (string) name of player
+"""
+ logging.debug("addHoleCards %s %s" % (cards, player))
+ try:
+ self.checkPlayerExists(player)
+ cardset = set(self.card(c) for c in cards)
+ if shown and len(cardset) > 0:
+ self.shown.add(player)
+ if 'PREFLOP' in self.holecards[player]:
+ self.holecards[player]['PREFLOP'].update(cardset)
+ else:
+ self.holecards[player]['PREFLOP'] = cardset
+ except FpdbParseError, e:
+ print "[ERROR] Tried to add holecards for unknown player: %s" % (player,)
+
+ def addShownCards(self, cards, player, holeandboard=None):
+ """\
+For when a player shows cards for any reason (for showdown or out of choice).
+Card ranks will be uppercased
+"""
+ logging.debug("addShownCards %s hole=%s all=%s" % (player, cards, holeandboard))
+ if cards is not None:
+ self.shown.add(player)
+ self.addHoleCards(cards,player)
+ elif holeandboard is not None:
+ holeandboard = set([self.card(c) for c in holeandboard])
+ board = set([c for s in self.board.values() for c in s])
+ self.addHoleCards(holeandboard.difference(board),player,shown=True)
+
def writeHand(self, fh=sys.__stdout__):
# PokerStars format.
- #print "\n### Pseudo stars format ###"
- #print >>fh, _("%s Game #%s: %s ($%s/$%s) - %s" %(self.sitename, self.handid, self.getGameTypeAsString(), self.sb, self.bb, self.starttime))
- print >>fh, _("%s Game #%s: %s ($%s/$%s) - %s" %("PokerStars", self.handid, self.getGameTypeAsString(), self.sb, self.bb, time.strftime('%Y/%m/%d - %H:%M:%S (ET)', self.starttime)))
+ print >>fh, _("%s Game #%s: %s ($%s/$%s) - %s" %("PokerStars", self.handid, self.getGameTypeAsString(), self.sb, self.bb, time.strftime('%Y/%m/%d - %H:%M:%S ET', self.starttime)))
print >>fh, _("Table '%s' %d-max Seat #%s is the button" %(self.tablename, self.maxseats, self.buttonpos))
- players_who_act_preflop = set([x[0] for x in self.actions['PREFLOP']])
-
+ players_who_act_preflop = set(([x[0] for x in self.actions['PREFLOP']]+[x[0] for x in self.actions['BLINDSANTES']]))
+ logging.debug(self.actions['PREFLOP'])
for player in [x for x in self.players if x[1] in players_who_act_preflop]:
#Only print stacks of players who do something preflop
- print >>fh, _("Seat %s: %s ($%s)" %(player[0], player[1], player[2]))
-
- if(self.posted[0] is None):
- #print >>fh, _("No small blind posted") # PS doesn't say this
- pass
- else:
- print >>fh, _("%s: posts small blind $%s" %(self.posted[0], self.sb))
-
- #May be more than 1 bb posting
- for a in self.posted[1:]:
- print >>fh, _("%s: posts big blind $%s" %(self.posted[1], self.bb))
-
- # TODO: What about big & small blinds?
+ print >>fh, _("Seat %s: %s ($%s in chips) " %(player[0], player[1], player[2]))
+ if self.actions['BLINDSANTES']:
+ for act in self.actions['BLINDSANTES']:
+ self.printActionLine(act, fh)
+
print >>fh, _("*** HOLE CARDS ***")
if self.involved:
- print >>fh, _("Dealt to %s [%s]" %(self.hero , " ".join(self.holecards[self.hero])))
+ print >>fh, _("Dealt to %s [%s]" %(self.hero , " ".join(self.holecards[self.hero]['PREFLOP'])))
- if 'PREFLOP' in self.actions:
+ if self.actions['PREFLOP']:
for act in self.actions['PREFLOP']:
self.printActionLine(act, fh)
- if 'FLOP' in self.actions:
+ if self.board['FLOP']:
print >>fh, _("*** FLOP *** [%s]" %( " ".join(self.board['FLOP'])))
+ if self.actions['FLOP']:
for act in self.actions['FLOP']:
self.printActionLine(act, fh)
- if 'TURN' in self.actions:
+ if self.board['TURN']:
print >>fh, _("*** TURN *** [%s] [%s]" %( " ".join(self.board['FLOP']), " ".join(self.board['TURN'])))
+ if self.actions['TURN']:
for act in self.actions['TURN']:
self.printActionLine(act, fh)
- if 'RIVER' in self.actions:
+ if self.board['RIVER']:
print >>fh, _("*** RIVER *** [%s] [%s]" %(" ".join(self.board['FLOP']+self.board['TURN']), " ".join(self.board['RIVER']) ))
+ if self.actions['RIVER']:
for act in self.actions['RIVER']:
self.printActionLine(act, fh)
@@ -410,9 +501,442 @@ Map the tuple self.gametype onto the pokerstars string describing it
#Some sites don't have a showdown section so we have to figure out if there should be one
# The logic for a showdown is: at the end of river action there are at least two players in the hand
# we probably don't need a showdown section in pseudo stars format for our filtering purposes
+ if self.shown:
+ print >>fh, _("*** SHOW DOWN ***")
+ for name in self.shown:
+ # TODO: legacy importer can't handle only one holecard here, make sure there are 2 for holdem, 4 for omaha
+ # TOOD: If HoldHand subclass supports more than omahahi, omahahilo, holdem, add them here
+ numOfHoleCardsNeeded = None
+ if self.gametype['category'] in ('omahahi','omahahilo'):
+ numOfHoleCardsNeeded = 4
+ elif self.gametype['category'] in ('holdem'):
+ numOfHoleCardsNeeded = 2
+ if len(self.holecards[name]['PREFLOP']) == numOfHoleCardsNeeded:
+ print >>fh, _("%s shows [%s] (a hand...)" % (name, " ".join(self.holecards[name]['PREFLOP'])))
+
+ # Current PS format has the lines:
+ # Uncalled bet ($111.25) returned to s0rrow
+ # s0rrow collected $5.15 from side pot
+ # stervels: shows [Ks Qs] (two pair, Kings and Queens)
+ # stervels collected $45.35 from main pot
+ # Immediately before the summary.
+ # The current importer uses those lines for importing winning rather than the summary
+ for name in self.pot.returned:
+ print >>fh, _("Uncalled bet ($%s) returned to %s" %(self.pot.returned[name],name))
+ for entry in self.collected:
+ print >>fh, _("%s collected $%s from x pot" %(entry[0], entry[1]))
+
+ print >>fh, _("*** SUMMARY ***")
+ print >>fh, "%s | Rake $%.2f" % (self.pot, self.rake)
+
+ board = []
+ for s in self.board.values():
+ board += s
+ if board: # sometimes hand ends preflop without a board
+ print >>fh, _("Board [%s]" % (" ".join(board)))
+
+ for player in [x for x in self.players if x[1] in players_who_act_preflop]:
+ seatnum = player[0]
+ name = player[1]
+ if name in self.collectees and name in self.shown:
+ print >>fh, _("Seat %d: %s showed [%s] and won ($%s)" % (seatnum, name, " ".join(self.holecards[name]['PREFLOP']), self.collectees[name]))
+ elif name in self.collectees:
+ print >>fh, _("Seat %d: %s collected ($%s)" % (seatnum, name, self.collectees[name]))
+ #~ elif name in self.shown:
+ #~ print >>fh, _("Seat %d: %s showed [%s]" % (seatnum, name, " ".join(self.holecards[name]['PREFLOP'])))
+ elif name in self.folded:
+ print >>fh, _("Seat %d: %s folded" % (seatnum, name))
+ else:
+ if name in self.shown:
+ print >>fh, _("Seat %d: %s showed [%s] and lost with..." % (seatnum, name, " ".join(self.holecards[name]['PREFLOP'])))
+ else:
+ print >>fh, _("Seat %d: %s mucked" % (seatnum, name))
+
+ print >>fh, "\n\n"
+
+class DrawHand(Hand):
+ def __init__(self, hhc, sitename, gametype, handText, builtFrom = "HHC"):
+ if gametype['base'] != 'draw':
+ pass # or indeed don't pass and complain instead
+ self.streetList = ['BLINDSANTES', 'DEAL', 'DRAWONE', 'DRAWTWO', 'DRAWTHREE']
+ self.holeStreets = ['DEAL', 'DRAWONE', 'DRAWTWO', 'DRAWTHREE']
+ self.actionStreets = ['PREDEAL', 'DEAL', 'DRAWONE', 'DRAWTWO', 'DRAWTHREE']
+ Hand.__init__(self, sitename, gametype, handText)
+ self.sb = gametype['sb']
+ self.bb = gametype['bb']
+ # Populate the draw hand.
+ if builtFrom == "HHC":
+ hhc.readHandInfo(self)
+ hhc.readPlayerStacks(self)
+ hhc.compilePlayerRegexs(self)
+ hhc.markStreets(self)
+ hhc.readBlinds(self)
+ hhc.readButton(self)
+ hhc.readShowdownActions(self)
+ # Read actions in street order
+ for street in self.streetList:
+ if self.streets[street]:
+ # hhc.readCommunityCards(self, street)
+ hhc.readDrawCards(self, street)
+ hhc.readAction(self, street)
+ hhc.readCollectPot(self)
+ hhc.readShownCards(self)
+ self.totalPot() # finalise it (total the pot)
+ hhc.getRake(self)
+ elif builtFrom == "DB":
+ self.select("dummy") # Will need a handId
+
+ # Draw games (at least Badugi has blinds - override default Holdem addBlind
+ def addBlind(self, player, blindtype, amount):
+ # if player is None, it's a missing small blind.
+ # The situation we need to cover are:
+ # Player in small blind posts
+ # - this is a bet of 1 sb, as yet uncalled.
+ # Player in the big blind posts
+ # - this is a call of 1 sb and a raise to 1 bb
+ #
+
+ logging.debug("addBlind: %s posts %s, %s" % (player, blindtype, amount))
+ if player is not None:
+ self.bets['DEAL'][player].append(Decimal(amount))
+ self.stacks[player] -= Decimal(amount)
+ #print "DEBUG %s posts, stack %s" % (player, self.stacks[player])
+ act = (player, 'posts', blindtype, amount, self.stacks[player]==0)
+ self.actions['BLINDSANTES'].append(act)
+ self.pot.addMoney(player, Decimal(amount))
+ if blindtype == 'big blind':
+ self.lastBet['DEAL'] = Decimal(amount)
+ elif blindtype == 'both':
+ # extra small blind is 'dead'
+ self.lastBet['DEAL'] = Decimal(self.bb)
+ self.posted = self.posted + [[player,blindtype]]
+ #print "DEBUG: self.posted: %s" %(self.posted)
+
+
+
+ def addDrawHoleCards(self, newcards, oldcards, player, street, shown=False):
+ """\
+Assigns observed holecards to a player.
+cards list of card bigrams e.g. ['2h','Jc']
+player (string) name of player
+"""
+ try:
+ self.checkPlayerExists(player)
+# if shown and len(cardset) > 0:
+# self.shown.add(player)
+ self.holecards[player][street] = (newcards,oldcards)
+ except FpdbParseError, e:
+ print "[ERROR] Tried to add holecards for unknown player: %s" % (player,)
+
+
+ def discardDrawHoleCards(self, cards, player, street):
+ logging.debug("discardDrawHoleCards '%s' '%s' '%s'" % (cards, player, street))
+ self.discards[player][street] = set([cards])
+
+
+ def addDiscard(self, street, player, num, cards):
+ self.checkPlayerExists(player)
+ if cards:
+ act = (player, 'discards', num, cards)
+ self.discardDrawHoleCards(cards, player, street)
+ else:
+ act = (player, 'discards', num)
+ self.actions[street].append(act)
+
+
+ def addShownCards(self, cards, player, holeandboard=None):
+ """\
+For when a player shows cards for any reason (for showdown or out of choice).
+Card ranks will be uppercased
+"""
+ logging.debug("addShownCards %s hole=%s all=%s" % (player, cards, holeandboard))
+# if cards is not None:
+# self.shown.add(player)
+# self.addHoleCards(cards,player)
+# elif holeandboard is not None:
+# holeandboard = set([self.card(c) for c in holeandboard])
+# board = set([c for s in self.board.values() for c in s])
+# self.addHoleCards(holeandboard.difference(board),player,shown=True)
+
+
+ def writeHand(self, fh=sys.__stdout__):
+ # PokerStars format.
+ print >>fh, _("%s Game #%s: %s ($%s/$%s) - %s" %("PokerStars", self.handid, self.getGameTypeAsString(), self.sb, self.bb, time.strftime('%Y/%m/%d %H:%M:%S ET', self.starttime)))
+ print >>fh, _("Table '%s' %d-max Seat #%s is the button" %(self.tablename, self.maxseats, self.buttonpos))
+
+ players_who_act_ondeal = set(([x[0] for x in self.actions['DEAL']]+[x[0] for x in self.actions['BLINDSANTES']]))
+
+ for player in [x for x in self.players if x[1] in players_who_act_ondeal]:
+ #Only print stacks of players who do something on deal
+ print >>fh, _("Seat %s: %s ($%s in chips) " %(player[0], player[1], player[2]))
+
+ if 'BLINDSANTES' in self.actions:
+ for act in self.actions['BLINDSANTES']:
+ print >>fh, _("%s: %s %s $%s" %(act[0], act[1], act[2], act[3]))
+
+ if 'DEAL' in self.actions:
+ print >>fh, _("*** DEALING HANDS ***")
+ for player in [x[1] for x in self.players if x[1] in players_who_act_ondeal]:
+ if 'DEAL' in self.holecards[player]:
+ (nc,oc) = self.holecards[player]['DEAL']
+ print >>fh, _("Dealt to %s: [%s]") % (player, " ".join(nc))
+ for act in self.actions['DEAL']:
+ self.printActionLine(act, fh)
+
+ if 'DRAWONE' in self.actions:
+ print >>fh, _("*** FIRST DRAW ***")
+ for act in self.actions['DRAWONE']:
+ self.printActionLine(act, fh)
+ if act[0] == self.hero and act[1] == 'discards':
+ (nc,oc) = self.holecards[act[0]]['DRAWONE']
+ dc = self.discards[act[0]]['DRAWONE']
+ kc = oc - dc
+ print >>fh, _("Dealt to %s [%s] [%s]" % (act[0], " ".join(kc), " ".join(nc)))
+
+ if 'DRAWTWO' in self.actions:
+ print >>fh, _("*** SECOND DRAW ***")
+ for act in self.actions['DRAWTWO']:
+ self.printActionLine(act, fh)
+ if act[0] == self.hero and act[1] == 'discards':
+ (nc,oc) = self.holecards[act[0]]['DRAWTWO']
+ dc = self.discards[act[0]]['DRAWTWO']
+ kc = oc - dc
+ print >>fh, _("Dealt to %s [%s] [%s]" % (act[0], " ".join(kc), " ".join(nc)))
+
+ if 'DRAWTHREE' in self.actions:
+ print >>fh, _("*** THIRD DRAW ***")
+ for act in self.actions['DRAWTHREE']:
+ self.printActionLine(act, fh)
+ if act[0] == self.hero and act[1] == 'discards':
+ (nc,oc) = self.holecards[act[0]]['DRAWTHREE']
+ dc = self.discards[act[0]]['DRAWTHREE']
+ kc = oc - dc
+ print >>fh, _("Dealt to %s [%s] [%s]" % (act[0], " ".join(kc), " ".join(nc)))
+
if 'SHOWDOWN' in self.actions:
print >>fh, _("*** SHOW DOWN ***")
- print >>fh, "DEBUG: what do they show"
+ #TODO: Complete SHOWDOWN
+
+ # Current PS format has the lines:
+ # Uncalled bet ($111.25) returned to s0rrow
+ # s0rrow collected $5.15 from side pot
+ # stervels: shows [Ks Qs] (two pair, Kings and Queens)
+ # stervels collected $45.35 from main pot
+ # Immediately before the summary.
+ # The current importer uses those lines for importing winning rather than the summary
+ for name in self.pot.returned:
+ print >>fh, _("Uncalled bet ($%s) returned to %s" %(self.pot.returned[name],name))
+ for entry in self.collected:
+ print >>fh, _("%s collected $%s from x pot" %(entry[0], entry[1]))
+
+ print >>fh, _("*** SUMMARY ***")
+ print >>fh, "%s | Rake $%.2f" % (self.pot, self.rake)
+ print >>fh, "\n\n"
+
+
+
+class StudHand(Hand):
+ def __init__(self, hhc, sitename, gametype, handText, builtFrom = "HHC"):
+ if gametype['base'] != 'stud':
+ pass # or indeed don't pass and complain instead
+ self.streetList = ['ANTES','THIRD','FOURTH','FIFTH','SIXTH','SEVENTH'] # a list of the observed street names in order
+ self.holeStreets = ['ANTES','THIRD','FOURTH','FIFTH','SIXTH','SEVENTH']
+ Hand.__init__(self, sitename, gametype, handText)
+ self.sb = gametype['sb']
+ self.bb = gametype['bb']
+ #Populate the StudHand
+ #Generally, we call a 'read' method here, which gets the info according to the particular filter (hhc)
+ # which then invokes a 'addXXX' callback
+ if builtFrom == "HHC":
+ hhc.readHandInfo(self)
+ hhc.readPlayerStacks(self)
+ hhc.compilePlayerRegexs(self)
+ hhc.markStreets(self)
+ hhc.readAntes(self)
+ hhc.readBringIn(self)
+ #hhc.readShowdownActions(self) # not done yet
+ # Read actions in street order
+ for street in self.streetList:
+ if self.streets[street]:
+ logging.debug(street)
+ logging.debug(self.streets[street])
+ hhc.readStudPlayerCards(self, street)
+ hhc.readAction(self, street)
+ hhc.readCollectPot(self)
+ #hhc.readShownCards(self) # not done yet
+ self.totalPot() # finalise it (total the pot)
+ hhc.getRake(self)
+ elif builtFrom == "DB":
+ self.select("dummy") # Will need a handId
+
+ def addPlayerCards(self, player, street, open=[], closed=[]):
+ """\
+Assigns observed cards to a player.
+player (string) name of player
+street (string) the street name (in streetList)
+open list of card bigrams e.g. ['2h','Jc'], dealt face up
+closed likewise, but known only to player
+"""
+ logging.debug("addPlayerCards %s, o%s x%s" % (player, open, closed))
+ try:
+ self.checkPlayerExists(player)
+ self.holecards[player][street] = (open, closed)
+# cards = set([self.card(c) for c in cards])
+# self.holecards[player].update(cards)
+ except FpdbParseError, e:
+ print "[ERROR] Tried to add holecards for unknown player: %s" % (player,)
+
+ # TODO: def addComplete(self, player, amount):
+ def addComplete(self, street, player, amountTo):
+ # assert street=='THIRD'
+ # This needs to be called instead of addRaiseTo, and it needs to take account of self.lastBet['THIRD'] to determine the raise-by size
+ """\
+Add a complete on [street] by [player] to [amountTo]
+"""
+ logging.debug("%s %s completes %s" % (street, player, amountTo))
+ self.checkPlayerExists(player)
+ Bp = self.lastBet['THIRD']
+ Bc = reduce(operator.add, self.bets[street][player], 0)
+ Rt = Decimal(amountTo)
+ C = Bp - Bc
+ Rb = Rt - C
+ self._addRaise(street, player, C, Rb, Rt)
+ #~ self.bets[street][player].append(C + Rb)
+ #~ self.stacks[player] -= (C + Rb)
+ #~ act = (player, 'raises', Rb, Rt, C, self.stacks[player]==0)
+ #~ self.actions[street].append(act)
+ #~ self.lastBet[street] = Rt # TODO check this is correct
+ #~ self.pot.addMoney(player, C+Rb)
+
+ def addBringIn(self, player, bringin):
+ if player is not None:
+ logging.debug("Bringin: %s, %s" % (player , bringin))
+ self.bets['THIRD'][player].append(Decimal(bringin))
+ self.stacks[player] -= Decimal(bringin)
+ act = (player, 'bringin', bringin, self.stacks[player]==0)
+ self.actions['THIRD'].append(act)
+ self.lastBet['THIRD'] = Decimal(bringin)
+ self.pot.addMoney(player, Decimal(bringin))
+
+ def writeHand(self, fh=sys.__stdout__):
+ # PokerStars format.
+ print >>fh, _("%s Game #%s: %s ($%s/$%s) - %s" %("PokerStars", self.handid, self.getGameTypeAsString(), self.sb, self.bb, time.strftime('%Y/%m/%d - %H:%M:%S (ET)', self.starttime)))
+ print >>fh, _("Table '%s' %d-max Seat #%s is the button" %(self.tablename, self.maxseats, self.buttonpos))
+
+ players_who_post_antes = set([x[0] for x in self.actions['ANTES']])
+
+ for player in [x for x in self.players if x[1] in players_who_post_antes]:
+ #Only print stacks of players who do something preflop
+ print >>fh, _("Seat %s: %s ($%s)" %(player[0], player[1], player[2]))
+
+ if 'ANTES' in self.actions:
+ for act in self.actions['ANTES']:
+ print >>fh, _("%s: posts the ante $%s" %(act[0], act[3]))
+
+ if 'THIRD' in self.actions:
+ dealt = 0
+ #~ print >>fh, _("*** 3RD STREET ***")
+ for player in [x[1] for x in self.players if x[1] in players_who_post_antes]:
+ if 'THIRD' in self.holecards[player]:
+ (open, closed) = self.holecards[player]['THIRD']
+ dealt+=1
+ if dealt==1:
+ print >>fh, _("*** 3RD STREET ***")
+ print >>fh, _("Dealt to %s:%s%s") % (player, " [" + " ".join(closed) + "] " if closed else " ", "[" + " ".join(open) + "]" if open else "")
+ for act in self.actions['THIRD']:
+ #FIXME: Need some logic here for bringin vs completes
+ self.printActionLine(act, fh)
+
+ if 'FOURTH' in self.actions:
+ dealt = 0
+ #~ print >>fh, _("*** 4TH STREET ***")
+ for player in [x[1] for x in self.players if x[1] in players_who_post_antes]:
+ if 'FOURTH' in self.holecards[player]:
+ old = []
+ (o,c) = self.holecards[player]['THIRD']
+ if o:old.extend(o)
+ if c:old.extend(c)
+ new = self.holecards[player]['FOURTH'][0]
+ dealt+=1
+ if dealt==1:
+ print >>fh, _("*** 4TH STREET ***")
+ print >>fh, _("Dealt to %s:%s%s") % (player, " [" + " ".join(old) + "] " if old else " ", "[" + " ".join(new) + "]" if new else "")
+ for act in self.actions['FOURTH']:
+ self.printActionLine(act, fh)
+
+ if 'FIFTH' in self.actions:
+ dealt = 0
+ #~ print >>fh, _("*** 5TH STREET ***")
+ for player in [x[1] for x in self.players if x[1] in players_who_post_antes]:
+ if 'FIFTH' in self.holecards[player]:
+ old = []
+ for street in ('THIRD','FOURTH'):
+ (o,c) = self.holecards[player][street]
+ if o:old.extend(o)
+ if c:old.extend(c)
+ new = self.holecards[player]['FIFTH'][0]
+ dealt+=1
+ if dealt==1:
+ print >>fh, _("*** 5TH STREET ***")
+ print >>fh, _("Dealt to %s:%s%s") % (player, " [" + " ".join(old) + "] " if old else " ", "[" + " ".join(new) + "]" if new else "")
+ for act in self.actions['FIFTH']:
+ self.printActionLine(act, fh)
+
+ if 'SIXTH' in self.actions:
+ dealt = 0
+ #~ print >>fh, _("*** 6TH STREET ***")
+ for player in [x[1] for x in self.players if x[1] in players_who_post_antes]:
+ if 'SIXTH' in self.holecards[player]:
+ old = []
+ for street in ('THIRD','FOURTH','FIFTH'):
+ (o,c) = self.holecards[player][street]
+ if o:old.extend(o)
+ if c:old.extend(c)
+ new = self.holecards[player]['SIXTH'][0]
+ dealt += 1
+ if dealt == 1:
+ print >>fh, _("*** 6TH STREET ***")
+ print >>fh, _("Dealt to %s:%s%s") % (player, " [" + " ".join(old) + "] " if old else " ", "[" + " ".join(new) + "]" if new else "")
+ for act in self.actions['SIXTH']:
+ self.printActionLine(act, fh)
+
+ if 'SEVENTH' in self.actions:
+ # OK. It's possible that they're all in at an earlier street, but only closed cards are dealt.
+ # Then we have no 'dealt to' lines, no action lines, but still 7th street should appear.
+ # The only way I can see to know whether to print this line is by knowing the state of the hand
+ # i.e. are all but one players folded; is there an allin showdown; and all that.
+ print >>fh, _("*** 7TH STREET ***")
+ for player in [x[1] for x in self.players if x[1] in players_who_post_antes]:
+ if 'SEVENTH' in self.holecards[player]:
+ old = []
+ for street in ('THIRD','FOURTH','FIFTH','SIXTH'):
+ (o,c) = self.holecards[player][street]
+ if o:old.extend(o)
+ if c:old.extend(c)
+ new = self.holecards[player]['SEVENTH'][0]
+ if new:
+ print >>fh, _("Dealt to %s:%s%s") % (player, " [" + " ".join(old) + "] " if old else " ", "[" + " ".join(new) + "]" if new else "")
+ for act in self.actions['SEVENTH']:
+ self.printActionLine(act, fh)
+
+ #Some sites don't have a showdown section so we have to figure out if there should be one
+ # The logic for a showdown is: at the end of river action there are at least two players in the hand
+ # we probably don't need a showdown section in pseudo stars format for our filtering purposes
+ if 'SHOWDOWN' in self.actions:
+ print >>fh, _("*** SHOW DOWN ***")
+ # TODO: print showdown lines.
+
+ # Current PS format has the lines:
+ # Uncalled bet ($111.25) returned to s0rrow
+ # s0rrow collected $5.15 from side pot
+ # stervels: shows [Ks Qs] (two pair, Kings and Queens)
+ # stervels collected $45.35 from main pot
+ # Immediately before the summary.
+ # The current importer uses those lines for importing winning rather than the summary
+ for name in self.pot.returned:
+ print >>fh, _("Uncalled bet ($%s) returned to %s" %(self.pot.returned[name],name))
+ for entry in self.collected:
+ print >>fh, _("%s collected $%s from x pot" %(entry[0], entry[1]))
print >>fh, _("*** SUMMARY ***")
print >>fh, "%s | Rake $%.2f" % (self.pot, self.rake)
@@ -424,13 +948,13 @@ Map the tuple self.gametype onto the pokerstars string describing it
if board: # sometimes hand ends preflop without a board
print >>fh, _("Board [%s]" % (" ".join(board)))
- for player in [x for x in self.players if x[1] in players_who_act_preflop]:
+ for player in [x for x in self.players if x[1] in players_who_post_antes]:
seatnum = player[0]
name = player[1]
- if name in self.collected and name in self.shown:
- print >>fh, _("Seat %d: %s showed [%s] and won ($%s)" % (seatnum, name, " ".join(self.holecards[name]), self.collected[name]))
- elif name in self.collected:
- print >>fh, _("Seat %d: %s collected ($%s)" % (seatnum, name, self.collected[name]))
+ if name in self.collectees and name in self.shown:
+ print >>fh, _("Seat %d: %s showed [%s] and won ($%s)" % (seatnum, name, " ".join(self.holecards[name]), self.collectees[name]))
+ elif name in self.collectees:
+ print >>fh, _("Seat %d: %s collected ($%s)" % (seatnum, name, self.collectees[name]))
elif name in self.shown:
print >>fh, _("Seat %d: %s showed [%s]" % (seatnum, name, " ".join(self.holecards[name])))
elif name in self.folded:
@@ -439,77 +963,8 @@ Map the tuple self.gametype onto the pokerstars string describing it
print >>fh, _("Seat %d: %s mucked" % (seatnum, name))
print >>fh, "\n\n"
- # TODO:
- # logic for side pots
- # logic for which players get to showdown
- # I'm just not sure we need to do this so heavily.. and if we do, it's probably better to use pokerlib
- #if self.holecards[player[1]]: # empty list default is false
- #hole = self.holecards[player[1]]
- ##board = []
- ##for s in self.board.values():
- ##board += s
- ##playerhand = self.bestHand('hi', board+hole)
- ##print "Seat %d: %s showed %s and won/lost with %s" % (player[0], player[1], hole, playerhand)
- #print "Seat %d: %s showed %s" % (player[0], player[1], hole)
- #else:
- #print "Seat %d: %s mucked or folded" % (player[0], player[1])
-
-
- def printHand(self):
- self.writeHand(sys.stdout)
-
- def printActionLine(self, act, fh):
- if act[1] == 'folds':
- print >>fh, _("%s: folds " %(act[0]))
- elif act[1] == 'checks':
- print >>fh, _("%s: checks " %(act[0]))
- if act[1] == 'calls':
- print >>fh, _("%s: calls $%s%s" %(act[0], act[2], ' and is all-in' if act[3] else ''))
- if act[1] == 'bets':
- print >>fh, _("%s: bets $%s%s" %(act[0], act[2], ' and is all-in' if act[3] else ''))
- if act[1] == 'raises':
- print >>fh, _("%s: raises $%s to $%s%s" %(act[0], act[2], act[3], ' and is all-in' if act[5] else ''))
-
- # going to use pokereval to figure out hands at some point.
- # these functions are copied from pokergame.py
- def bestHand(self, side, cards):
- return HandHistoryConverter.eval.best('hi', cards, [])
- # from pokergame.py
- # got rid of the _ for internationalisation
- def readableHandValueLong(self, side, value, cards):
- if value == "NoPair":
- if side == "low":
- if cards[0][0] == '5':
- return ("The wheel")
- else:
- return join(map(lambda card: card[0], cards), ", ")
- else:
- return ("High card %(card)s") % { 'card' : (letter2name[cards[0][0]]) }
- elif value == "OnePair":
- return ("A pair of %(card)s") % { 'card' : (letter2names[cards[0][0]]) } + (", %(card)s kicker") % { 'card' : (letter2name[cards[2][0]]) }
- elif value == "TwoPair":
- return ("Two pairs %(card1)s and %(card2)s") % { 'card1' : (letter2names[cards[0][0]]), 'card2' : _(letter2names[cards[2][0]]) } + (", %(card)s kicker") % { 'card' : (letter2name[cards[4][0]]) }
- elif value == "Trips":
- return ("Three of a kind %(card)s") % { 'card' : (letter2names[cards[0][0]]) } + (", %(card)s kicker") % { 'card' : (letter2name[cards[3][0]]) }
- elif value == "Straight":
- return ("Straight %(card1)s to %(card2)s") % { 'card1' : (letter2name[cards[0][0]]), 'card2' : (letter2name[cards[4][0]]) }
- elif value == "Flush":
- return ("Flush %(card)s high") % { 'card' : (letter2name[cards[0][0]]) }
- elif value == "FlHouse":
- return ("%(card1)ss full of %(card2)ss") % { 'card1' : (letter2name[cards[0][0]]), 'card2' : (letter2name[cards[3][0]]) }
- elif value == "Quads":
- return _("Four of a kind %(card)s") % { 'card' : (letter2names[cards[0][0]]) } + (", %(card)s kicker") % { 'card' : (letter2name[cards[4][0]]) }
- elif value == "StFlush":
- if letter2name[cards[0][0]] == 'Ace':
- return ("Royal flush")
- else:
- return ("Straight flush %(card)s high") % { 'card' : (letter2name[cards[0][0]]) }
- return value
-
-
-class FpdbParseError(Exception): pass
class Pot(object):
@@ -518,6 +973,7 @@ class Pot(object):
self.contenders = set()
self.committed = {}
self.total = None
+ self.returned = {}
def addPlayer(self,player):
self.committed[player] = Decimal(0)
@@ -539,14 +995,15 @@ class Pot(object):
lastbet = committed[-1][0] - committed[-2][0]
if lastbet > 0: # uncalled
returnto = committed[-1][1]
- #print "returning %f to %s" % (lastbet, returnto)
+ #print "DEBUG: returning %f to %s" % (lastbet, returnto)
self.total -= lastbet
self.committed[returnto] -= lastbet
-
-
+ self.returned[returnto] = lastbet
+
+
# Work out side pots
commitsall = sorted([(v,k) for (k,v) in self.committed.items() if v >0])
-
+
self.pots = []
while len(commitsall) > 0:
commitslive = [(v,k) for (v,k) in commitsall if k in self.contenders]
@@ -575,8 +1032,10 @@ class Pot(object):
return "Total pot $%.2f Main pot $%.2f. Side pot $%2.f." % (self.total, self.pots[0], self.pots[1])
elif len(self.pots) == 3:
return "Total pot $%.2f Main pot $%.2f. Side pot-1 $%2.2f. Side pot-2 $%.2f." % (self.total, self.pots[0], self.pots[1], self.pots[2])
+ elif len(self.pots) == 0:
+ # no small blind and walk in bb (hopefully)
+ return "Total pot $%.2f" % (self.total,)
else:
- return "maybe no pot.. or too many pots.. no small blind and walk in bb?."
+ return _("too many pots.. no small blind and walk in bb?. self.pots: %s" %(self.pots))
# I don't know stars format for a walk in the bb when sb doesn't post.
# The thing to do here is raise a Hand error like fpdb import does and file it into errors.txt
-
diff --git a/pyfpdb/HandHistoryConverter.py b/pyfpdb/HandHistoryConverter.py
index 7dea7731..8af8fbd1 100644
--- a/pyfpdb/HandHistoryConverter.py
+++ b/pyfpdb/HandHistoryConverter.py
@@ -15,12 +15,12 @@
#In the "official" distribution you can find the license in
#agpl-3.0.txt in the docs folder of the package.
-import Configuration
-import FpdbRegex
import Hand
import re
import sys
import traceback
+import logging
+from optparse import OptionParser
import os
import os.path
import xml.dom.minidom
@@ -28,7 +28,7 @@ import codecs
from decimal import Decimal
import operator
from xml.dom.minidom import Node
-from pokereval import PokerEval
+# from pokereval import PokerEval
import time
import datetime
import gettext
@@ -71,85 +71,178 @@ letter2names = {
import gettext
gettext.install('myapplication')
+class HandHistoryConverter():
-
-class HandHistoryConverter:
- eval = PokerEval()
- def __init__(self, config, file, sitename):
- print "HandHistory init called"
- self.c = config
- self.sitename = sitename
- self.obs = "" # One big string
+ READ_CHUNK_SIZE = 10000 # bytes to read at a time from file (in tail mode)
+ def __init__(self, in_path = '-', out_path = '-', sitename = None, follow=False):
+ logging.info("HandHistory init called")
+
+ # default filetype and codepage. Subclasses should set these properly.
self.filetype = "text"
self.codepage = "utf8"
- self.doc = None # For XML based HH files
- self.file = file
- self.hhbase = self.c.get_import_parameters().get("hhArchiveBase")
- self.hhbase = os.path.expanduser(self.hhbase)
- self.hhdir = os.path.join(self.hhbase,sitename)
- self.gametype = []
-# self.ofile = os.path.join(self.hhdir,file)
- self.rexx = FpdbRegex.FpdbRegex()
+
+ self.in_path = in_path
+ self.out_path = out_path
+ if self.out_path == '-':
+ # write to stdout
+ self.out_fh = sys.stdout
+ else:
+ # TODO: out_path should be sanity checked before opening. Perhaps in fpdb_import?
+ # I'm not sure what we're looking for, although we don't want out_path==in_path!='-'
+ self.out_fh = open(self.out_path, 'w') # doomswitch is now on :|
+ self.sitename = sitename
+ self.follow = follow
+ self.compiledPlayers = set()
+ self.maxseats = 10
def __str__(self):
+ #TODO : I got rid of most of the hhdir stuff.
tmp = "HandHistoryConverter: '%s'\n" % (self.sitename)
- tmp = tmp + "\thhbase: '%s'\n" % (self.hhbase)
- tmp = tmp + "\thhdir: '%s'\n" % (self.hhdir)
+ #tmp = tmp + "\thhbase: '%s'\n" % (self.hhbase)
+ #tmp = tmp + "\thhdir: '%s'\n" % (self.hhdir)
tmp = tmp + "\tfiletype: '%s'\n" % (self.filetype)
- tmp = tmp + "\tinfile: '%s'\n" % (self.file)
-# tmp = tmp + "\toutfile: '%s'\n" % (self.ofile)
-# tmp = tmp + "\tgametype: '%s'\n" % (self.gametype[0])
-# tmp = tmp + "\tgamebase: '%s'\n" % (self.gametype[1])
-# tmp = tmp + "\tlimit: '%s'\n" % (self.gametype[2])
-# tmp = tmp + "\tsb/bb: '%s/%s'\n" % (self.gametype[3], self.gametype[4])
+ tmp = tmp + "\tinfile: '%s'\n" % (self.in_path)
+ tmp = tmp + "\toutfile: '%s'\n" % (self.out_path)
+ #tmp = tmp + "\tgametype: '%s'\n" % (self.gametype[0])
+ #tmp = tmp + "\tgamebase: '%s'\n" % (self.gametype[1])
+ #tmp = tmp + "\tlimit: '%s'\n" % (self.gametype[2])
+ #tmp = tmp + "\tsb/bb: '%s/%s'\n" % (self.gametype[3], self.gametype[4])
return tmp
- def processFile(self):
+ def start(self):
+ """process a hand at a time from the input specified by in_path.
+If in follow mode, wait for more data to turn up.
+Otherwise, finish at eof..."""
starttime = time.time()
if not self.sanityCheck():
print "Cowardly refusing to continue after failed sanity check"
return
- self.readFile(self.file)
- self.gametype = self.determineGameType()
- self.hands = self.splitFileIntoHands()
- for hand in self.hands:
- print "\nInput:\n"+hand.string
- self.readHandInfo(hand)
- self.readPlayerStacks(hand)
- print "DEBUG stacks:", hand.stacks
- self.markStreets(hand)
- self.readBlinds(hand)
- self.readHeroCards(hand) # want to generalise to draw games
-
- self.readShowdownActions(hand)
-
- # Read actions in street order
- for street in hand.streetList: # go through them in order
- if hand.streets.group(street) is not None:
- self.readCommunityCards(hand, street) # read community cards
- self.readAction(hand, street)
-
-
- self.readCollectPot(hand)
- self.readShownCards(hand)
-
- # finalise it (total the pot)
- hand.totalPot()
- self.getRake(hand)
-
- hand.writeHand(sys.stderr)
- #if(hand.involved == True):
- #self.writeHand("output file", hand)
- #hand.printHand()
- #else:
- #pass #Don't write out observed hands
+ if self.follow:
+ numHands = 0
+ for handText in self.tailHands():
+ numHands+=1
+ self.processHand(handText)
+ else:
+ handsList = self.allHandsAsList()
+ logging.info("Parsing %d hands" % len(handsList))
+ for handText in handsList:
+ self.processHand(handText)
+ numHands= len(handsList)
endtime = time.time()
- print "Processed %d hands in %d seconds" % (len(self.hands), endtime-starttime)
+ print "Processed %d hands in %.3f seconds" % (numHands, endtime - starttime)
+ if self.out_fh != sys.stdout:
+ self.out_fh.close()
+
+
+ def tailHands(self):
+ """Generator of handTexts from a tailed file:
+Tail the in_path file and yield handTexts separated by re_SplitHands"""
+ if self.in_path == '-': raise StopIteration
+ interval = 1.0 # seconds to sleep between reads for new data
+ fd = codecs.open(self.in_path,'r', self.codepage)
+ data = ''
+ while 1:
+ where = fd.tell()
+ newdata = fd.read(self.READ_CHUNK_SIZE)
+ if not newdata:
+ fd_results = os.fstat(fd.fileno())
+ try:
+ st_results = os.stat(self.in_path)
+ except OSError:
+ st_results = fd_results
+ if st_results[1] == fd_results[1]:
+ time.sleep(interval)
+ fd.seek(where)
+ else:
+ logging.debug("%s changed inode numbers from %d to %d" % (self.in_path, fd_results[1], st_results[1]))
+ fd = codecs.open(self.in_path, 'r', self.codepage)
+ fd.seek(where)
+ else:
+ # yield hands
+ data = data + newdata
+ result = self.re_SplitHands.split(data)
+ result = iter(result)
+ data = ''
+ # --x data (- is bit of splitter, x is paragraph) yield,...,keep
+ # [,--,x] result of re.split (with group around splitter)
+ # ,x our output: yield nothing, keep x
+ #
+ # --x--x [,--,x,--,x] x,x
+ # -x--x [-x,--,x] x,x
+ # x- [x-] ,x-
+ # x-- [x,--,] x,--
+ # x--x [x,--,x] x,x
+ # x--x-- [x,--,x,--,] x,x,--
+
+ # The length is always odd.
+ # 'odd' indices are always splitters.
+ # 'even' indices are always paragraphs or ''
+ # We want to discard all the ''
+ # We want to discard splitters unless the final item is '' (because the splitter could grow with new data)
+ # We want to yield all paragraphs followed by a splitter, i.e. all even indices except the last.
+ for para in result:
+ try:
+ result.next()
+ splitter = True
+ except StopIteration:
+ splitter = False
+ if splitter: # para is followed by a splitter
+ if para: yield para # para not ''
+ else:
+ data = para # keep final partial paragraph
+
+
+ def allHandsAsList(self):
+ """Return a list of handtexts in the file at self.in_path"""
+ #TODO : any need for this to be generator? e.g. stars support can email one huge file of all hands in a year. Better to read bit by bit than all at once.
+ self.readFile()
+ self.obs = self.obs.strip()
+ self.obs = self.obs.replace('\r\n', '\n')
+ if self.obs == "" or self.obs == None:
+ logging.info("Read no hands.")
+ return
+ return re.split(self.re_SplitHands, self.obs)
+
+ def processHand(self, handText):
+ gametype = self.determineGameType(handText)
+ logging.debug("gametype %s" % gametype)
+ if gametype is None:
+ l = None
+ gametype = "unmatched"
+ # TODO: not ideal, just trying to not error.
+ # TODO: Need to count failed hands.
+ else:
+ # See if gametype is supported.
+ type = gametype['type']
+ base = gametype['base']
+ limit = gametype['limitType']
+ l = [type] + [base] + [limit]
+ hand = None
+ if l in self.readSupportedGames():
+ hand = None
+ if gametype['base'] == 'hold':
+ logging.debug("hand = Hand.HoldemOmahaHand(self, self.sitename, gametype, handtext)")
+ hand = Hand.HoldemOmahaHand(self, self.sitename, gametype, handText)
+ elif gametype['base'] == 'stud':
+ hand = Hand.StudHand(self, self.sitename, gametype, handText)
+ elif gametype['base'] == 'draw':
+ hand = Hand.DrawHand(self, self.sitename, gametype, handText)
+ else:
+ logging.info("Unsupported game type: %s" % gametype)
+
+ if hand:
+ hand.writeHand(self.out_fh)
+ else:
+ logging.info("Unsupported game type: %s" % gametype)
+ # TODO: pity we don't know the HID at this stage. Log the entire hand?
+ # From the log we can deduce that it is the hand after the one before :)
+
- #####
# These functions are parse actions that may be overridden by the inheriting class
- #
+ # This function should return a list of lists looking like:
+ # return [["ring", "hold", "nl"], ["tour", "hold", "nl"]]
+ # Showing all supported games limits and types
def readSupportedGames(self): abstract
@@ -157,22 +250,38 @@ class HandHistoryConverter:
# type base limit
# [ ring, hold, nl , sb, bb ]
# Valid types specified in docs/tabledesign.html in Gametypes
- def determineGameType(self): abstract
+ def determineGameType(self, handText): abstract
+ """return dict with keys/values:
+ 'type' in ('ring', 'tour')
+ 'limitType' in ('nl', 'cn', 'pl', 'cp', 'fl')
+ 'base' in ('hold', 'stud', 'draw')
+ 'category' in ('holdem', 'omahahi', omahahilo', 'razz', 'studhi', 'studhilo', 'fivedraw', '27_1draw', '27_3draw', 'badugi')
+ 'hilo' in ('h','l','s')
+ 'smallBlind' int?
+ 'bigBlind' int?
+ 'smallBet'
+ 'bigBet'
+ 'currency' in ('USD', 'EUR', 'T$', )
+or None if we fail to get the info """
+ #TODO: which parts are optional/required?
# Read any of:
- # HID HandID
- # TABLE Table name
- # SB small blind
- # BB big blind
- # GAMETYPE gametype
- # YEAR MON DAY HR MIN SEC datetime
- # BUTTON button seat number
+ # HID HandID
+ # TABLE Table name
+ # SB small blind
+ # BB big blind
+ # GAMETYPE gametype
+ # YEAR MON DAY HR MIN SEC datetime
+ # BUTTON button seat number
def readHandInfo(self, hand): abstract
# Needs to return a list of lists in the format
# [['seat#', 'player1name', 'stacksize'] ['seat#', 'player2name', 'stacksize'] [...]]
def readPlayerStacks(self, hand): abstract
-
+
+ def compilePlayerRegexs(self): abstract
+ """Compile dynamic regexes -- these explicitly match known player names and must be updated if a new player joins"""
+
# Needs to return a MatchObject with group names identifying the streets into the Hand object
# so groups are called by street names 'PREFLOP', 'FLOP', 'STREET2' etc
# blinds are done seperately
@@ -182,7 +291,11 @@ class HandHistoryConverter:
# ['player1name', 'player2name', ...] where player1name is the sb and player2name is bb,
# addtional players are assumed to post a bb oop
def readBlinds(self, hand): abstract
+ def readAntes(self, hand): abstract
+ def readBringIn(self, hand): abstract
+ def readButton(self, hand): abstract
def readHeroCards(self, hand): abstract
+ def readPlayerCards(self, hand, street): abstract
def readAction(self, hand, street): abstract
def readCollectPot(self, hand): abstract
def readShownCards(self, hand): abstract
@@ -194,23 +307,34 @@ class HandHistoryConverter:
def sanityCheck(self):
+ """Check we aren't going to do some stupid things"""
+ #TODO: the hhbase stuff needs to be in fpdb_import
sane = False
base_w = False
- #Check if hhbase exists and is writable
- #Note: Will not try to create the base HH directory
- if not (os.access(self.hhbase, os.W_OK) and os.path.isdir(self.hhbase)):
- print "HH Sanity Check: Directory hhbase '" + self.hhbase + "' doesn't exist or is not writable"
- else:
- #Check if hhdir exists and is writable
- if not os.path.isdir(self.hhdir):
- # In first pass, dir may not exist. Attempt to create dir
- print "Creating directory: '%s'" % (self.hhdir)
- os.mkdir(self.hhdir)
- sane = True
- elif os.access(self.hhdir, os.W_OK):
- sane = True
- else:
- print "HH Sanity Check: Directory hhdir '" + self.hhdir + "' or its parent directory are not writable"
+ #~ #Check if hhbase exists and is writable
+ #~ #Note: Will not try to create the base HH directory
+ #~ if not (os.access(self.hhbase, os.W_OK) and os.path.isdir(self.hhbase)):
+ #~ print "HH Sanity Check: Directory hhbase '" + self.hhbase + "' doesn't exist or is not writable"
+ #~ else:
+ #~ #Check if hhdir exists and is writable
+ #~ if not os.path.isdir(self.hhdir):
+ #~ # In first pass, dir may not exist. Attempt to create dir
+ #~ print "Creating directory: '%s'" % (self.hhdir)
+ #~ os.mkdir(self.hhdir)
+ #~ sane = True
+ #~ elif os.access(self.hhdir, os.W_OK):
+ #~ sane = True
+ #~ else:
+ #~ print "HH Sanity Check: Directory hhdir '" + self.hhdir + "' or its parent directory are not writable"
+
+ # Make sure input and output files are different or we'll overwrite the source file
+ if True: # basically.. I don't know
+ sane = True
+
+ if(self.in_path != '-' and self.out_path == self.in_path):
+ print "HH Sanity Check: output and input files are the same, check config"
+ sane = False
+
return sane
@@ -221,21 +345,27 @@ class HandHistoryConverter:
def splitFileIntoHands(self):
hands = []
- self.obs.strip()
- list = self.rexx.split_hand_re.split(self.obs)
+ self.obs = self.obs.strip()
+ list = self.re_SplitHands.split(self.obs)
list.pop() #Last entry is empty
for l in list:
-# print "'" + l + "'"
+# print "'" + l + "'"
hands = hands + [Hand.Hand(self.sitename, self.gametype, l)]
return hands
- def readFile(self, filename):
- """Read file"""
- print "Reading file: '%s'" %(filename)
+ def readFile(self):
+ """open in_path according to self.codepage"""
+
if(self.filetype == "text"):
- infile=codecs.open(filename, "rU", self.codepage)
- self.obs = infile.read()
- infile.close()
+ if self.in_path == '-':
+ # read from stdin
+ logging.debug("Reading stdin with %s" % self.codepage) # is this necessary? or possible? or what?
+ in_fh = codecs.getreader('cp1252')(sys.stdin)
+ else:
+ logging.debug("Opening %s with %s" % (self.in_path, self.codepage))
+ in_fh = codecs.open(self.in_path, 'r', self.codepage)
+ self.obs = in_fh.read()
+ in_fh.close()
elif(self.filetype == "xml"):
try:
doc = xml.dom.minidom.parse(filename)
@@ -244,18 +374,9 @@ class HandHistoryConverter:
traceback.print_exc(file=sys.stderr)
-#takes a poker float (including , for thousand seperator and converts it to an int
- def float2int (self, string):
- pos=string.find(",")
- if (pos!=-1): #remove , the thousand seperator
- string=string[0:pos]+string[pos+1:]
+ def getStatus(self):
+ #TODO: Return a status of true if file processed ok
+ return True
- pos=string.find(".")
- if (pos!=-1): #remove decimal point
- string=string[0:pos]+string[pos+1:]
-
- result = int(string)
- if pos==-1: #no decimal point - was in full dollars - need to multiply with 100
- result*=100
- return result
-#end def float2int
+ def getProcessedFile(self):
+ return self.out_path
diff --git a/pyfpdb/Hello.py b/pyfpdb/Hello.py
new file mode 100644
index 00000000..41262d6c
--- /dev/null
+++ b/pyfpdb/Hello.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python
+"""Hello.py
+
+Hello World demostration for Aux_Window.
+"""
+# Copyright 2009, Ray E. Barker
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+########################################################################
+
+# to do
+# add another class that demonstrates querying the db
+
+# Standard Library modules
+import sys
+
+# pyGTK modules
+import pygtk
+import gtk
+import gobject
+
+# FreePokerTools modules
+from Mucked import Aux_Window
+
+class Hello(Aux_Window):
+ """A 'Hello World' Aux_Window demo."""
+ def create(self):
+# This demo simply creates a label in a window.
+ self.container = gtk.Window()
+ self.container.add(gtk.Label("Hello World"))
+# and shows it. There is no functionality.
+ self.container.show_all()
+
+class Hello_plus(Aux_Window):
+ """A slightly more complex 'Hello World demo."""
+ def __init__(self, hud, config, params):
+ """Initialize a new aux_window object."""
+# Initialize the aux_window object. Do not interact with the gui
+# in this function.
+ self.hud = hud # hud object that this aux window supports
+ self.config = config # configuration object for this aux window to use
+ self.params = params # hash aux params from config
+
+ self.hands_played = 0 # initialize the hands played counter
+
+# get the site we are playing from the HUD
+ self.site = hud.site
+ print "site =", hud.site # print it to the terminal, to make sure
+
+# now get our screen name for that site from the configuration
+# wrap it in a try/except in case screen name isn't set up in the config file
+ try:
+ site_params = self.config.get_site_parameters(self.hud.site)
+ self.hero = site_params['screen_name']
+ except:
+ self.hero = 'YOUR NAME HERE'
+ print "hero =", self.hero
+
+
+ def create(self):
+ """Creates the gui."""
+ self.container = gtk.Window() # create a gtk window for our container
+ self.label = gtk.Label("") # create a blank label to write in update_gui
+ self.container.add(self.label) # add it to our container
+ self.container.show_all() # show the container and its contents
+
+ def update_data(self, new_hand_id, db_connection):
+ """Increment the hands.played attribute."""
+# This function will be called from the main program, in a thread separate from
+# the gui. Therefore complex calculations can be done without slowing down the
+# HUD. Long-running calculations will delay the appearance or updating of the HUD.
+# This function should NOT interact with the gui--that will cause unpredictable
+# results on some systems.
+
+# This long running calculation is incrementing the number of hands played.
+ self.hands_played = self.hands_played + 1
+
+ def update_gui(self, new_hand_id):
+ """Update the aux_window gui."""
+# This function runs inside the gui thread and should only be used for
+# interacting with the gui. Long-running calculations should not be done
+# in this function--they will prevent HUD interaction until they are
+# complete.
+
+# Here, we just update the label in our aux_window from the number of
+# hands played that was updated in the "update_data()" function.
+ self.label.set_text("Hello %s\nYou have played %d hands\n on %s." % (self.hero, self.hands_played, self.site))
+
+class Hello_Menu(Aux_Window):
+ """A 'Hello World' Aux_Window demo."""
+ def create(self):
+# This demo puts a menu item on the HUD mainwindow.
+ self.item = gtk.MenuItem('Print cards')
+ self.hud.menu.append(self.item)
+ self.item.connect("activate", self.print_cards)
+ self.item.show()
+
+ def print_cards(self, *args):
+# callback for the menu item
+ print "cards =", self.hud.cards
diff --git a/pyfpdb/Hud.py b/pyfpdb/Hud.py
index 9911a61b..363175a1 100644
--- a/pyfpdb/Hud.py
+++ b/pyfpdb/Hud.py
@@ -3,7 +3,7 @@
Create and manage the hud overlays.
"""
-# Copyright 2008, Ray E. Barker
+# Copyright 2008, 2009 Ray E. Barker
#
# This program is free software; you can redistribute it and/or modify
@@ -43,11 +43,24 @@ import Configuration
import Stats
import Mucked
import Database
-import HUD_main
+import HUD_main
+
+def importName(module_name, name):
+ """Import a named object 'name' from module 'module_name'."""
+# Recipe 16.3 in the Python Cookbook, 2nd ed. Thanks!!!!
+
+ try:
+ module = __import__(module_name, globals(), locals(), [name])
+ except:
+ return None
+ return(getattr(module, name))
class Hud:
- def __init__(self, table, max, poker_game, config, db_connection):
+ def __init__(self, parent, table, max, poker_game, config, db_connection):
+# __init__ is (now) intended to be called from the stdin thread, so it
+# cannot touch the gui
+ self.parent = parent
self.table = table
self.config = config
self.poker_game = poker_game
@@ -56,29 +69,40 @@ class Hud:
self.deleted = False
self.stacked = True
self.site = table.site
- self.colors = config.get_default_colors(self.table.site)
+ self.mw_created = False
- self.stat_windows = {}
+ self.stat_windows = {}
self.popup_windows = {}
- self.aux_windows = []
+ self.aux_windows = []
(font, font_size) = config.get_default_font(self.table.site)
+ self.colors = config.get_default_colors(self.table.site)
+
if font == None:
font = "Sans"
if font_size == None:
font_size = "8"
-
- self.font = pango.FontDescription(font + " " + font_size)
-
+ self.font = pango.FontDescription("%s %s" % (font, font_size))
# do we need to add some sort of condition here for dealing with a request for a font that doesn't exist?
+ game_params = config.get_game_parameters(self.poker_game)
+ if not game_params['aux'] == [""]:
+ for aux in game_params['aux']:
+ aux_params = config.get_aux_parameters(aux)
+ my_import = importName(aux_params['module'], aux_params['class'])
+ if my_import == None:
+ continue
+ self.aux_windows.append(my_import(self, config, aux_params))
+
+ def create_mw(self):
+
# Set up a main window for this this instance of the HUD
self.main_window = gtk.Window()
self.main_window.set_gravity(gtk.gdk.GRAVITY_STATIC)
- self.main_window.set_title(table.name + " FPDBHUD")
- self.main_window.connect("destroy", self.kill_hud)
+ self.main_window.set_title("%s FPDBHUD" % (self.table.name))
self.main_window.set_decorated(False)
self.main_window.set_opacity(self.colors["hudopacity"])
+ self.main_window.set_focus_on_map(False)
self.ebox = gtk.EventBox()
self.label = gtk.Label("FPDB Menu (Right Click)\nLeft-drag to move")
@@ -101,7 +125,7 @@ class Hud:
self.menu = gtk.Menu()
self.item1 = gtk.MenuItem('Kill this HUD')
self.menu.append(self.item1)
- self.item1.connect("activate", self.kill_hud)
+ self.item1.connect("activate", self.parent.kill_hud, self.table_name)
self.item1.show()
self.item2 = gtk.MenuItem('Save Layout')
@@ -122,6 +146,7 @@ class Hud:
self.ebox.connect_object("button-press-event", self.on_button_press, self.menu)
self.main_window.show_all()
+ self.mw_created = True
# TODO: fold all uses of this type of 'topify' code into a single function, if the differences between the versions don't
# create adverse effects?
@@ -129,14 +154,16 @@ class Hud:
if os.name == 'nt':
self.topify_window(self.main_window)
else:
- self.main_window.parentgdkhandle = gtk.gdk.window_foreign_new(self.table.number) # gets a gdk handle for poker client
+ self.main_window.parentgdkhandle = gtk.gdk.window_foreign_new(int(self.table.number)) # gets a gdk handle for poker client
self.main_window.gdkhandle = gtk.gdk.window_foreign_new(self.main_window.window.xid) # gets a gdk handle for the hud table window
self.main_window.gdkhandle.set_transient_for(self.main_window.parentgdkhandle) #
+
+ self.update_table_position()
def update_table_position(self):
if os.name == 'nt':
if not win32gui.IsWindow(self.table.number):
- self.kill_hud()
+ self.parent.kill_hud(self, self.table.name)
return False
# anyone know how to do this in unix, or better yet, trap the X11 error that is triggered when executing the get_origin() for a closed window?
@@ -147,10 +174,10 @@ class Hud:
self.main_window.move(x, y)
adj = self.adj_seats(self.hand, self.config)
loc = self.config.get_locations(self.table.site, self.max)
- for i in range(1, self.max + 1):
- (x, y) = loc[adj[i]]
- if i in self.stat_windows:
- self.stat_windows[i].relocate(x, y)
+ # TODO: is stat_windows getting converted somewhere from a list to a dict, for no good reason?
+ for i, w in enumerate(self.stat_windows.itervalues()):
+ (x, y) = loc[adj[i+1]]
+ w.relocate(x, y)
return True
def on_button_press(self, widget, event):
@@ -162,20 +189,29 @@ class Hud:
return True
return False
- def kill_hud(self, *args):
- for k in self.stat_windows:
- self.stat_windows[k].window.destroy()
- self.main_window.destroy()
- self.deleted = True
- HUD_main.HUD_removed(self.table.name)
+ def kill(self, *args):
+# kill all stat_windows, popups and aux_windows in this HUD
+# heap dead, burnt bodies, blood 'n guts, veins between my teeth
+ for s in self.stat_windows.itervalues():
+ s.kill_popups()
+ s.window.destroy()
+ self.stat_windows = {}
+# also kill any aux windows
+ for aux in self.aux_windows:
+ aux.destroy()
+ self.aux_windows = []
def reposition_windows(self, *args):
- for w in self.stat_windows:
- self.stat_windows[w].window.move(self.stat_windows[w].x, self.stat_windows[w].y)
+ for w in self.stat_windows.itervalues():
+ if type(w) == int:
+# print "in reposition, w =", w
+ continue
+# print "in reposition, w =", w, w.x, w.y
+ w.window.move(w.x, w.y)
return True
def debug_stat_windows(self, *args):
- print self.table, "\n", self.main_window.window.get_transient_for()
+# print self.table, "\n", self.main_window.window.get_transient_for()
for w in self.stat_windows:
print self.stat_windows[w].window.window.get_transient_for()
@@ -186,42 +222,67 @@ class Hud:
new_loc = (loc[0] - self.table.x, loc[1] - self.table.y)
new_layout[self.stat_windows[sw].adj - 1] = new_loc
self.config.edit_layout(self.table.site, self.max, locations = new_layout)
+# ask each aux to save its layout back to the config object
+ (aux.save_layout() for aux in self.aux_windows)
+# save the config object back to the file
+ print "saving new xml file"
self.config.save()
def adj_seats(self, hand, config):
+
+# Need range here, not xrange -> need the actual list
adj = range(0, self.max + 1) # default seat adjustments = no adjustment
# does the user have a fav_seat?
- try:
- if int(config.supported_sites[self.table.site].layout[self.max].fav_seat) > 0:
+ if int(config.supported_sites[self.table.site].layout[self.max].fav_seat) > 0:
+ try:
+ sys.stderr.write("site = %s, max = %d, fav seat = %d\n" % (self.table.site, self.max, config.supported_sites[self.table.site].layout[self.max].fav_seat))
fav_seat = config.supported_sites[self.table.site].layout[self.max].fav_seat
-# db_connection = Database.Database(config, self.db_name, 'temp')
- actual_seat = self.db_connection.get_actual_seat(hand, config.supported_sites[self.table.site].screen_name)
-# db_connection.close_connection()
- for i in range(0, self.max + 1):
+ sys.stderr.write("found fav seat = %d\n" % fav_seat)
+# actual_seat = self.db_connection.get_actual_seat(hand, config.supported_sites[self.table.site].screen_name)
+ actual_seat = self.get_actual_seat(config.supported_sites[self.table.site].screen_name)
+ sys.stderr.write("found actual seat = %d\n" % actual_seat)
+ for i in xrange(0, self.max + 1):
j = actual_seat + i
- if j > self.max: j = j - self.max
+ if j > self.max:
+ j = j - self.max
adj[j] = fav_seat + i
- if adj[j] > self.max: adj[j] = adj[j] - self.max
- except:
- pass
+ if adj[j] > self.max:
+ adj[j] = adj[j] - self.max
+ except Exception, inst:
+ sys.stderr.write("exception in adj!!!\n\n")
+ sys.stderr.write("error is %s" % inst) # __str__ allows args to printed directly
return adj
- def create(self, hand, config):
+ def get_actual_seat(self, name):
+ for key in self.stat_dict:
+ if self.stat_dict[key]['screen_name'] == name:
+ return self.stat_dict[key]['seat']
+ sys.stderr.write("Error finding actual seat.\n")
+
+ def create(self, hand, config, stat_dict, cards):
# update this hud, to the stats and players as of "hand"
# hand is the hand id of the most recent hand played at this table
#
# this method also manages the creating and destruction of stat
# windows via calls to the Stat_Window class
-
+ self.hand = hand
+ if not self.mw_created:
+ self.create_mw()
+
+ self.stat_dict = stat_dict
+ self.cards = cards
+ sys.stderr.write("------------------------------------------------------------\nCreating hud from hand %s\n" % hand)
adj = self.adj_seats(hand, config)
+ sys.stderr.write("adj = %s\n" % adj)
loc = self.config.get_locations(self.table.site, self.max)
# create the stat windows
- for i in range(1, self.max + 1):
+ for i in xrange(1, self.max + 1):
(x, y) = loc[adj[i]]
if i in self.stat_windows:
self.stat_windows[i].relocate(x, y)
else:
+ sys.stderr.write("actual seat = %d, x = %d, y= %d\n" % (i, x, y))
self.stat_windows[i] = Stat_Window(game = config.supported_games[self.poker_game],
parent = self,
table = self.table,
@@ -233,56 +294,49 @@ class Hud:
font = self.font)
self.stats = []
- for i in range(0, config.supported_games[self.poker_game].rows + 1):
- row_list = [''] * config.supported_games[self.poker_game].cols
+ game = config.supported_games[self.poker_game]
+
+ for i in xrange(0, game.rows + 1):
+ row_list = [''] * game.cols
self.stats.append(row_list)
- for stat in config.supported_games[self.poker_game].stats:
+ for stat in game.stats:
self.stats[config.supported_games[self.poker_game].stats[stat].row] \
[config.supported_games[self.poker_game].stats[stat].col] = \
config.supported_games[self.poker_game].stats[stat].stat_name
-
- game_params = config.get_game_parameters(self.poker_game)
- if not game_params['aux'] == "":
- aux_params = config.get_aux_parameters(game_params['aux'])
- self.aux_windows.append(eval("%s.%s(gtk.Window(), self, config, aux_params)" % (aux_params['module'], aux_params['class'])))
if os.name == "nt":
gobject.timeout_add(500, self.update_table_position)
- def update(self, hand, config, stat_dict):
+ def update(self, hand, config):
self.hand = hand # this is the last hand, so it is available later
- self.stat_dict = stat_dict # so this is available for popups, etc
- self.update_table_position()
- self.stat_dict = stat_dict
+ if os.name == 'nt':
+ self.update_table_position()
- for s in stat_dict:
+ for s in self.stat_dict:
+ statd = self.stat_dict[s]
try:
- self.stat_windows[stat_dict[s]['seat']].player_id = stat_dict[s]['player_id']
+ self.stat_windows[self.stat_dict[s]['seat']].player_id = self.stat_dict[s]['player_id']
except: # omg, we have more seats than stat windows .. damn poker sites with incorrect max seating info .. let's force 10 here
self.max = 10
- self.create(hand, config)
- self.stat_windows[stat_dict[s]['seat']].player_id = stat_dict[s]['player_id']
+ self.create(hand, config, self.stat_dict, self.cards)
+ self.stat_windows[statd['seat']].player_id = statd['player_id']
- for r in range(0, config.supported_games[self.poker_game].rows):
- for c in range(0, config.supported_games[self.poker_game].cols):
+ for r in xrange(0, config.supported_games[self.poker_game].rows):
+ for c in xrange(0, config.supported_games[self.poker_game].cols):
this_stat = config.supported_games[self.poker_game].stats[self.stats[r][c]]
- number = Stats.do_stat(stat_dict, player = stat_dict[s]['player_id'], stat = self.stats[r][c])
- statstring = this_stat.hudprefix + str(number[1]) + this_stat.hudsuffix
+ number = Stats.do_stat(self.stat_dict, player = statd['player_id'], stat = self.stats[r][c])
+ statstring = "%s%s%s" % (this_stat.hudprefix, str(number[1]), this_stat.hudsuffix)
+ window = self.stat_windows[statd['seat']]
if this_stat.hudcolor != "":
self.label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(self.colors['hudfgcolor']))
- self.stat_windows[stat_dict[s]['seat']].label[r][c].modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(this_stat.hudcolor))
-
- self.stat_windows[stat_dict[s]['seat']].label[r][c].set_text(statstring)
+ window.label[r][c].modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(this_stat.hudcolor))
+
+ window.label[r][c].set_text(statstring)
if statstring != "xxx": # is there a way to tell if this particular stat window is visible already, or no?
- self.stat_windows[stat_dict[s]['seat']].window.show_all()
-# self.reposition_windows()
- tip = stat_dict[s]['screen_name'] + "\n" + number[5] + "\n" + \
- number[3] + ", " + number[4]
- Stats.do_tip(self.stat_windows[stat_dict[s]['seat']].e_box[r][c], tip)
-# for m in self.aux_windows:
-# m.update_data(hand)
-# m.update_gui(hand)
+ window.window.show_all()
+ tip = "%s\n%s\n%s, %s" % (statd['screen_name'], number[5], number[3], number[4])
+ Stats.do_tip(window.e_box[r][c], tip)
def topify_window(self, window):
"""Set the specified gtk window to stayontop in MS Windows."""
@@ -306,6 +360,8 @@ class Hud:
style = win32gui.GetWindowLong(self.table.number, win32con.GWL_EXSTYLE)
style |= win32con.WS_CLIPCHILDREN
win32gui.SetWindowLong(self.table.number, win32con.GWL_EXSTYLE, style)
+ break
+
window.set_title(real_name)
class Stat_Window:
@@ -316,7 +372,7 @@ class Stat_Window:
# and double-clicks.
if event.button == 3: # right button event
- Popup_window(widget, self)
+ self.popups.append(Popup_window(widget, self))
if event.button == 2: # middle button event
self.window.hide()
@@ -327,7 +383,15 @@ class Stat_Window:
self.window.begin_resize_drag(gtk.gdk.WINDOW_EDGE_SOUTH_EAST, event.button, int(event.x_root), int(event.y_root), event.time)
else:
self.window.begin_move_drag(event.button, int(event.x_root), int(event.y_root), event.time)
-
+
+ def kill_popup(self, popup):
+ popup.window.destroy()
+ self.popups.remove(popup)
+
+ def kill_popups(self):
+ map(lambda x: x.window.destroy(), self.popups)
+ self.popups = { }
+
def relocate(self, x, y):
self.x = x + self.table.x
self.y = y + self.table.y
@@ -343,6 +407,8 @@ class Stat_Window:
self.y = y + table.y # x and y are the location relative to table.x & y
self.player_id = player_id # looks like this isn't used ;)
self.sb_click = 0 # used to figure out button clicks
+ self.popups = [] # list of open popups for this stat window
+ self.useframes = parent.config.get_frames(parent.site)
self.window = gtk.Window()
self.window.set_decorated(0)
@@ -351,32 +417,48 @@ class Stat_Window:
self.window.set_title("%s" % seat)
self.window.set_property("skip-taskbar-hint", True)
self.window.set_transient_for(parent.main_window)
+ self.window.set_focus_on_map(False)
- self.grid = gtk.Table(rows = self.game.rows, columns = self.game.cols, homogeneous = False)
- self.window.add(self.grid)
+ grid = gtk.Table(rows = game.rows, columns = game.cols, homogeneous = False)
+ self.grid = grid
+ self.window.add(grid)
+ self.window.modify_bg(gtk.STATE_NORMAL, parent.backgroundcolor)
self.e_box = []
self.frame = []
self.label = []
- for r in range(self.game.rows):
- self.e_box.append([])
- self.label.append([])
- for c in range(self.game.cols):
- self.e_box[r].append( gtk.EventBox() )
+ usegtkframes = self.useframes
+ e_box = self.e_box
+ label = self.label
+ for r in xrange(game.rows):
+ if usegtkframes:
+ self.frame.append([])
+ e_box.append([])
+ label.append([])
+ for c in xrange(game.cols):
+ if usegtkframes:
+ self.frame[r].append( gtk.Frame() )
+ e_box[r].append( gtk.EventBox() )
- self.e_box[r][c].modify_bg(gtk.STATE_NORMAL, parent.backgroundcolor)
- self.e_box[r][c].modify_fg(gtk.STATE_NORMAL, parent.foregroundcolor)
+ e_box[r][c].modify_bg(gtk.STATE_NORMAL, parent.backgroundcolor)
+ e_box[r][c].modify_fg(gtk.STATE_NORMAL, parent.foregroundcolor)
- Stats.do_tip(self.e_box[r][c], 'stuff')
- self.grid.attach(self.e_box[r][c], c, c+1, r, r+1, xpadding = 0, ypadding = 0)
- self.label[r].append( gtk.Label('xxx') )
+ Stats.do_tip(e_box[r][c], 'stuff')
+ if usegtkframes:
+ grid.attach(self.frame[r][c], c, c+1, r, r+1, xpadding = 0, ypadding = 0)
+ self.frame[r][c].add(e_box[r][c])
+ else:
+ grid.attach(e_box[r][c], c, c+1, r, r+1, xpadding = 0, ypadding = 0)
+ label[r].append( gtk.Label('xxx') )
- self.label[r][c].modify_bg(gtk.STATE_NORMAL, parent.backgroundcolor)
- self.label[r][c].modify_fg(gtk.STATE_NORMAL, parent.foregroundcolor)
+ if usegtkframes:
+ self.frame[r][c].modify_bg(gtk.STATE_NORMAL, parent.backgroundcolor)
+ label[r][c].modify_bg(gtk.STATE_NORMAL, parent.backgroundcolor)
+ label[r][c].modify_fg(gtk.STATE_NORMAL, parent.foregroundcolor)
- self.e_box[r][c].add(self.label[r][c])
- self.e_box[r][c].connect("button_press_event", self.button_press_cb)
- self.label[r][c].modify_font(font)
+ e_box[r][c].add(self.label[r][c])
+ e_box[r][c].connect("button_press_event", self.button_press_cb)
+ label[r][c].modify_font(font)
self.window.set_opacity(parent.colors['hudopacity'])
@@ -390,6 +472,7 @@ def destroy(*args): # call back for terminating the main eventloop
class Popup_window:
def __init__(self, parent, stat_window):
self.sb_click = 0
+ self.stat_window = stat_window
# create the popup window
self.window = gtk.Window()
@@ -419,8 +502,8 @@ class Popup_window:
# figure out the row, col address of the click that activated the popup
row = 0
col = 0
- for r in range(0, stat_window.game.rows):
- for c in range(0, stat_window.game.cols):
+ for r in xrange(0, stat_window.game.rows):
+ for c in xrange(0, stat_window.game.cols):
if stat_window.e_box[r][c] == parent:
row = r
col = c
@@ -472,7 +555,8 @@ class Popup_window:
pass
if event.button == 3: # right button event
- self.window.destroy()
+ self.stat_window.kill_popup(self)
+# self.window.destroy()
def toggle_decorated(self, widget):
top = widget.get_toplevel()
@@ -500,8 +584,12 @@ class Popup_window:
for w in tl_windows:
if w[1] == unique_name:
- win32gui.SetWindowPos(w[0], win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE|win32con.SWP_NOSIZE)
-
+ window.set_transient_for(self.parent.main_window)
+ style = win32gui.GetWindowLong(self.table.number, win32con.GWL_EXSTYLE)
+ style |= win32con.WS_CLIPCHILDREN
+ win32gui.SetWindowLong(self.table.number, win32con.GWL_EXSTYLE, style)
+ break
+
window.set_title(real_name)
if __name__== "__main__":
diff --git a/pyfpdb/Mucked.py b/pyfpdb/Mucked.py
index 5d4d8047..93f6d102 100755
--- a/pyfpdb/Mucked.py
+++ b/pyfpdb/Mucked.py
@@ -3,7 +3,7 @@
Mucked cards display for FreePokerTools HUD.
"""
-# Copyright 2008, Ray E. Barker
+# Copyright 2008, 2009, Ray E. Barker
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -25,6 +25,7 @@ Mucked cards display for FreePokerTools HUD.
# Standard Library modules
import sys
+import pprint
# pyGTK modules
import pygtk
@@ -36,26 +37,63 @@ import Configuration
import Database
class Aux_Window:
- def __init__(self, container, hud, params, config):
- self.config = hud
+ def __init__(self, hud, params, config):
+ self.hud = hud
+ self.params = params
self.config = config
- self.container = container
- self.vbox = gtk.VBox()
- self.container.add(self.vbox)
-
- def update_data(self):
+ def update_data(self, *args):
pass
- def update_gui(self):
+ def update_gui(self, *args):
pass
+ def create(self, *args):
+ pass
+
+ def relocate(self, *args):
+ pass
+
+ def save_layout(self, *args):
+ pass
+
+ def destroy(self):
+ try:
+ self.container.destroy()
+ except:
+ pass
+
+############################################################################
+# Some utility routines useful for Aux_Windows
+#
+ def get_card_images(self):
+ card_images = {}
+ suits = ('S', 'H', 'D', 'C')
+ ranks = ('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'B')
+ pb = gtk.gdk.pixbuf_new_from_file(self.config.execution_path(self.params['deck']))
+
+ for j in range(0, 14):
+ for i in range(0, 4):
+ temp_pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, pb.get_has_alpha(), pb.get_bits_per_sample(), 30, 42)
+ pb.copy_area(30*j, 42*i, 30, 42, temp_pb, 0, 0)
+ card_images[(ranks[j], suits[i])] = temp_pb
+ return(card_images)
+# cards are 30 wide x 42 high
+
+ def split_cards(self, card):
+ if card == 'xx': return ('B', 'S')
+ return (card[0], card[1].upper())
+
+ def has_cards(self, cards):
+ for c in cards:
+ if c in set('shdc'): return True
+ return False
+
class Stud_mucked(Aux_Window):
- def __init__(self, container, hud, config, params):
+ def __init__(self, hud, config, params):
self.hud = hud # hud object that this aux window supports
self.config = config # configuration object for this aux window to use
- self.container = container # parent container for this aux window widget
self.params = params # hash aux params from config
try:
@@ -64,12 +102,18 @@ class Stud_mucked(Aux_Window):
except:
self.hero = ''
+ self.mucked_list = Stud_list(self, params, config, self.hero)
+ self.mucked_cards = Stud_cards(self, params, config)
+ self.mucked_list.mucked_cards = self.mucked_cards
+
+ def create(self):
+
+ self.container =gtk.Window()
self.vbox = gtk.VBox()
self.container.add(self.vbox)
- self.mucked_list = Stud_list(self.vbox, self, params, config, self.hero)
- self.mucked_cards = Stud_cards(self.vbox, self, params, config)
- self.mucked_list.mucked_cards = self.mucked_cards
+ self.mucked_list.create(self.vbox)
+ self.mucked_cards.create(self.vbox)
self.container.show_all()
def update_data(self, new_hand_id, db_connection):
@@ -81,16 +125,16 @@ class Stud_mucked(Aux_Window):
self.mucked_list.update_gui(new_hand_id)
class Stud_list:
- def __init__(self, container, parent, params, config, hero):
+ def __init__(self, parent, params, config, hero):
- self.container = container
self.parent = parent
self.params = params
self.config = config
self.hero = hero
-# self.db_name = db_name
+ def create(self, container):
# set up a scrolled window to hold the listbox
+ self.container = container
self.scrolled_window = gtk.ScrolledWindow()
self.scrolled_window.set_policy(gtk.POLICY_NEVER, gtk.POLICY_ALWAYS)
self.container.add(self.scrolled_window)
@@ -151,7 +195,7 @@ class Stud_list:
winners = winners + player
pot_dec = "%.2f" % (float(pot)/100)
- hero_cards = self.get_hero_cards(self.parent.hero, self.parent.mucked_cards.cards)
+ hero_cards = self.get_hero_cards(self.parent.hero, self.parent.hud.cards)
self.info_row = ((new_hand_id, hero_cards, pot_dec, winners), )
def get_hero_cards(self, hero, cards):
@@ -160,11 +204,10 @@ class Stud_list:
if hero == '':
return "xxxxxx"
else:
- for k in cards.keys():
- if cards[k]['screen_name'] == hero:
- return trans[cards[k]['card1Value']] + cards[k]['card1Suit'] \
- + trans[cards[k]['card2Value']] + cards[k]['card2Suit'] \
- + trans[cards[k]['card3Value']] + cards[k]['card3Suit']
+# find the hero's seat from the stat_dict
+ for stat in self.parent.hud.stat_dict.itervalues():
+ if stat['screen_name'] == hero:
+ return self.parent.hud.cards[stat['seat']][0:6]
return "xxxxxx"
def update_gui(self, new_hand_id):
@@ -176,21 +219,23 @@ class Stud_list:
vadj.set_value(vadj.upper)
class Stud_cards:
- def __init__(self, container, parent, params, config):
+ def __init__(self, parent, params, config):
- self.container = container #this is the parent container of the mucked cards widget
self.parent = parent
self.params = params
self.config = config
# self.db_name = db_name
- self.card_images = self.get_card_images()
+ self.card_images = self.parent.get_card_images()
self.seen_cards = {}
self.grid_contents = {}
self.eb = {}
self.rows = 8
self.cols = 7
+
+ def create(self, container):
+ self.container = container
self.grid = gtk.Table(self.rows, self.cols + 4, homogeneous = False)
for r in range(0, self.rows):
@@ -222,25 +267,7 @@ class Stud_cards:
self.container.add(self.grid)
- def translate_cards(self, old_cards):
- ranks = ('', '', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
-
- for c in old_cards.keys():
- for i in range(1, 8):
- rank = 'card' + str(i) + 'Value'
- suit = 'card' + str(i) + 'Suit'
- key = 'hole_card_' + str(i)
- if old_cards[c][rank] == 0:
- old_cards[c][key] = 'xx'
- else:
- old_cards[c][key] = ranks[old_cards[c][rank]] + old_cards[c][suit]
- return old_cards
-
def update_data(self, new_hand_id, db_connection):
-# db_connection = Database.Database(self.config, 'fpdb', '')
- cards = db_connection.get_cards(new_hand_id)
- self.cards = self.translate_cards(cards)
-
self.tips = []
action = db_connection.get_action_from_hand(new_hand_id)
for street in action:
@@ -258,13 +285,13 @@ class Stud_cards:
def update_gui(self, new_hand_id):
self.clear()
- for c in self.cards.keys():
- self.grid_contents[(1, self.cards[c]['seat_number'] - 1)].set_text(self.cards[c]['screen_name'])
- for i in ((0, 'hole_card_1'), (1, 'hole_card_2'), (2, 'hole_card_3'), (3, 'hole_card_4'),
- (4, 'hole_card_5'), (5, 'hole_card_6'), (6, 'hole_card_7')):
- if not self.cards[c][i[1]] == "xx":
- self.seen_cards[(i[0], self.cards[c]['seat_number'] - 1)]. \
- set_from_pixbuf(self.card_images[self.split_cards(self.cards[c][i[1]])])
+ for c, cards in self.parent.hud.cards.iteritems():
+ self.grid_contents[(1, c - 1)].set_text(self.get_screen_name(c))
+ for i in ((0, cards[0:2]), (1, cards[2:4]), (2, cards[4:6]), (3, cards[6:8]),
+ (4, cards[8:10]), (5, cards[10:12]), (6, cards[12:14])):
+ if not i[1] == "xx":
+ self.seen_cards[(i[0], c - 1)]. \
+ set_from_pixbuf(self.card_images[self.parent.split_cards(i[1])])
## action in tool tips for 3rd street cards
for c in (0, 1, 2):
for r in range(0, self.rows):
@@ -276,8 +303,12 @@ class Stud_cards:
for r in range(0, self.rows):
self.eb[(round_to_col[round], r)].set_tooltip_text(self.tips[round])
- def split_cards(self, card):
- return (card[0], card[1].upper())
+ def get_screen_name(self, seat_no):
+ """Gets and returns the screen name from stat_dict, given seat number."""
+ for k in self.parent.hud.stat_dict.keys():
+ if self.parent.hud.stat_dict[k]['seat'] == seat_no:
+ return self.parent.hud.stat_dict[k]['screen_name']
+ return "No Name"
def clear(self):
for r in range(0, self.rows):
@@ -286,20 +317,147 @@ class Stud_cards:
self.seen_cards[(c, r)].set_from_pixbuf(self.card_images[('B', 'S')])
self.eb[(c, r)].set_tooltip_text('')
- def get_card_images(self):
- card_images = {}
- suits = ('S', 'H', 'D', 'C')
- ranks = ('A', 'K', 'Q', 'J', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'B')
- pb = gtk.gdk.pixbuf_new_from_file(self.config.execution_path(self.params['deck']))
-
- for j in range(0, 14):
- for i in range(0, 4):
- temp_pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, pb.get_has_alpha(), pb.get_bits_per_sample(), 30, 42)
- pb.copy_area(30*j, 42*i, 30, 42, temp_pb, 0, 0)
- card_images[(ranks[j], suits[i])] = temp_pb
- return(card_images)
+class Flop_Mucked(Aux_Window):
+ """Aux_Window class for displaying mucked cards for flop games."""
-# cards are 30 wide x 42 high
+ def __init__(self, hud, config, params):
+ self.hud = hud # hud object that this aux window supports
+ self.config = config # configuration object for this aux window to use
+ self.params = params # dict aux params from config
+ self.positions = {} # dict of window positions
+# self.rel_positions = {} # dict of window positions, relative to the table origin
+ self.displayed_cards = False
+ self.timer_on = False # bool = Ture if the timeout for removing the cards is on
+ self.card_images = self.get_card_images()
+
+ def create(self):
+ self.adj = self.hud.adj_seats(0, self.config)
+ loc = self.config.get_aux_locations(self.params['name'], int(self.hud.max))
+
+ self.m_windows = {} # windows to put the card images in
+ self.eb = {} # event boxes so we can interact with the mucked cards
+ self.seen_cards = {} # image objects to stash the cards in
+
+ for i in (range(1, self.hud.max + 1) + ['common']):
+ if i == 'common':
+ (x, y) = self.params['layout'][self.hud.max].common
+ else:
+ (x, y) = loc[self.adj[i]]
+ self.m_windows[i] = gtk.Window()
+ self.m_windows[i].set_decorated(False)
+ self.m_windows[i].set_property("skip-taskbar-hint", True)
+ self.m_windows[i].set_transient_for(self.hud.main_window)
+ self.m_windows[i].set_focus_on_map(False)
+ self.eb[i] = gtk.EventBox()
+ self.eb[i].connect("button_press_event", self.button_press_cb)
+ self.m_windows[i].connect("configure_event", self.configure_event_cb, i)
+ self.m_windows[i].add(self.eb[i])
+ self.seen_cards[i] = gtk.image_new_from_pixbuf(self.card_images[('B', 'H')])
+ self.eb[i].add(self.seen_cards[i])
+ self.positions[i] = (int(x) + self.hud.table.x, int(y) + self.hud.table.y)
+# self.rel_positions[i] = (int(x), int(y))
+ self.m_windows[i].move(self.positions[i][0], self.positions[i][1])
+ self.m_windows[i].set_opacity(float(self.params['opacity']))
+ self.m_windows[i].show_all()
+ self.m_windows[i].hide()
+
+ def update_gui(self, new_hand_id):
+ """Prepare and show the mucked cards."""
+ if self.displayed_cards:
+ self.hide_mucked_cards()
+ self.displayed_cards = False
+ for (i, cards) in self.hud.cards.iteritems():
+ if self.has_cards(cards):
+# scratch is a working pixbuf, used to assemble the image
+ scratch = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8,
+ int(self.params['card_wd'])*len(cards)/2,
+ int(self.params['card_ht']))
+ x = 0 # x coord where the next card starts in scratch
+ for card in [cards[k:k+2] for k in xrange(0, len(cards), 2)]:
+# concatenate each card image to scratch
+ self.card_images[self.split_cards(card)].copy_area(0, 0,
+ int(self.params['card_wd']), int(self.params['card_ht']),
+ scratch, x, 0)
+ x = x + int(self.params['card_wd'])
+ self.seen_cards[i].set_from_pixbuf(scratch)
+# self.m_windows[i].show_all()
+ self.m_windows[i].resize(1,1)
+ self.m_windows[i].show()
+ self.m_windows[i].move(self.positions[i][0], self.positions[i][1]) # here is where I move back
+ self.displayed_cards = True
+
+ for stats in self.hud.stat_dict.itervalues():
+ self.eb[stats['seat']].set_tooltip_text(stats['screen_name'])
+
+ if self.displayed_cards and float(self.params['timeout']) > 0:
+ self.timer_on = True
+ gobject.timeout_add(int(1000*float(self.params['timeout'])), self.timed_out)
+
+ def destroy(self):
+ """Destroy all of the mucked windows."""
+ for w in self.m_windows.values():
+ w.destroy()
+
+ def timed_out(self):
+# this is the callback from the timeout
+
+# if timer_on is False the user has cancelled the timer with a click
+# so just return False to cancel the timer
+ if not self.timer_on:
+ return False
+ else:
+ self.hide_mucked_cards()
+ return False
+
+ def hide_mucked_cards(self):
+ """Hide the mucked card windows."""
+ for (i, w) in self.m_windows.iteritems():
+ w.hide()
+ self.displayed_cards = False
+
+ def button_press_cb(self, widget, event, *args):
+ """Handle button clicks in the event boxes."""
+
+# shift-any button exposes all the windows and turns off the timer
+ if event.state & gtk.gdk.SHIFT_MASK:
+ self.timer_on = False
+ self.expose_all()
+ return
+
+ if event.button == 3: # right button event
+ pass
+
+ elif event.button == 2: # middle button event
+ if self.timer_on == True:
+ self.timer_on = False
+ else:
+ self.timer_on = False
+ self.hide_mucked_cards()
+
+ elif event.button == 1: # left button event
+ window = widget.get_parent()
+ window.begin_move_drag(event.button, int(event.x_root), int(event.y_root), event.time)
+
+ def configure_event_cb(self, widget, event, i, *args):
+ self.positions[i] = widget.get_position()
+# self.rel_positions[i] = (self.positions[i][0] - self.hud.table.x, self.positions[i][1] - self.hud.table.y)
+
+ def expose_all(self):
+ for (i, cards) in self.hud.cards.iteritems():
+ self.m_windows[i].show()
+ self.m_windows[i].move(self.positions[i][0], self.positions[i][1]) # here is where I move back
+ self.displayed_cards = True
+
+ def save_layout(self, *args):
+ """Save new layout back to the aux element in the config file."""
+ new_locs = {}
+# print "adj =", self.adj
+ for (i, pos) in self.positions.iteritems():
+ if i != 'common':
+ new_locs[self.adj[int(i)]] = (pos[0] - self.hud.table.x, pos[1] - self.hud.table.y)
+ else:
+ new_locs[i] = (pos[0] - self.hud.table.x, pos[1] - self.hud.table.y)
+ self.config.edit_aux_layout(self.params['name'], self.hud.max, locations = new_locs)
if __name__== "__main__":
diff --git a/pyfpdb/PokerStarsToFpdb.py b/pyfpdb/PokerStarsToFpdb.py
new file mode 100755
index 00000000..0c1beb6b
--- /dev/null
+++ b/pyfpdb/PokerStarsToFpdb.py
@@ -0,0 +1,335 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+#
+# Copyright 2008, Carl Gherardi
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+########################################################################
+
+import sys
+from HandHistoryConverter import *
+
+# PokerStars HH Format
+
+class PokerStars(HandHistoryConverter):
+
+ # Static regexes
+ re_GameInfo = re.compile("PokerStars Game #(?P[0-9]+):\s+(HORSE)? \(?(?PHold\'em|Razz|7 Card Stud|Omaha|Omaha Hi/Lo|Badugi) (?PNo Limit|Limit|Pot Limit),? \(?(?P\$|)?(?P[.0-9]+)/\$?(?P[.0-9]+)\) - (?P.*$)", re.MULTILINE)
+ re_SplitHands = re.compile('(\n\n+)')
+ re_HandInfo = re.compile("^Table \'(?P[- a-zA-Z]+)\'(?P.+?$)?", re.MULTILINE)
+ re_Button = re.compile('Seat #(?P\d+) is the button', re.MULTILINE)
+ re_PlayerInfo = re.compile('^Seat (?P[0-9]+): (?P.*) \(\$?(?P[.0-9]+) in chips\)', re.MULTILINE)
+ re_Board = re.compile(r"\[(?P.+)\]")
+# self.re_setHandInfoRegex('.*#(?P[0-9]+): Table (?P[ a-zA-Z]+) - \$?(?P[.0-9]+)/\$?(?P[.0-9]+) - (?P