# -*- encoding: utf-8 -*- clr.AddReference("System.IO") from System.IO import * clr.AddReference("SpreadsheetLight") from SpreadsheetLight import SLDocument from datetime import datetime from collections import defaultdict class PadelHelper: def __init__(self): pass def GetPlayers(self, team): backhand = None drive = None for player in team.InPlay: if player.Function.ToString() == "Backhand": backhand = player elif player.Function.ToString() == "Drive": drive = player if not backhand: Core.StatusManager.Add(team.ShortName + " doesn't have Backhand player") if not drive: Core.StatusManager.Add(team.ShortName + " doesn't have Drive player") if not backhand or not drive: return None, None else: return backhand, drive def GetCountryFlag(self, countryInitials): filePath = ProjectSettings["ImagesFolderPath"] + "\\Flags\\" + countryInitials + ".png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetSponsors(self, projectSettings, folder, sponsorNumber, render=""): filePath = projectSettings["ImagesFolderPath"] + "\\Sponsors\\" + folder + "\\" if render == "GLOBAL": filePath = projectSettings["ImagesFolderPath"] + "\\Sponsors\\" + folder + "\\GLOBAL\\" if render == "RESTRICTED": filePath = projectSettings["ImagesFolderPath"] + "\\Sponsors\\" + folder + "\\RESTRICTED\\" if not Directory.Exists(filePath): return (False, "", "Directory '{}' does not exist".format(filePath)) files = Directory.GetFiles(filePath) for f in files: fileName = Path.GetFileName(f) if fileName.startswith(sponsorNumber): return (True, f, "") return (False, "", "Image with number '{}' not found in folder '{}'".format(sponsorNumber, filePath)) def GetTournamentBadge(self): filePath = ProjectSettings["ImagesFolderPath"] + "\\CompetitionBadges\\competition_badge_worldChamp.png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetTournamenticon(self): filePath = ProjectSettings["ImagesFolderPath"] + "\\CompetitionBadges\\competitionlogo_World.png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetTimelineSponsor(self): filePath = ProjectSettings["ImagesFolderPath"] + "\\Sponsors_Timeline\\sponsorTimeline.png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetTimelineCompetitionLogo(self): filePath = ProjectSettings["ImagesFolderPath"] + "\\vaz.png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetSponsor(self): filePath = ProjectSettings["ImagesFolderPath"] + "\\Sponsors\\sponsor.png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetOnlineSponsor(self): filePath = ProjectSettings["ImagesFolderPath"] + "\\Sponsors\\sponsor_online.png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetPhoto(self, officialname): filePath = ProjectSettings["ImagesFolderPath"] + "\\Photos\\" + officialname + ".webp" if not File.Exists(filePath): filePath = ProjectSettings["ImagesFolderPath"] + "\\Photos\\" + officialname + ".png" if not File.Exists(filePath): return ProjectSettings["ImagesFolderPath"] + "\\empty.png" return filePath.Replace("\\", "/") def GetPhotoTeam(self, officialname, teamFolder): imagesFolder = ProjectSettings["ImagesFolderPath"] folderPath = imagesFolder + "\\Photos\\" + teamFolder filePath = folderPath + "\\" + officialname + ".webp" logPath = Path.GetTempPath() + "PadelHelper_photos.log" try: logText = "GetPhotoTeam | name={0} | teamFolder={1} | imagesFolder={2} | candidate={3} | exists={4}".format( officialname, teamFolder, imagesFolder, filePath, File.Exists(filePath) ) if Directory.Exists(folderPath): fileNames = [Path.GetFileName(f) for f in Directory.GetFiles(folderPath)] logText += " | folderFiles=" + ", ".join(fileNames) else: logText += " | folderExists=False" File.AppendAllText(logPath, logText + "\r\n") except Exception as ex: File.AppendAllText(logPath, "GetPhotoTeam logging error: " + str(ex) + "\r\n") if not File.Exists(filePath): return imagesFolder + "\\empty.png" return filePath.Replace("\\", "/") def GetIcon(self, refname): dirPath = ProjectSettings["ImagesFolderPath"] + "\\Icons\\" filePath = Path.Combine(dirPath, refname + ".png") if not File.Exists(filePath): dirPath = ProjectSettings["ImagesFolderPath"] + "\\" filePath = Path.Combine(dirPath, "empty.png") return filePath.Replace("\\", "/") def GetAdvert(self, refname, engine): filePath = ProjectSettings["ImagesFolderPath"] + "\\Adverts\\" + engine + "\\" + refname + ".png" if not File.Exists(filePath): return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png" return True, filePath.Replace("\\", "/") def GetVirtual(self, refname, engine): filePath = ProjectSettings["ImagesFolderPath"] + "\\Virtuals\\" + engine + "\\" + refname + ".png" if not File.Exists(filePath): return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png" return True, filePath.Replace("\\", "/") def GetSceneName(self, sceneFullName): last_slash_index = sceneFullName.rfind("/") if last_slash_index != -1: text_after_last_slash = sceneFullName[last_slash_index + 1:] else: text_after_last_slash = sceneFullName return text_after_last_slash def GetBanner(self, refname, engine): filePath = ProjectSettings["ImagesFolderPath"] + "\\Banners\\" + engine + "\\" + refname + ".png" if not File.Exists(filePath): return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png" return True, filePath.Replace("\\", "/") def GetSpecial(self, refname, engine): filePath = ProjectSettings["ImagesFolderPath"] + "\\Special_Scenes\\" + engine + "\\" + refname + ".png" if not File.Exists(filePath): return False, ProjectSettings["ImagesFolderPath"] + "\\empty.png" return True, filePath.Replace("\\", "/") def GetCountryNameAndInitials(self, verify=False): homeCountry = ActiveObjects.HomeTeam.Attributes["COUNTRY"].Value if ActiveObjects.HomeTeam.Attributes["COUNTRY"] else "" awayCountry = ActiveObjects.AwayTeam.Attributes["COUNTRY"].Value if ActiveObjects.AwayTeam.Attributes["COUNTRY"] else "" homeCountryInitials = ActiveObjects.HomeTeam.Attributes["COUNTRY INITIALS"].Value if ActiveObjects.HomeTeam.Attributes["COUNTRY INITIALS"] else "" awayCountryInitials = ActiveObjects.AwayTeam.Attributes["COUNTRY INITIALS"].Value if ActiveObjects.AwayTeam.Attributes["COUNTRY INITIALS"] else "" if verify: verifyCountry = [] if not homeCountry: verifyCountry.append("#Please Fill Home Country parameter") if not awayCountry: verifyCountry.append("#Please Fill Away Country parameter") if not homeCountryInitials: verifyCountry.append("#Please Fill Home Country Initials parameter") if not awayCountryInitials: verifyCountry.append("#Please Fill Away Country Initials parameter") if len(verifyCountry) > 0: Core.StatusManager.Add("\n".join(verifyCountry)) return False else: return True return (homeCountry, homeCountryInitials, awayCountry, awayCountryInitials) def GetStandingsXlsxData(self, type): group = Globals["frmController"].Controls["cmbGroup"].Text filePath = ProjectSettings["Excels Path"] + "\\PadelGames.xlsx" sheet = "%s_Group_%s" % (type, group) ws = SLDocument(filePath, sheet) NRows = ws.GetWorksheetStatistics().EndRowIndex - 1 matches = [] # ===================================================== # FUNCAO AUXILIAR PARA CONVERTER VALORES NUMERICOS # ===================================================== def safeInt(value, default=0): try: value = str(value).strip() if value == "": return default return int(value) except: return default # ===================================================== # LER OS JOGOS DO EXCEL # ===================================================== for i in range(NRows): if ws.GetCellValueAsString(i + 2, 1): confronto = ws.GetCellValueAsString(i + 2, 1).Trim() game = ws.GetCellValueAsString(i + 2, 2).ToString() hometeam = ws.GetCellValueAsString(i + 2, 3).Trim() hometeamInitials = ws.GetCellValueAsString(i + 2, 4).Trim() hometeamSetsWin = ws.GetCellValueAsString(i + 2, 5).Trim() orderHomeRaw = ws.GetCellValueAsString(i + 2, 6).Trim() orderAwayRaw = ws.GetCellValueAsString(i + 2, 7).Trim() awayteamSetsWin = ws.GetCellValueAsString(i + 2, 8).Trim() awayteam = ws.GetCellValueAsString(i + 2, 9).Trim() awayteamInitials = ws.GetCellValueAsString(i + 2, 10).Trim() homeParticipants = ws.GetCellValueAsString(i + 2, 11).Trim().split("|") awayParticipants = ws.GetCellValueAsString(i + 2, 12).Trim().split("|") # Converter ordens manuais para numeros orderHome = None orderAway = None if orderHomeRaw != "": try: orderHome = int(orderHomeRaw) except: orderHome = None if orderAwayRaw != "": try: orderAway = int(orderAwayRaw) except: orderAway = None # Converter sets vazios para zero homeSetsValue = safeInt(hometeamSetsWin) awaySetsValue = safeInt(awayteamSetsWin) # Determinar vencedor do jogo confrontoWin = None if homeSetsValue > awaySetsValue and homeSetsValue >= 2: confrontoWin = hometeam elif awaySetsValue > homeSetsValue and awaySetsValue >= 2: confrontoWin = awayteam matches.append([ confronto, game, hometeam, hometeamInitials, homeSetsValue, awayteam, awaySetsValue, awayteamInitials, confrontoWin, homeParticipants, awayParticipants, orderHome, orderAway ]) # ===================================================== # ESTRUTURA DE DADOS DAS ESTATISTICAS # ===================================================== stats = defaultdict(lambda: { 'initials': None, 'sets_won': 0, 'sets_lost': 0, 'matches_won': 0, 'matches_lost': 0, 'points': 0, 'games_played': 0, 'home_participants': None, 'away_participants': None, 'order': None }) # ===================================================== # AGRUPAR OS JOGOS POR CONFRONTO # ===================================================== confrontos = defaultdict(list) for match in matches: confronto = match[0] confrontos[confronto].append(match) # ===================================================== # PROCESSAR CADA CONFRONTO # ===================================================== for confronto, games in confrontos.items(): for game in games: ( _, date_str, home_team, home_initials, home_sets, away_team, away_sets, away_initials, winner, homeParticipants, awayParticipants, orderHome, orderAway ) = game # Garantir que os sets sao sempre numeros home_sets = safeInt(home_sets) away_sets = safeInt(away_sets) stats[home_team]['home_participants'] = homeParticipants stats[away_team]['away_participants'] = awayParticipants stats[home_team]['initials'] = home_initials stats[away_team]['initials'] = away_initials # Guardar a ordem manual, quando existe if orderHome is not None: stats[home_team]['order'] = orderHome if orderAway is not None: stats[away_team]['order'] = orderAway # Atualizar jogos jogados if home_sets > 0 or away_sets > 0: stats[home_team]['games_played'] += 1 stats[away_team]['games_played'] += 1 # Atualizar sets ganhos e perdidos stats[home_team]['sets_won'] += home_sets stats[home_team]['sets_lost'] += away_sets stats[away_team]['sets_won'] += away_sets stats[away_team]['sets_lost'] += home_sets # ================================================= # ATUALIZAR PARTIDAS GANHAS, PERDIDAS E PONTOS # VITORIA = 2 PONTOS # DERROTA = 1 PONTO # ================================================= if winner is not None: if winner == home_team: stats[home_team]['matches_won'] += 1 stats[away_team]['matches_lost'] += 1 stats[home_team]['points'] += 2 stats[away_team]['points'] += 1 elif winner == away_team: stats[away_team]['matches_won'] += 1 stats[home_team]['matches_lost'] += 1 stats[away_team]['points'] += 2 stats[home_team]['points'] += 1 # ===================================================== # VERIFICAR SE TODAS AS EQUIPAS TEM ORDEM MANUAL # ===================================================== hasOrder = True for team, stat in stats.items(): if stat['order'] is None or stat['order'] <= 0: hasOrder = False break # ===================================================== # ORDENAR A CLASSIFICACAO # ===================================================== if hasOrder: sorted_stats = sorted( stats.items(), key=lambda x: x[1]['order'] ) else: sorted_stats = sorted( stats.items(), key=lambda x: ( x[1]['points'], x[1]['matches_won'], x[1]['sets_won'] - x[1]['sets_lost'], x[1]['sets_won'] ), reverse=True ) return sorted_stats, confrontos def Run(): Globals["PadelHelper"] = PadelHelper()