past season standings with -s flag

This commit is contained in:
Sakimori 2021-01-15 20:15:52 -05:00
parent c4b4af2322
commit 797e0da931
3 changed files with 131 additions and 16 deletions

View File

@ -21,6 +21,23 @@ def create_connection(league_name):
print("oops, db connection no work")
return conn
def create_season_connection(league_name, season_num):
#create connection, create db if doesn't exist
conn = None
try:
if not os.path.exists(os.path.join(data_dir, league_dir, league_name)):
os.makedirs(os.path.join(data_dir, league_dir, league_name))
conn = sql.connect(os.path.join(data_dir, league_dir, league_name, season_num, f"{league_name}.db"))
# enable write-ahead log for performance and resilience
conn.execute('pragma journal_mode=wal')
return conn
except:
print("oops, db connection no work")
return conn
def state(league_name):
if not os.path.exists(os.path.dirname(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state"))):
os.makedirs(os.path.dirname(os.path.join(data_dir, league_dir, league_name, f"{league_name}.state")))
@ -87,7 +104,7 @@ def save_league(league):
"series_length" : league.series_length,
"games_per_hour" : league.games_per_hour,
"owner" : league.owner,
"champions" : league.champions,
"champion" : league.champion,
"historic" : league.historic
}
with open(os.path.join(data_dir, league_dir, league.name, f"{league.name}.state"), "w") as state_file:
@ -138,11 +155,49 @@ def get_standings(league_name):
conn.close()
return standings_array
def season_save(league):
if league_exists(league.name):
seasons = 1
with os.scandir(os.path.join(data_dir, league_dir, league.name)) as folder:
for item in folder:
if "." not in item.name:
seasons += 1
new_dir = os.path.join(data_dir, league_dir, league.name, str(seasons))
os.makedirs(new_dir)
with os.scandir(os.path.join(data_dir, league_dir, league.name)) as folder:
for item in folder:
if "." in item.name:
os.rename(os.path.join(data_dir, league_dir, league.name, item.name), os.path.join(new_dir, item.name))
def get_past_standings(league_name, season_num):
if league_exists(league_name):
with os.scandir(os.path.join(data_dir, league_dir, league_name)) as folder:
for item in folder:
if item.name == str(season_num):
conn = create_season_connection(league_name, str(item.name))
if conn is not None:
c = conn.cursor()
c.execute("SELECT name, wins, losses, run_diff FROM teams",)
standings_array = c.fetchall()
conn.close()
return standings_array
def get_past_champion(league_name, season_num):
if league_exists(league_name):
with os.scandir(os.path.join(data_dir, league_dir, league_name)) as folder:
for item in folder:
if item.name == str(season_num):
with open(os.path.join(data_dir, league_dir, league_name, item.name, f"{league_name}.state")) as state_file:
state_dic = json.load(state_file)
return state_dic["champion"]
def league_exists(league_name):
with os.scandir(os.path.join(data_dir, league_dir)) as folder:
for subfolder in folder:
if league_name in subfolder.name:
if league_name == subfolder.name:
with os.scandir(subfolder.path) as league_folder:
for item in league_folder:
if item.name == f"{league_name}.db":
return True
return False

View File

@ -14,7 +14,7 @@ class league_structure(object):
self.owner = None
self.season = 1
self.autoplay = -1
self.champions = {}
self.champion = None
def setup(self, league_dic, division_games = 1, inter_division_games = 1, inter_league_games = 1, games_per_hour = 2):
self.league = league_dic # { subleague name : { division name : [team object] } }
@ -32,6 +32,14 @@ class league_structure(object):
self.active = False
self.games_per_hour = games_per_hour
def season_reset(self):
self.season += 1
self.day = 1
self.champion = None
self.schedule = {}
self.generate_schedule()
save_league(self)
def add_stats_from_game(self, players_dic):
league_db.add_stats(self.name, players_dic)
@ -234,11 +242,42 @@ class league_structure(object):
teams.sort(key=sorter, reverse=True)
return teams
def past_standings(self, season_num):
this_embed = Embed(color=Color.purple(), title=self.name)
standings = {}
for team_name, wins, losses, run_diff in league_db.get_past_standings(self.name, season_num):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
this_embed.add_field(name=league_db.get_past_champion(self.name, season_num), value=f"Season {season_num} champions", inline = False)
for subleague in iter(self.league.keys()):
this_embed.add_field(name="Subleague:", value=f"**{subleague}**", inline = False)
for division in iter(self.league[subleague].keys()):
teams = self.division_standings(self.league[subleague][division], standings)
for index in range(0, len(teams)):
if index == self.constraints["division_leaders"] - 1:
teams[index][4] = "-"
else:
games_behind = ((teams[self.constraints["division_leaders"] - 1][1] - teams[index][1]) + (teams[index][2] - teams[self.constraints["division_leaders"] - 1][2]))/2
teams[index][4] = games_behind
teams_string = ""
for this_team in teams:
if this_team[2] != 0 or this_team[1] != 0:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: {round(this_team[1]/(this_team[1]+this_team[2]), 3)} GB: {this_team[4]}\n\n"
else:
teams_string += f"**{this_team[0].name}\n**{this_team[1]} - {this_team[2]} WR: - GB: {this_team[4]}\n\n"
this_embed.add_field(name=f"{division} Division:", value=teams_string, inline = False)
this_embed.set_footer(text=f"Season {season_num} Final Standings")
return this_embed
def season_length(self):
return int(list(self.schedule.keys())[-1]) * self.series_length
def standings_embed(self):
this_embed = Embed(color=Color.purple(), title=self.name)
this_embed = Embed(color=Color.purple(), title=f"{self.name} Season {self.season}")
standings = {}
for team_name, wins, losses, run_diff in league_db.get_standings(self.name):
standings[team_name] = {"wins" : wins, "losses" : losses, "run_diff" : run_diff}
@ -461,7 +500,7 @@ def load_league_file(league_name):
this_league.historic = state_dic["historic"]
this_league.season = state_dic["season"]
try:
this_league.champions = state_dic["champions"]
this_league.champion = state_dic["champion"]
except:
this_league.champions = {}
this_league.champion = None
return this_league

View File

@ -1,7 +1,7 @@
import discord, json, math, os, roman, games, asyncio, random, main_controller, threading, time, urllib, leagues, datetime
import database as db
import onomancer as ono
from league_storage import league_exists
from league_storage import league_exists, season_save
from the_draft import Draft, DRAFT_ROUNDS
from flask import Flask
from uuid import uuid4
@ -753,9 +753,15 @@ class DebugLeagueDisplay(Command):
name = "displaydebugleague"
async def execute(self, msg, command):
if league_exists("test2"):
league = leagues.load_league_file("test2")
await msg.channel.send(embed=league.standings_embed())
if league_exists("Midseries"):
league = leagues.load_league_file("Midseries")
league.champion = "Butts"
leagues.save_league(league)
season_save(league)
league.season_reset()
await msg.channel.send(embed=league.past_standings(1))
class StartLeagueCommand(Command):
name = "startleague"
@ -829,12 +835,25 @@ Plays a league with a given name, provided that league has been saved on the web
class LeagueDisplayCommand(Command):
name = "leaguestandings"
template = "m;leaguestandings [league name]"
description = "Displays the current standings for the given league."
description = "Displays the current standings for the given league. Use `--season X` or `-s X` to get standings from season X of that league."
async def execute(self, msg, command):
if league_exists(command.strip()):
league = leagues.load_league_file(command.strip())
if league_exists(command.split("-")[0].strip()):
league = leagues.load_league_file(command.split("-")[0].strip())
try:
if "--season " in command:
season_num = int(command.split("--season ")[1])
await msg.channel.send(embed=league.past_standings(season_num))
elif "-s " in command:
season_num = int(command.split("-s ")[1])
await msg.channel.send(embed=league.past_standings(season_num))
else:
await msg.channel.send(embed=league.standings_embed())
except ValueError:
await msg.channel.send("Give us a proper number, boss.")
except TypeError:
await msg.channel.send("That season hasn't been played yet, chief.")
else:
await msg.channel.send("Can't find that league, boss.")
@ -1981,8 +2000,10 @@ async def league_postseason(channel, league):
await channel.send(f"The {league.name} Championship Series is starting in {math.ceil(wait_seconds/60)} minutes!")
await asyncio.sleep(wait_seconds)
await start_tournament_round(channel, world_series)
league.champions[str(league.season)] = world_series.winner.name
league.champion = world_series.winner.name
leagues.save_league(league)
season_save(league)
league.season_reset()