sqlcoder initial updates

This commit is contained in:
sqlcoder 2008-12-02 00:15:50 +00:00
parent 5884f2f66b
commit a824814c0a
15 changed files with 2578 additions and 2334 deletions

0
pyfpdb/CliFpdb.py Executable file → Normal file
View File

117
pyfpdb/Configuration.py Executable file → Normal file
View File

@ -57,6 +57,8 @@ 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.layout = {}
for layout_node in node.getElementsByTagName('layout'):
@ -99,6 +101,7 @@ class Game:
self.db = node.getAttribute("db")
self.rows = int( node.getAttribute("rows") )
self.cols = int( node.getAttribute("cols") )
self.aux = node.getAttribute("aux")
self.stats = {}
for stat_node in node.getElementsByTagName('stat'):
@ -119,6 +122,7 @@ class Game:
temp = temp + " db = %s\n" % self.db
temp = temp + " rows = %d\n" % self.rows
temp = temp + " cols = %d\n" % self.cols
temp = temp + " aux = %s\n" % self.aux
for stat in self.stats.keys():
temp = temp + "%s" % self.stats[stat]
@ -143,18 +147,20 @@ class Database:
temp = temp + ' ' + key + " = " + value + "\n"
return temp
class Mucked:
class Aux_window:
def __init__(self, node):
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")
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")
def __str__(self):
temp = 'Mucked = ' + self.name + "\n"
temp = 'Aux = ' + self.name + "\n"
for key in dir(self):
if key.startswith('__'): continue
value = getattr(self, key)
@ -179,9 +185,10 @@ class Import:
def __init__(self, node):
self.interval = node.getAttribute("interval")
self.callFpdbHud = node.getAttribute("callFpdbHud")
self.hhArchiveBase = node.getAttribute("hhArchiveBase")
def __str__(self):
return " interval = %s\n callFpdbHud = %s\n" % (self.interval, self.callFpdbHud)
return " interval = %s\n callFpdbHud = %s\n hhArchiveBase = %s" % (self.interval, self.callFpdbHud, self.hhArchiveBase)
class Tv:
def __init__(self, node):
@ -236,7 +243,7 @@ class Config:
self.supported_sites = {}
self.supported_games = {}
self.supported_databases = {}
self.mucked_windows = {}
self.aux_windows = {}
self.popup_windows = {}
# s_sites = doc.getElementsByTagName("supported_sites")
@ -255,9 +262,9 @@ class Config:
self.supported_databases[db.db_name] = db
# s_dbs = doc.getElementsByTagName("mucked_windows")
for mw_node in doc.getElementsByTagName("mw"):
mw = Mucked(node = mw_node)
self.mucked_windows[mw.name] = mw
for aw_node in doc.getElementsByTagName("aw"):
aw = Aux_window(node = aw_node)
self.aux_windows[aw.name] = aw
# s_dbs = doc.getElementsByTagName("popup_windows")
for pu_node in doc.getElementsByTagName("pu"):
@ -377,7 +384,6 @@ class Config:
def edit_layout(self, site_name, max, width = None, height = None,
fav_seat = None, locations = None):
print "max = ", max
site_node = self.get_site_node(site_name)
layout_node = self.get_layout_node(site_node, max)
if layout_node == None: return
@ -437,11 +443,13 @@ class Config:
def get_import_parameters(self):
imp = {}
try:
imp['imp-callFpdbHud'] = self.imp.callFpdbHud
imp['hud-defaultInterval'] = int(self.imp.interval)
except: # Default import parameters
imp['imp-callFpdbHud'] = True
imp['hud-defaultInterval'] = 10
imp['callFpdbHud'] = self.callFpdbHud
imp['interval'] = self.interval
imp['hhArchiveBase'] = self.hhArchiveBase
except: # Default params
imp['callFpdbHud'] = True
imp['interval'] = 10
imp['hhArchiveBase'] = "~/.fpdb/HandHistories/"
return imp
def get_default_paths(self, site = "PokerStars"):
@ -480,6 +488,10 @@ class Config:
( 0, 280), (121, 280), ( 46, 30) )
return locations
def get_supported_sites(self):
"""Returns the list of supported sites."""
return self.supported_sites.keys()
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):
@ -494,13 +506,16 @@ class Config:
parms["site_path"] = self.supported_sites[site].site_path
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
return parms
def set_site_parameters(self, site_name, converter = None, decoder = None,
hudbgcolor = None, hudfgcolor = None,
hudopacity = None, screen_name = None,
site_path = None, table_finder = None,
HH_path = None):
HH_path = None, enabled = None):
"""Sets the specified site parameters for the specified site."""
site_node = self.get_site_node(site_name)
if not db_node == None:
@ -513,6 +528,7 @@ class Config:
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 self.supported_databases.has_key(db_name):
if not converter == None: self.supported_sites[site].converter = converter
@ -524,8 +540,47 @@ class Config:
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
return
def get_aux_windows(self):
"""Gets the list of mucked window formats in the configuration."""
mw = []
for w in self.aux_windows.keys():
mw.append(w)
return mw
def get_aux_parameters(self, name):
"""Gets a dict of mucked window parameters from the named mw."""
param = {}
if self.aux_windows.has_key(name):
for key in dir(self.aux_windows[name]):
if key.startswith('__'): continue
value = getattr(self.aux_windows[name], key)
if callable(value): continue
param[key] = value
return param
return None
def get_game_parameters(self, name):
"""Get the configuration parameters for the named game."""
param = {}
if self.supported_games.has_key(name):
param['game_name'] = self.supported_games[name].game_name
param['db'] = self.supported_games[name].db
param['rows'] = self.supported_games[name].rows
param['cols'] = self.supported_games[name].cols
param['aux'] = self.supported_games[name].aux
return param
def get_supported_games(self):
"""Get the list of supported games."""
sg = []
for game in c.supported_games.keys():
sg.append(c.supported_games[game].game_name)
return sg
if __name__== "__main__":
c = Config()
@ -546,18 +601,20 @@ if __name__== "__main__":
print c.supported_databases[db]
print "----------- END SUPPORTED DATABASES -----------"
print "\n----------- MUCKED WINDOW FORMATS -----------"
for w in c.mucked_windows.keys():
print c.mucked_windows[w]
print "----------- END MUCKED WINDOW FORMATS -----------"
print "\n----------- AUX WINDOW FORMATS -----------"
for w in c.aux_windows.keys():
print c.aux_windows[w]
print "----------- END AUX WINDOW FORMATS -----------"
print "\n----------- POPUP WINDOW FORMATS -----------"
for w in c.popup_windows.keys():
print c.popup_windows[w]
print "----------- END MUCKED WINDOW FORMATS -----------"
print "----------- END POPUP WINDOW FORMATS -----------"
print "\n----------- IMPORT -----------"
# print c.imp
tmp = c.get_import_parameters()
for param in tmp:
print " " + str(param) + ": " + str(tmp[param])
print "----------- END IMPORT -----------"
print "\n----------- TABLE VIEW -----------"
@ -573,6 +630,12 @@ if __name__== "__main__":
print "paths = ", c.get_default_paths("PokerStars")
print "colors = ", c.get_default_colors("PokerStars")
print "locs = ", c.get_locations("PokerStars", 8)
for mw in c.get_aux_windows():
print c.get_aux_parameters(mw)
for site in c.supported_sites.keys():
print "site = ", site,
print c.get_site_parameters(site)
for game in c.get_supported_games():
print c.get_game_parameters(game)

View File

@ -601,7 +601,34 @@ class FpdbSQLQueries:
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
# Returns the profit for all hands, Total pot - money invested by playerId
if(self.dbname == 'MySQL InnoDB') or (self.dbname == 'PostgreSQL'):
self.query['getRingProfitAllHandsPlayerIdSite'] = """
SELECT hp.handId, hp.winnings, SUM(ha.amount) costs, hp.winnings - SUM(ha.amount) profit
FROM HandsPlayers hp
INNER JOIN Players pl ON hp.playerId = pl.id
INNER JOIN Hands h ON h.id = hp.handId
INNER JOIN HandsActions ha ON ha.handPlayerId = hp.id
WHERE pl.name = %s
AND pl.siteId = %s
AND hp.tourneysPlayersId IS NULL
group by hp.handId, hp.winnings, h.handStart
ORDER BY h.handStart"""
elif(self.dbname == 'SQLite'):
#May not work.
self.query['getRingProfitAllHandsPlayerIdSite'] = """
SELECT hp.handId, hp.winnings, SUM(ha.amount) costs, hp.winnings - SUM(ha.amount) profit
FROM HandsPlayers hp
INNER JOIN Players pl ON hp.playerId = pl.id
INNER JOIN Hands h ON h.id = hp.handId
INNER JOIN HandsActions ha ON ha.handPlayerId = hp.id
WHERE pl.name = %s
AND pl.siteId = %s
AND hp.tourneysPlayersId IS NULL
group by hp.handId, hp.winnings, h.handStart
ORDER BY h.handStart"""
# Returns the profit for a given ring game handId, Total pot - money invested by playerId - WRONG, returns players costs
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

View File

@ -26,11 +26,61 @@ import os
import time
import fpdb_import
class GuiAutoImport (threading.Thread):
def starsBrowseClicked(self, widget, data):
"""runs when user clicks browse on auto import tab"""
#print "start of GuiAutoImport.starsBrowseClicked"
current_path=self.starsDirPath.get_text()
def __init__(self, settings, config):
"""Constructor for GuiAutoImport"""
self.settings=settings
self.config=config
imp = self.config.get_import_parameters()
print "Import parameters"
print imp
self.input_settings = {}
self.importer = fpdb_import.Importer(self, self.settings, self.config)
self.importer.setCallHud(True)
self.importer.setMinPrint(30)
self.importer.setQuiet(False)
self.importer.setFailOnError(False)
self.importer.setHandCount(0)
# self.importer.setWatchTime()
self.server=settings['db-host']
self.user=settings['db-user']
self.password=settings['db-password']
self.database=settings['db-databaseName']
self.mainVBox=gtk.VBox(False,1)
self.mainVBox.show()
self.settingsHBox = gtk.HBox(False, 0)
self.mainVBox.pack_start(self.settingsHBox, False, True, 0)
self.settingsHBox.show()
self.intervalLabel = gtk.Label("Time between imports in seconds:")
self.settingsHBox.pack_start(self.intervalLabel)
self.intervalLabel.show()
self.intervalEntry=gtk.Entry()
self.intervalEntry.set_text(str(self.config.get_import_parameters().get("interval")))
self.settingsHBox.pack_start(self.intervalEntry)
self.intervalEntry.show()
self.addSites(self.mainVBox)
self.startButton=gtk.Button("Start Autoimport")
self.startButton.connect("clicked", self.startClicked, "start clicked")
self.mainVBox.add(self.startButton)
self.startButton.show()
#end of GuiAutoImport.__init__
def browseClicked(self, widget, data):
"""runs when user clicks one of the browse buttons in the auto import tab"""
current_path=data[1].get_text()
dia_chooser = gtk.FileChooserDialog(title="Please choose the path that you want to auto import",
action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
@ -42,32 +92,12 @@ class GuiAutoImport (threading.Thread):
response = dia_chooser.run()
if response == gtk.RESPONSE_OK:
#print dia_chooser.get_filename(), 'selected'
self.starsDirPath.set_text(dia_chooser.get_filename())
data[1].set_text(dia_chooser.get_filename())
self.input_settings[data[0]][0] = dia_chooser.get_filename()
elif response == gtk.RESPONSE_CANCEL:
print 'Closed, no files selected'
dia_chooser.destroy()
#end def GuiAutoImport.starsBrowseClicked
def tiltBrowseClicked(self, widget, data):
"""runs when user clicks browse on auto import tab"""
#print "start of GuiAutoImport.tiltBrowseClicked"
current_path=self.tiltDirPath.get_text()
dia_chooser = gtk.FileChooserDialog(title="Please choose the path that you want to auto import",
action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
#dia_chooser.set_current_folder(pathname)
dia_chooser.set_filename(current_path)
#dia_chooser.set_select_multiple(select_multiple) #not in tv, but want this in bulk import
response = dia_chooser.run()
if response == gtk.RESPONSE_OK:
#print dia_chooser.get_filename(), 'selected'
self.tiltDirPath.set_text(dia_chooser.get_filename())
elif response == gtk.RESPONSE_CANCEL:
print 'Closed, no files selected'
dia_chooser.destroy()
#end def GuiAutoImport.tiltBrowseClicked
#end def GuiAutoImport.browseClicked
def do_import(self):
"""Callback for timer to do an import iteration."""
@ -106,12 +136,11 @@ class GuiAutoImport (threading.Thread):
# command = command + " %s" % (self.database)
# print "command = ", command
# self.pipe_to_hud = os.popen(command, 'w')
self.starspath=self.starsDirPath.get_text()
self.tiltpath=self.tiltDirPath.get_text()
# Add directory to importer object.
self.importer.addImportDirectory(self.starspath, True, "PokerStars", "passthrough")
self.importer.addImportDirectory(self.tiltpath, True, "FullTilt", "passthrough")
# Add directories to importer object.
for site in self.input_settings:
self.importer.addImportDirectory(self.input_settings[site][0], True, site, self.input_settings[site][1])
print "Adding import directories - Site: " + site + " dir: "+ str(self.input_settings[site][0])
self.do_import()
interval=int(self.intervalEntry.get_text())
@ -123,78 +152,44 @@ class GuiAutoImport (threading.Thread):
return self.mainVBox
#end def get_vbox
def __init__(self, settings, config, debug=True):
"""Constructor for GuiAutoImport"""
self.settings=settings
self.config=config
self.importer = fpdb_import.Importer(self,self.settings)
self.importer.setCallHud(True)
self.importer.setMinPrint(30)
self.importer.setQuiet(False)
self.importer.setFailOnError(False)
self.importer.setHandCount(0)
# self.importer.setWatchTime()
#Create the site line given required info and setup callbacks
#enabling and disabling sites from this interface not possible
#expects a box to layout the line horizontally
def createSiteLine(self, hbox, site, iconpath, hhpath, filter_name, active = True):
label = gtk.Label(site + " auto-import:")
hbox.pack_start(label, False, False, 0)
label.show()
self.server=settings['db-host']
self.user=settings['db-user']
self.password=settings['db-password']
self.database=settings['db-databaseName']
dirPath=gtk.Entry()
dirPath.set_text(hhpath)
hbox.pack_start(dirPath, False, True, 0)
dirPath.show()
self.mainVBox=gtk.VBox(False,1)
self.mainVBox.show()
browseButton=gtk.Button("Browse...")
browseButton.connect("clicked", self.browseClicked, [site] + [dirPath])
hbox.pack_start(browseButton, False, False, 0)
browseButton.show()
self.settingsHBox = gtk.HBox(False, 0)
self.mainVBox.pack_start(self.settingsHBox, False, True, 0)
self.settingsHBox.show()
label = gtk.Label(site + " filter:")
hbox.pack_start(label, False, False, 0)
label.show()
self.intervalLabel = gtk.Label("Interval (ie. break) between imports in seconds:")
self.settingsHBox.pack_start(self.intervalLabel)
self.intervalLabel.show()
filter=gtk.Entry()
filter.set_text(filter_name)
hbox.pack_start(filter, False, True, 0)
filter.show()
self.intervalEntry=gtk.Entry()
self.intervalEntry.set_text(str(self.settings['hud-defaultInterval']))
self.settingsHBox.pack_start(self.intervalEntry)
self.intervalEntry.show()
def addSites(self, vbox):
for site in self.config.supported_sites.keys():
pathHBox = gtk.HBox(False, 0)
vbox.pack_start(pathHBox, False, True, 0)
pathHBox.show()
self.pathHBox = gtk.HBox(False, 0)
self.mainVBox.pack_start(self.pathHBox, False, True, 0)
self.pathHBox.show()
paths = self.config.get_default_paths(site)
params = self.config.get_site_parameters(site)
self.createSiteLine(pathHBox, site, False, paths['hud-defaultPath'], params['converter'], params['enabled'])
self.input_settings[site] = [paths['hud-defaultPath']] + [params['converter']]
self.pathStarsLabel = gtk.Label("Path to PokerStars auto-import:")
self.pathHBox.pack_start(self.pathStarsLabel, False, False, 0)
self.pathStarsLabel.show()
self.starsDirPath=gtk.Entry()
paths = self.config.get_default_paths("PokerStars")
self.starsDirPath.set_text(paths['hud-defaultPath'])
self.pathHBox.pack_start(self.starsDirPath, False, True, 0)
self.starsDirPath.show()
self.browseButton=gtk.Button("Browse...")
self.browseButton.connect("clicked", self.starsBrowseClicked, "Browse clicked")
self.pathHBox.pack_start(self.browseButton, False, False, 0)
self.browseButton.show()
self.pathTiltLabel = gtk.Label("Path to Full Tilt auto-import:")
self.pathHBox.pack_start(self.pathTiltLabel, False, False, 0)
self.pathTiltLabel.show()
self.tiltDirPath=gtk.Entry()
paths = self.config.get_default_paths("Full Tilt")
self.tiltDirPath.set_text(paths['hud-defaultPath'])
self.pathHBox.pack_start(self.tiltDirPath, False, True, 0)
self.tiltDirPath.show()
self.browseButton=gtk.Button("Browse...")
self.browseButton.connect("clicked", self.tiltBrowseClicked, "Browse clicked")
self.pathHBox.pack_start(self.browseButton, False, False, 0)
self.browseButton.show()
self.startButton=gtk.Button("Start Autoimport")
self.startButton.connect("clicked", self.startClicked, "start clicked")
self.mainVBox.add(self.startButton)
self.startButton.show()
#end of GuiAutoImport.__init__
if __name__== "__main__":
def destroy(*args): # call back for terminating the main eventloop
gtk.main_quit()
@ -206,7 +201,7 @@ if __name__== "__main__":
settings['db-databaseName'] = "fpdb"
settings['hud-defaultInterval'] = 10
settings['hud-defaultPath'] = 'C:/Program Files/PokerStars/HandHistory/nutOmatic'
settings['imp-callFpdbHud'] = True
settings['callFpdbHud'] = True
i = GuiAutoImport(settings)
main_window = gtk.Window()

View File

@ -87,16 +87,20 @@ class GuiGraphViewer (threading.Thread):
#end of def showClicked
def getRingProfitGraph(self, name, site):
self.cursor.execute(self.sql.query['getRingWinningsAllGamesPlayerIdSite'], (name, site))
#self.cursor.execute(self.sql.query['getRingWinningsAllGamesPlayerIdSite'], (name, site))
self.cursor.execute(self.sql.query['getRingProfitAllHandsPlayerIdSite'], (name, site))
# returns (HandId,Winnings,Costs,Profit)
winnings = self.db.cursor.fetchall()
profit=range(len(winnings))
for i in profit:
self.cursor.execute(self.sql.query['getRingProfitFromHandId'], (name, winnings[i][0], site))
spent = self.db.cursor.fetchone()
profit[i]=(i, winnings[i][1]-spent[0])
#profit=range(len(winnings))
#for i in profit:
# self.cursor.execute(self.sql.query['getRingProfitFromHandId'], (name, winnings[i][0], site))
# spent = self.db.cursor.fetchone()
# profit[i]=(i, winnings[i][1]-spent[0])
#y=map(lambda x:float(x[1]), profit)
y=map(lambda x:float(x[3]), winnings)
y=map(lambda x:float(x[1]), profit)
line = cumsum(y)
return line/100
#end of def getRingProfitGraph

27
pyfpdb/HUD_main.py Executable file → Normal file
View File

@ -83,6 +83,8 @@ def update_HUD(new_hand_id, table_name, config, stat_dict):
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()
@ -92,7 +94,7 @@ def read_stdin(): # This is the thread function
global hud_dict
db_connection = Database.Database(config, db_name, 'temp')
# tourny_finder = re.compile('(\d+) (\d+)')
tourny_finder = re.compile('(\d+) (\d+)')
while True: # wait for a new hand number on stdin
new_hand_id = sys.stdin.readline()
@ -110,28 +112,32 @@ def read_stdin(): # This is the thread function
# find out if this hand is from a tournament
is_tournament = False
# (t_number, s_number) = (0, 0)
# mat_obj = tourny_finder(table_name)
(tour_number, tab_number) = (0, 0)
mat_obj = tourny_finder.search(table_name)
# if len(mat_obj.groups) == 2:
# is_tournament = True
# (t_number, s_number) = mat_obj.group(1, 2)
if mat_obj:
is_tournament = True
(tour_number, tab_number) = mat_obj.group(1, 2)
stat_dict = db_connection.get_stats_from_hand(new_hand_id)
# if a hud for this CASH table exists, just update it
if hud_dict.has_key(table_name):
# update the data for the aux_windows
for aw in hud_dict[table_name].aux_windows:
aw.update_data(new_hand_id)
update_HUD(new_hand_id, table_name, config, stat_dict)
# if a hud for this TOURNAMENT table exists, just update it
# elif hud_dict.has_key(t_number):
# update_HUD(new_hand_id, t_number, config, stat_dict)
elif hud_dict.has_key(tour_number):
update_HUD(new_hand_id, tour_number, config, stat_dict)
# otherwise create a new hud
else:
if is_tournament:
tablewindow = Tables.discover_tournament_table(config, t_number, s_number)
tablewindow = Tables.discover_tournament_table(config, tour_number, tab_number)
if tablewindow == None:
sys.stderr.write("table name "+table_name+" not found\n")
sys.stderr.write("tournament %s, table %s not found\n" % (tour_number, tab_number))
else:
create_HUD(new_hand_id, tablewindow, db_name, t_number, max, poker_game, db_connection, config, stat_dict)
create_HUD(new_hand_id, tablewindow, db_name, tour_number, max, poker_game, db_connection, config, stat_dict)
else:
tablewindow = Tables.discover_table_by_name(config, table_name)
if tablewindow == None:
@ -163,4 +169,3 @@ if __name__== "__main__":
main_window.show_all()
gtk.main()

View File

@ -59,6 +59,7 @@ class Hud:
self.stat_windows = {}
self.popup_windows = {}
self.aux_windows = []
self.font = pango.FontDescription("Sans 8")
# Set up a main window for this this instance of the HUD
@ -68,10 +69,12 @@ class Hud:
self.main_window.set_title(table.name + " FPDBHUD")
self.main_window.connect("destroy", self.kill_hud)
self.main_window.set_decorated(False)
self.main_window.set_opacity(self.colors["hudopacity"])
#self.main_window.set_transient_for(parent.get_toplevel())
self.ebox = gtk.EventBox()
self.label = gtk.Label("Right click to close HUD for %s\nor Save Stat Positions." % (table.name))
# self.label = gtk.Label("Right click to close HUD for %s\nor Save Stat Positions." % (table.name))
self.label = gtk.Label("FPDB Menu (Right Click)\nLeft-drag to move")
self.label.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse(self.colors['hudbgcolor']))
self.label.modify_fg(gtk.STATE_NORMAL, gtk.gdk.color_parse(self.colors['hudfgcolor']))
@ -111,29 +114,31 @@ class Hud:
self.main_window.set_destroy_with_parent(True)
def on_button_press(self, widget, event):
if event.button == 1:
self.main_window.begin_move_drag(event.button, int(event.x_root), int(event.y_root), event.time)
return True
if event.button == 3:
widget.popup(None, None, None, event.button, event.time)
return True
return False
def kill_hud(self, args):
def kill_hud(self, *args):
for k in self.stat_windows.keys():
self.stat_windows[k].window.destroy()
self.main_window.destroy()
self.deleted = True
def reposition_windows(self, args):
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)
def save_layout(self, *args):
new_layout = []
new_layout = [(0, 0)] * self.max
# todo: have the hud track the poker table's window position regularly, don't forget to update table.x and table.y.
for sw in self.stat_windows:
loc = self.stat_windows[sw].window.get_position()
new_loc = (loc[0] - self.table.x, loc[1] - self.table.y)
new_layout.append(new_loc)
# print new_layout
new_layout[self.stat_windows[sw].adj - 1] = new_loc
self.config.edit_layout(self.table.site, self.max, locations = new_layout)
self.config.save()
@ -177,6 +182,7 @@ class Hud:
x = x,
y = y,
seat = i,
adj = adj[i],
player_id = 'fake',
font = self.font)
@ -188,9 +194,11 @@ class Hud:
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
# self.mucked_window = gtk.Window()
# self.m = Mucked.Mucked(self.mucked_window, self.db_connection)
# self.mucked_window.show_all()
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(), config, 'fpdb')" % (aux_params['module'], aux_params['class'])))
def update(self, hand, config, stat_dict):
self.hand = hand # this is the last hand, so it is available later
@ -211,7 +219,9 @@ class Hud:
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)
# self.m.update(hand)
# for m in self.aux_windows:
# m.update_data(hand)
# m.update_gui(hand)
def topify_window(self, window):
"""Set the specified gtk window to stayontop in MS Windows."""
@ -259,7 +269,8 @@ class Stat_Window:
# This handles all callbacks from button presses on the event boxes in
# the stat windows. There is a bit of an ugly kludge to separate single-
# and double-clicks.
if event.button == 1: # left button event
if event.button == 3: # right button event
if event.type == gtk.gdk.BUTTON_PRESS: # left button single click
if self.sb_click > 0: return
self.sb_click = gobject.timeout_add(250, self.single_click, widget)
@ -270,12 +281,14 @@ class Stat_Window:
self.double_click(widget, event, *args)
if event.button == 2: # middle button event
pass
# print "middle button clicked"
if event.button == 3: # right button event
pass
# print "right button clicked"
if event.button == 1: # left button event
if event.state & gtk.gdk.SHIFT_MASK:
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 single_click(self, widget):
# Callback from the timeout in the single-click finding part of the
@ -305,10 +318,12 @@ class Stat_Window:
self.y = y + self.table.y
self.window.move(self.x, self.y)
def __init__(self, parent, game, table, seat, x, y, player_id, font):
def __init__(self, parent, game, table, seat, adj, x, y, player_id, font):
self.parent = parent # Hud object that this stat window belongs to
self.game = game # Configuration object for the curren
self.table = table # Table object where this is going
self.seat = seat # seat number of his player
self.adj = adj # the adjusted seat number for this player
self.x = x + table.x # table.x and y are the location of the table
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 ;)
@ -349,8 +364,9 @@ class Stat_Window:
# font = pango.FontDescription("Sans 8")
self.label[r][c].modify_font(font)
if not os.name == 'nt': # seems to be a bug in opacity on windows
# if not os.name == 'nt': # seems to be a bug in opacity on windows
self.window.set_opacity(parent.colors['hudopacity'])
self.window.realize
self.window.move(self.x, self.y)
self.window.show_all()
@ -457,7 +473,7 @@ class Popup_window:
self.lab.set_text(pu_text)
self.window.show_all()
self.window.set_transient_for(stat_window.main_window)
self.window.set_transient_for(stat_window.window)
# set_keep_above(1) for windows
if os.name == 'nt': self.topify_window(self.window)

View File

@ -229,14 +229,21 @@ class Sql:
sum(street3CheckCallRaiseDone) AS ccr_3,
sum(street4CheckCallRaiseChance) AS ccr_opp_4,
sum(street4CheckCallRaiseDone) AS ccr_4
FROM HudCache, Hands
WHERE HudCache.PlayerId in
(SELECT PlayerId FROM HandsPlayers
WHERE handId = %s)
AND Hands.id = %s
AND Hands.gametypeId = HudCache.gametypeId
FROM Hands
INNER JOIN HandsPlayers ON (HandsPlayers.handId = %s)
INNER JOIN HudCache ON ( HudCache.PlayerId = HandsPlayers.PlayerId+0
AND HudCache.gametypeId+0 = Hands.gametypeId+0)
WHERE Hands.id = %s
GROUP BY HudCache.PlayerId
"""
# FROM HudCache, Hands
# WHERE HudCache.PlayerId in
# (SELECT PlayerId FROM HandsPlayers
# WHERE handId = %s)
# AND Hands.id = %s
# AND Hands.gametypeId = HudCache.gametypeId
# AND PlayerId LIKE %s
# HudCache.gametypeId AS gametypeId,
# activeSeats AS n_active,

View File

@ -71,6 +71,7 @@ def do_stat(stat_dict, player = 24, stat = 'vpip'):
# functions that return individual stats
def playername(stat_dict, player):
""" Player Name."""
return (stat_dict[player]['screen_name'],
stat_dict[player]['screen_name'],
stat_dict[player]['screen_name'],
@ -98,6 +99,26 @@ def vpip(stat_dict, player):
'wtsd'
)
def vpip_0(stat_dict, player):
""" Voluntarily put $ in the pot (no decimals)."""
stat = 0.0
try:
stat = float(stat_dict[player]['vpip'])/float(stat_dict[player]['n'])
return (stat,
'%2.0f' % (100*stat) + '%',
'v=%2.0f' % (100*stat) + '%',
'vpip=%2.0f' % (100*stat) + '%',
'(%d/%d)' % (stat_dict[player]['vpip'], stat_dict[player]['n']),
'vpip'
)
except: return (stat,
'%2.0f' % (0) + '%',
'w=%2.0f' % (0) + '%',
'wtsd=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'wtsd'
)
def pfr(stat_dict, player):
""" Preflop (3rd street) raise."""
stat = 0.0
@ -119,6 +140,27 @@ def pfr(stat_dict, player):
'pfr'
)
def pfr_0(stat_dict, player):
""" Preflop (3rd street) raise (no decimals)."""
stat = 0.0
try:
stat = float(stat_dict[player]['pfr'])/float(stat_dict[player]['n'])
return (stat,
'%2.0f' % (100*stat) + '%',
'p=%2.0f' % (100*stat) + '%',
'pfr=%2.0f' % (100*stat) + '%',
'(%d/%d)' % (stat_dict[player]['pfr'], stat_dict[player]['n']),
'pfr'
)
except:
return (stat,
'%2.0f' % (0) + '%',
'p=%2.0f' % (0) + '%',
'pfr=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'pfr'
)
def wtsd(stat_dict, player):
""" Went to SD when saw flop/4th."""
stat = 0.0
@ -149,7 +191,7 @@ def wmsd(stat_dict, player):
'%3.1f' % (100*stat) + '%',
'w=%3.1f' % (100*stat) + '%',
'wmsd=%3.1f' % (100*stat) + '%',
'(%f5.0/%d)' % (stat_dict[player]['wmsd'], stat_dict[player]['sd']),
'(%5.1f/%d)' % (float(stat_dict[player]['wmsd']), stat_dict[player]['sd']),
'% won money at showdown'
)
except:
@ -415,6 +457,61 @@ def a_freq_4(stat_dict, player):
'Aggression Freq flop/4th'
)
def a_freq_123(stat_dict, player):
""" Post-Flop aggression frequency."""
stat = 0.0
try:
stat = float( stat_dict[player]['aggr_1'] + stat_dict[player]['aggr_2'] + stat_dict[player]['aggr_3']
) / float( stat_dict[player]['saw_1'] + stat_dict[player]['saw_2'] + stat_dict[player]['saw_3']);
return (stat,
'%3.1f' % (100*stat) + '%',
'afq=%3.1f' % (100*stat) + '%',
'postf_aggfq=%3.1f' % (100*stat) + '%',
'(%d/%d)' % ( stat_dict[player]['aggr_1']
+ stat_dict[player]['aggr_2']
+ stat_dict[player]['aggr_3']
, stat_dict[player]['saw_1']
+ stat_dict[player]['saw_2']
+ stat_dict[player]['saw_3']
),
'Post-Flop Aggression Freq'
)
except:
return (stat,
'%2.0f' % (0) + '%',
'a3=%2.0f' % (0) + '%',
'a_fq_3=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'Post-Flop Aggression Freq'
)
def a_freq_123_0(stat_dict, player):
""" Post-Flop aggression frequency (no decimals)."""
stat = 0.0
try:
stat = float( stat_dict[player]['aggr_1'] + stat_dict[player]['aggr_2'] + stat_dict[player]['aggr_3']) / float( stat_dict[player]['saw_1'] + stat_dict[player]['saw_2'] + stat_dict[player]['saw_3']);
return (stat,
'%2.0f' % (100*stat) + '%',
'afq=%2.0f' % (100*stat) + '%',
'postf_aggfq=%2.0f' % (100*stat) + '%',
'(%d/%d)' % ( stat_dict[player]['aggr_1']
+ stat_dict[player]['aggr_2']
+ stat_dict[player]['aggr_3']
, stat_dict[player]['saw_1']
+ stat_dict[player]['saw_2']
+ stat_dict[player]['saw_3']
),
'Post-Flop Aggression Freq'
)
except:
return (stat,
'%2.0f' % (0) + '%',
'a3=%2.0f' % (0) + '%',
'a_fq_3=%2.0f' % (0) + '%',
'(%d/%d)' % (0, 0),
'Post-Flop Aggression Freq'
)
def cb_1(stat_dict, player):
""" Flop continuation bet."""
stat = 0.0
@ -591,7 +688,9 @@ if __name__== "__main__":
for player in stat_dict.keys():
print "player = ", player, do_stat(stat_dict, player = player, stat = 'vpip')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'vpip_0')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'pfr')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'pfr_0')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'wtsd')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'saw_f')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'n')
@ -606,6 +705,8 @@ if __name__== "__main__":
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_2')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_3')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_4')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_123')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'a_freq_123_0')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_1')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_2')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'cb_3')
@ -614,6 +715,7 @@ if __name__== "__main__":
print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_2')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_3')
print "player = ", player, do_stat(stat_dict, player = player, stat = 'ffreq_4')
print "\n"
print "\n\nLegal stats:"
for attr in dir():
@ -621,8 +723,8 @@ if __name__== "__main__":
if attr in ("Configuration", "Database", "GInitiallyUnowned", "gtk", "pygtk",
"player", "c", "db_connection", "do_stat", "do_tip", "stat_dict",
"h"): continue
print attr, eval("%s.__doc__" % (attr))
print "%-14s %s" % (attr, eval("%s.__doc__" % (attr)))
# print " <pu_stat pu_stat_name = \"%s\"> </pu_stat>" % (attr)
db_connection.close
db_connection.close_connection

0
pyfpdb/fpdb.py Executable file → Normal file
View File

0
pyfpdb/fpdb_db.py Executable file → Normal file
View File

38
pyfpdb/fpdb_import.py Executable file → Normal file
View File

@ -41,23 +41,22 @@ from time import time
class Importer:
def __init__(self, caller, settings):
def __init__(self, caller, settings, config):
"""Constructor"""
self.settings=settings
self.caller=caller
self.config = config
self.db = None
self.cursor = None
self.filelist = {}
self.dirlist = {}
self.monitor = False
self.updated = {} #Time last import was run {file:mtime}
self.callHud = False
self.lines = None
self.faobs = None #File as one big string
self.pos_in_file = {} # dict to remember how far we have read in the file
#Set defaults
if not self.settings.has_key('imp-callFpdbHud'):
self.settings['imp-callFpdbHud'] = False
self.callHud = self.config.get_import_parameters().get("callFpdbHud")
if not self.settings.has_key('minPrint'):
self.settings['minPrint'] = 30
self.dbConnect()
@ -115,6 +114,7 @@ class Importer:
#dirlist is a hash of lists:
#dirlist{ 'PokerStars' => ["/path/to/import/", "filtername"] }
def addImportDirectory(self, dir, monitor = False, site = "default", filter = "passthrough"):
if dir != "/dev/null" and dir.lower() != "none":
if os.path.isdir(dir):
if monitor == True:
self.monitor = True
@ -123,12 +123,12 @@ class Importer:
for file in os.listdir(dir):
self.addImportFile(os.path.join(dir, file), site, filter)
else:
print "Warning: Attempted to add: '" + str(dir) + "' as an import directory"
print "Warning: Attempted to add: '" + str(dir) + "' as an import directory\n"
#Run full import on filelist
def runImport(self):
for file in self.filelist:
self.import_file_dict(file)
self.import_file_dict(file, self.filelist[file][0], self.filelist[file][1])
#Run import on updated files, then store latest update time.
def runUpdated(self):
@ -143,17 +143,25 @@ class Importer:
try:
lastupdate = self.updated[file]
if stat_info.st_mtime > lastupdate:
self.import_file_dict(file)
self.import_file_dict(file, self.filelist[file][0], self.filelist[file][1])
self.updated[file] = time()
except:
self.updated[file] = time()
# This codepath only runs first time the file is found, if modified in the last
# minute run an immediate import.
if (time() - stat_info.st_mtime) < 60:
self.import_file_dict(file)
self.import_file_dict(file, self.filelist[file][0], self.filelist[file][1])
# This is now an internal function that should not be called directly.
def import_file_dict(self, file):
def import_file_dict(self, file, site, filter):
if(filter == "passthrough"):
self.import_fpdb_file(file, site)
else:
#Load filter, and run filtered file though main importer
self.import_fpdb_file(file, site)
def import_fpdb_file(self, file, site):
starttime = time()
last_read_hand=0
loc = 0
@ -170,7 +178,11 @@ class Importer:
self.pos_in_file[file] = inputFile.tell()
inputFile.close()
try: # sometimes we seem to be getting an empty self.lines, in which case, we just want to return.
firstline = self.lines[0]
except:
# print "import_fpdb_file", file, site, self.lines, "\n"
return
if firstline.find("Tournament Summary")!=-1:
print "TODO: implement importing tournament summaries"
@ -229,8 +241,7 @@ class Importer:
stored+=1
self.db.commit()
# if settings['imp-callFpdbHud'] and self.callHud and os.sep=='/':
if self.settings['imp-callFpdbHud'] and self.callHud:
if self.callHud:
#print "call to HUD here. handsId:",handsId
#pipe the Hands.id out to the HUD
self.caller.pipe_to_hud.stdin.write("%s" % (handsId) + os.linesep)
@ -261,10 +272,11 @@ class Importer:
if ((stored+duplicates+partial+errors)>=self.settings['handCount']):
if (not self.settings['quiet']):
print "quitting due to reaching the amount of hands to be imported"
print "Total stored:", stored, "duplicates:", duplicates, "partial/damaged:", partial, "errors:", errors, " time:", (time() - starttime)
print "Total stored:", stored, "duplicates:", duplicates, "partial/damaged:",
partial, "errors:", errors, " time: %5.3f" % (time() - starttime)
sys.exit(0)
startpos=endpos
print "Total stored:", stored, "duplicates:", duplicates, "partial:", partial, "errors:", errors, " time:", (time() - starttime)
print "Total stored:", stored, "duplicates:", duplicates, "partial:", partial, "errors:", errors, " time: %5.3f" % (time() - starttime)
if stored==0:
if duplicates>0:

View File

@ -46,7 +46,7 @@ def mainParser(db, cursor, site, category, hand):
#print "found small blind line:",smallBlindLine
break
#print "small blind line:",smallBlindLine
gametypeID=fpdb_simple.recogniseGametypeID(cursor, hand[0], hand[smallBlindLine], siteID, category, isTourney)
gametypeID=fpdb_simple.recogniseGametypeID(db, cursor, hand[0], hand[smallBlindLine], siteID, category, isTourney)
if isTourney:
if site!="ps":
raise fpdb_simple.FpdbError("tourneys are only supported on PS right now")
@ -142,18 +142,18 @@ def mainParser(db, cursor, site, category, hand):
payin_amounts=fpdb_simple.calcPayin(len(names), buyin, fee)
if base=="hold":
result = fpdb_save_to_db.tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteID,
result = fpdb_save_to_db.tourney_holdem_omaha(db, cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteID,
siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, positions, cardValues, cardSuits, boardValues, boardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos)
elif base=="stud":
result = fpdb_save_to_db.tourney_stud(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteID,
result = fpdb_save_to_db.tourney_stud(db, cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteID,
siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, antes, cardValues, cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos)
else:
raise fpdb_simple.FpdbError ("unrecognised category")
else:
if base=="hold":
result = fpdb_save_to_db.ring_holdem_omaha(cursor, base, category, siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, positions, cardValues, cardSuits, boardValues, boardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos)
result = fpdb_save_to_db.ring_holdem_omaha(db, cursor, base, category, siteHandNo, gametypeID, handStartTime, names, playerIDs, startCashes, positions, cardValues, cardSuits, boardValues, boardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos)
elif base=="stud":
result = fpdb_save_to_db.ring_stud(cursor, base, category, siteHandNo, gametypeID,
result = fpdb_save_to_db.ring_stud(db, cursor, base, category, siteHandNo, gametypeID,
handStartTime, names, playerIDs, startCashes, antes, cardValues,
cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos)
else:

View File

@ -21,13 +21,13 @@
import fpdb_simple
#stores a stud/razz hand into the database
def ring_stud(cursor, base, category, site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, antes, card_values, card_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
def ring_stud(db, cursor, base, category, site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, antes, card_values, card_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits)
hands_id=fpdb_simple.storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats)
hands_id=fpdb_simple.storeHands(db, cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats)
#print "before calling store_hands_players_stud, antes:", antes
hands_players_ids=fpdb_simple.store_hands_players_stud(cursor, hands_id, player_ids,
hands_players_ids=fpdb_simple.store_hands_players_stud(db, cursor, hands_id, player_ids,
start_cashes, antes, card_values, card_suits, winnings, rakes, seatNos)
fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData)
@ -36,14 +36,14 @@ def ring_stud(cursor, base, category, site_hand_no, gametype_id, hand_start_time
return hands_id
#end def ring_stud
def ring_holdem_omaha(cursor, base, category, site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, positions, card_values, card_suits, board_values, board_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
def ring_holdem_omaha(db, cursor, base, category, site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, positions, card_values, card_suits, board_values, board_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
"""stores a holdem/omaha hand into the database"""
fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits)
fpdb_simple.fill_board_cards(board_values, board_suits)
hands_id=fpdb_simple.storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats)
hands_id=fpdb_simple.storeHands(db, cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats)
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos)
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha(db, cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos)
fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData)
@ -53,7 +53,7 @@ def ring_holdem_omaha(cursor, base, category, site_hand_no, gametype_id, hand_st
return hands_id
#end def ring_holdem_omaha
def tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourney_start, payin_amounts, ranks, tourneyTypeId, siteId, #end of tourney specific params
def tourney_holdem_omaha(db, cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourney_start, payin_amounts, ranks, tourneyTypeId, siteId, #end of tourney specific params
site_hand_no, gametype_id, hand_start_time, names, player_ids, start_cashes, positions, card_values, card_suits, board_values, board_suits, winnings, rakes, action_types, allIns, action_amounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
"""stores a tourney holdem/omaha hand into the database"""
fpdb_simple.fillCardArrays(len(names), base, category, card_values, card_suits)
@ -62,9 +62,9 @@ def tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knoc
tourney_id=fpdb_simple.store_tourneys(cursor, tourneyTypeId, siteTourneyNo, entries, prizepool, tourney_start)
tourneys_players_ids=fpdb_simple.store_tourneys_players(cursor, tourney_id, player_ids, payin_amounts, ranks, winnings)
hands_id=fpdb_simple.storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats)
hands_id=fpdb_simple.storeHands(db, cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats)
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha_tourney(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids)
hands_players_ids=fpdb_simple.store_hands_players_holdem_omaha_tourney(db, cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids)
fpdb_simple.storeHudCache(cursor, base, category, gametype_id, player_ids, hudImportData)
@ -74,7 +74,7 @@ def tourney_holdem_omaha(cursor, base, category, siteTourneyNo, buyin, fee, knoc
return hands_id
#end def tourney_holdem_omaha
def tourney_stud(cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteId,
def tourney_stud(db, cursor, base, category, siteTourneyNo, buyin, fee, knockout, entries, prizepool, tourneyStartTime, payin_amounts, ranks, tourneyTypeId, siteId,
siteHandNo, gametypeId, handStartTime, names, playerIds, startCashes, antes, cardValues, cardSuits, winnings, rakes, actionTypes, allIns, actionAmounts, actionNos, hudImportData, maxSeats, tableName, seatNos):
#stores a tourney stud/razz hand into the database
fpdb_simple.fillCardArrays(len(names), base, category, cardValues, cardSuits)
@ -83,9 +83,9 @@ def tourney_stud(cursor, base, category, siteTourneyNo, buyin, fee, knockout, en
tourneys_players_ids=fpdb_simple.store_tourneys_players(cursor, tourney_id, playerIds, payin_amounts, ranks, winnings)
hands_id=fpdb_simple.storeHands(cursor, siteHandNo, gametypeId, handStartTime, names, tableName, maxSeats)
hands_id=fpdb_simple.storeHands(db, cursor, siteHandNo, gametypeId, handStartTime, names, tableName, maxSeats)
hands_players_ids=fpdb_simple.store_hands_players_stud_tourney(cursor, hands_id, playerIds, startCashes, antes, cardValues, cardSuits, winnings, rakes, seatNos, tourneys_players_ids)
hands_players_ids=fpdb_simple.store_hands_players_stud_tourney(db, cursor, hands_id, playerIds, startCashes, antes, cardValues, cardSuits, winnings, rakes, seatNos, tourneys_players_ids)
fpdb_simple.storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData)

View File

@ -484,6 +484,7 @@ def isActionLine(line):
#returns whether this is a duplicate
def isAlreadyInDB(cursor, gametypeID, siteHandNo):
#print "isAlreadyInDB gtid,shand:",gametypeID, siteHandNo
cursor.execute ("SELECT id FROM Hands WHERE gametypeId=%s AND siteHandNo=%s", (gametypeID, siteHandNo))
result=cursor.fetchall()
if (len(result)>=1):
@ -1021,7 +1022,7 @@ def recogniseCategory(line):
#end def recogniseCategory
#returns the int for the gametype_id for the given line
def recogniseGametypeID(cursor, topline, smallBlindLine, site_id, category, isTourney):#todo: this method is messy
def recogniseGametypeID(db, cursor, topline, smallBlindLine, site_id, category, isTourney):#todo: this method is messy
#if (topline.find("HORSE")!=-1):
# raise FpdbError("recogniseGametypeID: HORSE is not yet supported.")
@ -1072,6 +1073,9 @@ def recogniseGametypeID(cursor, topline, smallBlindLine, site_id, category, isTo
else:
cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet))
result=cursor.fetchone()
#print "recgt1 result=",result
#ret=result[0]
#print "recgt1 ret=",ret
#print "tried SELECTing gametypes.id, result:",result
try:
@ -1105,16 +1109,18 @@ def recogniseGametypeID(cursor, topline, smallBlindLine, site_id, category, isTo
cursor.execute("""INSERT INTO Gametypes
(siteId, type, base, category, limitType, hiLo, smallBlind, bigBlind, smallBet, bigBet)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (site_id, type, base, category, limit_type, hiLo, small_blind, big_blind, small_bet, big_bet))
cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBet=%s AND bigBet=%s", (site_id, type, category, limit_type, small_bet, big_bet))
#cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBet=%s AND bigBet=%s", (site_id, type, category, limit_type, small_bet, big_bet))
else:
cursor.execute("""INSERT INTO Gametypes
(siteId, type, base, category, limitType, hiLo, smallBlind, bigBlind, smallBet, bigBet)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""", (site_id, type, base, category, limit_type, hiLo, small_bet, big_bet, 0, 0))#remember, for these bet means blind
cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet))
#cursor.execute ("SELECT id FROM Gametypes WHERE siteId=%s AND type=%s AND category=%s AND limitType=%s AND smallBlind=%s AND bigBlind=%s", (site_id, type, category, limit_type, small_bet, big_bet))
result=cursor.fetchone()
result=(db.insert_id(),)
#print "recgt2 result=",result
#print "created new gametypes.id:",result
#print "recgt3: result=", result
return result[0]
#end def recogniseGametypeID
@ -1248,15 +1254,16 @@ def store_board_cards(cursor, hands_id, board_values, board_suits):
board_values[4], board_suits[4]))
#end def store_board_cards
def storeHands(cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats):
def storeHands(db, cursor, site_hand_no, gametype_id, hand_start_time, names, tableName, maxSeats):
#stores into table hands
cursor.execute ("INSERT INTO Hands (siteHandNo, gametypeId, handStart, seats, tableName, importTime, maxSeats) VALUES (%s, %s, %s, %s, %s, %s, %s)", (site_hand_no, gametype_id, hand_start_time, len(names), tableName, datetime.datetime.today(), maxSeats))
#todo: find a better way of doing this...
cursor.execute("SELECT id FROM Hands WHERE siteHandNo=%s AND gametypeId=%s", (site_hand_no, gametype_id))
return cursor.fetchall()[0][0]
#cursor.execute("SELECT id FROM Hands WHERE siteHandNo=%s AND gametypeId=%s", (site_hand_no, gametype_id))
#return cursor.fetchall()[0][0]
return db.insert_id() # mysql only
#end def storeHands
def store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos):
def store_hands_players_holdem_omaha(db, cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos):
result=[]
if (category=="holdem"):
for i in range (len(player_ids)):
@ -1268,8 +1275,9 @@ def store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, sta
(hands_id, player_ids[i], start_cashes[i], positions[i],
card_values[i][0], card_suits[i][0], card_values[i][1], card_suits[i][1],
winnings[i], rakes[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0])
#cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
#result.append(cursor.fetchall()[0][0])
result.append( db.insert_id() ) # mysql only
elif (category=="omahahi" or category=="omahahilo"):
for i in range (len(player_ids)):
cursor.execute ("""INSERT INTO HandsPlayers
@ -1281,14 +1289,15 @@ def store_hands_players_holdem_omaha(cursor, category, hands_id, player_ids, sta
card_values[i][0], card_suits[i][0], card_values[i][1], card_suits[i][1],
card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3],
winnings[i], rakes[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0])
#cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
#result.append(cursor.fetchall()[0][0])
result.append( db.insert_id() ) # mysql only
else:
raise FpdbError("invalid category")
return result
#end def store_hands_players_holdem_omaha
def store_hands_players_stud(cursor, hands_id, player_ids, start_cashes, antes,
def store_hands_players_stud(db, cursor, hands_id, player_ids, start_cashes, antes,
card_values, card_suits, winnings, rakes, seatNos):
#stores hands_players rows for stud/razz games. returns an array of the resulting IDs
result=[]
@ -1307,12 +1316,14 @@ def store_hands_players_stud(cursor, hands_id, player_ids, start_cashes, antes,
card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3],
card_values[i][4], card_suits[i][4], card_values[i][5], card_suits[i][5],
card_values[i][6], card_suits[i][6], winnings[i], rakes[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0])
#cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
#result.append(cursor.fetchall()[0][0])
result.append( db.insert_id() ) # mysql only
return result
#end def store_hands_players_stud
def store_hands_players_holdem_omaha_tourney(cursor, category, hands_id, player_ids, start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids):
def store_hands_players_holdem_omaha_tourney(db, cursor, category, hands_id, player_ids,
start_cashes, positions, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids):
#stores hands_players for tourney holdem/omaha hands
result=[]
for i in range (len(player_ids)):
@ -1338,13 +1349,14 @@ def store_hands_players_holdem_omaha_tourney(cursor, category, hands_id, player_
winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i]))
else:
raise FpdbError ("invalid card_values length:"+str(len(card_values[0])))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0])
#cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
#result.append(cursor.fetchall()[0][0])
result.append( db.insert_id() ) # mysql only
return result
#end def store_hands_players_holdem_omaha_tourney
def store_hands_players_stud_tourney(cursor, hands_id, player_ids, start_cashes,
def store_hands_players_stud_tourney(db, cursor, hands_id, player_ids, start_cashes,
antes, card_values, card_suits, winnings, rakes, seatNos, tourneys_players_ids):
#stores hands_players for tourney stud/razz hands
result=[]
@ -1362,8 +1374,9 @@ def store_hands_players_stud_tourney(cursor, hands_id, player_ids, start_cashes,
card_values[i][2], card_suits[i][2], card_values[i][3], card_suits[i][3],
card_values[i][4], card_suits[i][4], card_values[i][5], card_suits[i][5],
card_values[i][6], card_suits[i][6], winnings[i], rakes[i], tourneys_players_ids[i], seatNos[i]))
cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId=%s", (hands_id, player_ids[i]))
result.append(cursor.fetchall()[0][0])
#cursor.execute("SELECT id FROM HandsPlayers WHERE handId=%s AND playerId+0=%s", (hands_id, player_ids[i]))
#result.append(cursor.fetchall()[0][0])
result.append( db.insert_id() ) # mysql only
return result
#end def store_hands_players_stud_tourney
@ -1949,9 +1962,9 @@ def storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData):
for player in range (len(playerIds)):
if base=="hold":
cursor.execute("SELECT * FROM HudCache WHERE gametypeId=%s AND playerId=%s AND activeSeats=%s AND position=%s", (gametypeId, playerIds[player], len(playerIds), hudImportData['position'][player]))
cursor.execute("SELECT * FROM HudCache WHERE gametypeId+0=%s AND playerId=%s AND activeSeats=%s AND position=%s", (gametypeId, playerIds[player], len(playerIds), hudImportData['position'][player]))
else:
cursor.execute("SELECT * FROM HudCache WHERE gametypeId=%s AND playerId=%s AND activeSeats=%s", (gametypeId, playerIds[player], len(playerIds)))
cursor.execute("SELECT * FROM HudCache WHERE gametypeId+0=%s AND playerId=%s AND activeSeats=%s", (gametypeId, playerIds[player], len(playerIds)))
row=cursor.fetchone()
#print "gametypeId:", gametypeId, "playerIds[player]",playerIds[player], "len(playerIds):",len(playerIds), "row:",row
@ -2097,7 +2110,7 @@ def storeHudCache(cursor, base, category, gametypeId, playerIds, hudImportData):
#end def storeHudCache
def store_tourneys(cursor, tourneyTypeId, siteTourneyNo, entries, prizepool, startTime):
cursor.execute("SELECT id FROM Tourneys WHERE siteTourneyNo=%s AND tourneyTypeId=%s", (siteTourneyNo, tourneyTypeId))
cursor.execute("SELECT id FROM Tourneys WHERE siteTourneyNo=%s AND tourneyTypeId+0=%s", (siteTourneyNo, tourneyTypeId))
tmp=cursor.fetchone()
#print "tried SELECTing tourneys.id, result:",tmp
@ -2107,7 +2120,7 @@ def store_tourneys(cursor, tourneyTypeId, siteTourneyNo, entries, prizepool, sta
cursor.execute("""INSERT INTO Tourneys
(tourneyTypeId, siteTourneyNo, entries, prizepool, startTime)
VALUES (%s, %s, %s, %s, %s)""", (tourneyTypeId, siteTourneyNo, entries, prizepool, startTime))
cursor.execute("SELECT id FROM Tourneys WHERE siteTourneyNo=%s AND tourneyTypeId=%s", (siteTourneyNo, tourneyTypeId))
cursor.execute("SELECT id FROM Tourneys WHERE siteTourneyNo=%s AND tourneyTypeId+0=%s", (siteTourneyNo, tourneyTypeId))
tmp=cursor.fetchone()
#print "created new tourneys.id:",tmp
return tmp[0]
@ -2121,7 +2134,7 @@ def store_tourneys_players(cursor, tourney_id, player_ids, payin_amounts, ranks,
#print "ranks:",ranks
#print "winnings:",winnings
for i in range (len(player_ids)):
cursor.execute("SELECT id FROM TourneysPlayers WHERE tourneyId=%s AND playerId=%s", (tourney_id, player_ids[i]))
cursor.execute("SELECT id FROM TourneysPlayers WHERE tourneyId=%s AND playerId+0=%s", (tourney_id, player_ids[i]))
tmp=cursor.fetchone()
#print "tried SELECTing tourneys_players.id:",tmp
@ -2132,7 +2145,7 @@ def store_tourneys_players(cursor, tourney_id, player_ids, payin_amounts, ranks,
(tourneyId, playerId, payinAmount, rank, winnings) VALUES (%s, %s, %s, %s, %s)""",
(tourney_id, player_ids[i], payin_amounts[i], ranks[i], winnings[i]))
cursor.execute("SELECT id FROM TourneysPlayers WHERE tourneyId=%s AND playerId=%s",
cursor.execute("SELECT id FROM TourneysPlayers WHERE tourneyId=%s AND playerId+0=%s",
(tourney_id, player_ids[i]))
tmp=cursor.fetchone()
#print "created new tourneys_players.id:",tmp