Move db creation to entry

Nearing completion of new-game mlb-campaign
This commit is contained in:
Cal Corum 2024-10-13 00:25:29 -05:00
parent c66075f9a8
commit 97519fc8d5
4 changed files with 35 additions and 73 deletions

View File

@ -8,17 +8,17 @@ from discord.app_commands import Choice
from discord.ext import commands from discord.ext import commands
from api_calls import db_get from api_calls import db_get
from helpers import PD_PLAYERS_ROLE_NAME, user_has_role from helpers import PD_PLAYERS_ROLE_NAME, team_role, user_has_role
from in_game import ai_manager
from in_game.game_helpers import PUBLIC_FIELDS_CATEGORY_NAME, legal_check from in_game.game_helpers import PUBLIC_FIELDS_CATEGORY_NAME, legal_check
from in_game.data_cache import get_pd_team from in_game.data_cache import get_pd_team
from in_game.gameplay_models import Lineup, Session, engine, create_db_and_tables, get_player, player_description, select, Game, get_team from in_game.gameplay_models import Lineup, Session, engine, get_player, player_description, select, Game, get_team
from in_game.gameplay_queries import get_channel_game_or_none, get_games_by_team_id from in_game.gameplay_queries import get_channel_game_or_none, get_games_by_team_id
class Gameplay(commands.Cog): class Gameplay(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
create_db_and_tables()
async def cog_command_error(self, ctx, error): async def cog_command_error(self, ctx, error):
await ctx.send(f'{error}\n\nRun !help <command_name> to see the command requirements') await ctx.send(f'{error}\n\nRun !help <command_name> to see the command requirements')
@ -33,10 +33,6 @@ class Gameplay(commands.Cog):
sp_card_id='Light gray number to the left of the pitcher\'s name on your depth chart' sp_card_id='Light gray number to the left of the pitcher\'s name on your depth chart'
) )
@app_commands.choices(league=[ @app_commands.choices(league=[
# Choice(name='Minor League', value='minor-league'),
# Choice(name='Flashback', value='flashback'),
# Choice(name='Major League', value='major-league'),
# Choice(name='Hall of Fame', value='hall-of-fame')
Choice(name='minor-league', value='Minor League'), Choice(name='minor-league', value='Minor League'),
Choice(name='flashback', value='Flashback'), Choice(name='flashback', value='Flashback'),
Choice(name='major-league', value='Major League'), Choice(name='major-league', value='Major League'),
@ -149,7 +145,7 @@ class Gameplay(commands.Cog):
human_sp_player = await get_player(session, human_sp_card['player'][id_key]) human_sp_player = await get_player(session, human_sp_card['player'][id_key])
if human_sp_card['team']['id'] != human_team.id: if human_sp_card['team']['id'] != human_team.id:
logging.error(f'Card_id {sp_card_id} does not belong to {human_team["abbrev"]} in Game {this_game.id}') logging.error(f'Card_id {sp_card_id} does not belong to {human_team.abbrev} in Game {this_game.id}')
await interaction.channel.send( await interaction.channel.send(
f'Uh oh. Card ID {sp_card_id} is {human_sp_player.name} and belongs to {human_sp_card["team"]["sname"]}. Will you double check that before we get started?' f'Uh oh. Card ID {sp_card_id} is {human_sp_player.name} and belongs to {human_sp_card["team"]["sname"]}. Will you double check that before we get started?'
) )
@ -173,13 +169,31 @@ class Gameplay(commands.Cog):
) )
# Get AI SP # Get AI SP
await interaction.edit_original_response(
content=f'{ai_team.gmname} is looking for a SP to counter {human_sp_player.name}...'
)
starter = await ai_manager.get_starting_pitcher(
ai_team,
this_game.id,
True if home_team['is_ai'] else False,
league.name
)
# Get AI Lineup # Get AI Lineup
session.delete(this_game) # Commit game and lineups
session.commit() # session.add(this_game)
# session.commit()
# session.refresh(this_game)
await interaction.channel.send(content='I also deleted that game for ~~science~~ testing.') away_role = await team_role(interaction, away_team)
home_role = await team_role(interaction, home_team)
await interaction.channel.send(
content=f'{away_role.mention} @ {home_role.mention} is set!\n\n'
f'Go ahead and set lineups with the `/read-lineup` command!',
# embed=this_game.get_scorebug(full_length=False)
)

View File

@ -17,6 +17,8 @@ from difflib import get_close_matches
from dataclasses import dataclass from dataclasses import dataclass
from typing import Optional, Literal from typing import Optional, Literal
from in_game.gameplay_models import Team
SBA_SEASON = 9 SBA_SEASON = 9
PD_SEASON = 7 PD_SEASON = 7
@ -1608,8 +1610,8 @@ async def get_team_by_owner(owner_id: int):
return team['teams'][0] return team['teams'][0]
async def team_role(ctx, team): async def team_role(ctx, team: Team):
return await get_or_create_role(ctx, f'{team["abbrev"]} - {team["lname"]}') return await get_or_create_role(ctx, f'{team.abbrev} - {team.lname}')
def get_cal_user(ctx): def get_cal_user(ctx):

View File

@ -12,6 +12,7 @@ from peewee import *
from typing import Optional, Literal from typing import Optional, Literal
from in_game import data_cache from in_game import data_cache
from in_game.gameplay_models import Game, Team
db = SqliteDatabase( db = SqliteDatabase(
'storage/ai-database.db', 'storage/ai-database.db',
@ -375,56 +376,7 @@ async def build_lineup(team_object: dict, game_id: int, league_name: str, sp_nam
async def get_starting_pitcher( async def get_starting_pitcher(
team_object: dict, game_id: int, is_home: bool, league_name: str = None) -> dict: this_team: Team, this_game: Game, is_home: bool, league_name: str = None) -> dict:
# set_params = [('cardset_id_exclude', 2)]
# if league_name == 'minor-league':
# set_params = copy.deepcopy(MINOR_CARDSET_PARAMS)
# elif league_name == 'major-league':
# set_params = copy.deepcopy(MAJOR_CARDSET_PARAMS)
# elif league_name == 'hall-of-fame':
# set_params = copy.deepcopy(HOF_CARDSET_PARAMS)
# elif league_name == 'gauntlet-1':
# set_params = copy.deepcopy(MINOR_CARDSET_PARAMS)
# elif 'gauntlet-2' in league_name:
# set_params = random.sample(GAUNTLET2_PARAMS)
#
# params = [
# ('mlbclub', team_object['lname']), ('pos_include', 'SP'), ('pos_exclude', 'RP'),
# ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 5)
# ]
# counter = 0
# logging.info(f'params: {params}')
# while counter < 2:
# logging.info(f'counter: {counter}')
# counter += 1
# # Pull starters sorted by current cost
# logging.info(f'counter: {counter} / params: {params}')
# try:
# params.extend(set_params)
# pitchers = await db_get(
# endpoint='players',
# params=params,
# timeout=10
# )
# logging.info(f'pitchers: {pitchers}')
# except ConnectionError as e:
# logging.error(f'Could not get pitchers for {team_object["lname"]}: {e}')
# raise ConnectionError(f'Error pulling starting pitchers for the {team_object["lname"]}. Cal help plz.')
#
# if pitchers['count'] == 0:
# logging.info(f'pitchers is None')
# del params
# params = [
# ('mlbclub', team_object['lname']), ('pos_include', 'SP'),
# ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 5)
# ]
# else:
# break
#
# logging.info(f'build_lineup - eligible starting pitcher count: {len(pitchers)}')
# if pitchers['count'] == 0:
# raise DatabaseError(f'Could not find any SP for {team_object["abbrev"]}. Seems like a Cal issue.')
d_100 = random.randint(1, 100) d_100 = random.randint(1, 100)
if is_home: if is_home:
if d_100 <= 30: if d_100 <= 30:
@ -449,17 +401,8 @@ async def get_starting_pitcher(
else: else:
sp_rank = 5 sp_rank = 5
# acardsets = [f'&cardset_id={x}' for x in cardset_ids] if cardset_ids is not None else ''
# cardsets = ''
# bcardsets = ''
# for x in cardset_ids:
# cardsets += f'&cardset_id={x}'
# abcardsets = [f'&cardset_id={x}' for x in backup_cardset_ids] if backup_cardset_ids is not None else ''
# for x in backup_cardset_ids:
# bcardsets += f'&backup_cardset_id={x}'
this_game = get_one_game(game_id=game_id)
starter = await db_get( starter = await db_get(
f'teams/{team_object["id"]}/sp/{league_name}?sp_rank={sp_rank}{get_cardset_string(this_game)}' f'teams/{this_team.id}/sp/{league_name}?sp_rank={sp_rank}{this_game.cardset_param_string}'
) )
# get player card; create one if none found # get player card; create one if none found

View File

@ -7,6 +7,8 @@ import os
from discord.ext import commands from discord.ext import commands
from in_game.gameplay_models import create_db_and_tables
raw_log_level = os.getenv('LOG_LEVEL') raw_log_level = os.getenv('LOG_LEVEL')
if raw_log_level == 'DEBUG': if raw_log_level == 'DEBUG':
log_level = logging.DEBUG log_level = logging.DEBUG
@ -71,6 +73,7 @@ async def on_ready():
async def main(): async def main():
create_db_and_tables()
for c in COGS: for c in COGS:
try: try:
await bot.load_extension(c) await bot.load_extension(c)