Completed new-game mlb-campaign

This commit is contained in:
Cal Corum 2024-10-14 00:44:49 -05:00
parent 2db26e00f1
commit a7189be67e
2 changed files with 91 additions and 136 deletions

View File

@ -1,3 +1,4 @@
import asyncio
import enum
import logging
from typing import Literal
@ -12,7 +13,7 @@ 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.data_cache import get_pd_team
from in_game.gameplay_models import Lineup, Session, engine, get_player_or_none, player_description, select, Game, get_team_or_none
from in_game.gameplay_models import Lineup, Session, engine, get_card_or_none, get_player_or_none, player_description, select, Game, get_team_or_none
from in_game.gameplay_queries import get_channel_game_or_none, get_active_games_by_team
@ -53,7 +54,6 @@ class Gameplay(commands.Cog):
)
return
# await interaction.edit_original_response(content=f'Now to check that you\'re in the right channel category...')
if interaction.channel.category is None or interaction.channel.category.name != PUBLIC_FIELDS_CATEGORY_NAME:
await interaction.edit_original_response(
content=f'Why don\'t you head down to one of the Public Fields that way other humans can help if anything '
@ -61,7 +61,6 @@ class Gameplay(commands.Cog):
)
return
# await interaction.edit_original_response(content=f'Now to find this away team **{away_team_abbrev.upper()}**')
try:
away_team = await get_team_or_none(session, team_abbrev=away_team_abbrev)
except LookupError as e:
@ -129,73 +128,83 @@ class Gameplay(commands.Cog):
ai_team='away' if away_team.is_ai else 'home',
game_type=league.name
)
# session.add(this_game)
# session.commit()
# session.refresh(this_game)
game_info_log = f'Game {this_game.id} ({league.value}) between {away_team.description} and {home_team.description} / first message: {this_game.first_message}'
game_info_log = f'{league.value} game between {away_team.description} and {home_team.description} / first message: {this_game.first_message}'
logging.info(game_info_log)
await interaction.channel.send(content=game_info_log)
# Get Human SP card
human_sp_card = await db_get('cards', object_id=sp_card_id)
id_key = 'id'
if 'player_id' in human_sp_card['player']:
id_key = 'player_id'
human_sp_player = await get_player_or_none(session, human_sp_card['player'][id_key])
human_sp_card = await get_card_or_none(session, card_id=sp_card_id)
if human_sp_card is None:
await interaction.channel.send(
f'Uh oh. I can\'t find a card with ID {sp_card_id}. Will you double check that before we get started?'
)
return
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}')
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_card.player.name} and belongs to {human_sp_card.team.sname}. Will you double check that before we get started?'
)
return
legal_data = await legal_check([sp_card_id], difficulty_name=league.name)
if not legal_data['legal']:
await interaction.edit_original_response(
content=f'It looks like this is a Ranked Legal game and {player_description(human_sp_player)} is not legal in {league.value} games. You can start a new game once you pick a new SP.'
content=f'It looks like this is a Ranked Legal game and {player_description(player=human_sp_card.player)} is not legal in {league.value} games. You can start a new game once you pick a new SP.'
)
return
human_sp_lineup = Lineup(
team_id=human_team.id,
player_id=human_sp_player.id,
player_id=human_sp_card.player.id,
card_id=sp_card_id,
position='P',
batting_order=10,
is_fatigued=False,
game=this_game
)
# session.add(human_sp_lineup)
# Get AI SP
await interaction.edit_original_response(
content=f'{ai_team.gmname} is looking for a SP to counter {human_sp_player.name}...'
content=f'{ai_team.gmname} is looking for a SP to counter {human_sp_card.player.name}...'
)
starter = await ai_manager.get_starting_pitcher(
ai_sp_lineup = await ai_manager.get_starting_pitcher(
session,
ai_team,
this_game.id,
True if home_team['is_ai'] else False,
this_game,
True if home_team.is_ai else False,
league.name
)
await interaction.edit_original_response(
content=f'The {ai_team.sname} are starting **{player_description(player=ai_sp_lineup.player)}**:\n\n{ai_sp_lineup.player.p_card_url}'
)
# Get AI Lineup
final_message = await interaction.channel.send(
content=f'{ai_team.gmname} is filling out the {ai_team.sname} lineup card...'
)
batter_lineups = await ai_manager.get_starting_lineup(
session,
team=ai_team,
game=this_game,
league_name=league.name,
sp_name=human_sp_card.player.name
)
# Commit game and lineups
# session.add(this_game)
# session.commit()
session.add(this_game)
session.commit()
# session.refresh(this_game)
away_role = await team_role(interaction, away_team)
home_role = await team_role(interaction, home_team)
await interaction.channel.send(
await final_message.edit(
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

@ -12,7 +12,8 @@ from peewee import *
from typing import Optional, Literal
from in_game import data_cache
from in_game.gameplay_models import Game, Team
import in_game.gameplay_models as iggm
from in_game.gameplay_models import Session, Game, Team, get_or_create_ai_card, get_player_id_from_dict, get_player_or_none
db = SqliteDatabase(
'storage/ai-database.db',
@ -240,100 +241,6 @@ async def build_lineup_graded(team_object: dict, vs_hand: str, league_name: str,
async def build_lineup(team_object: dict, game_id: int, league_name: str, sp_name: str, vs_hand: str = 'r') -> list:
# players = {
# 'C': None,
# '1B': None,
# '2B': None,
# '3B': None,
# 'SS': None,
# 'LF': None,
# 'CF': None,
# 'RF': None,
# 'DH': None
# }
# p_names = []
# rest_name = None
#
# set_params = [('cardset_id_exclude', 2)]
# if team_object['id'] == 58:
# set_params = []
# elif 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 'gauntlet-1' in league_name:
# set_params = copy.deepcopy(MINOR_CARDSET_PARAMS)
# elif 'gauntlet-2' in league_name:
# set_params = random.sample(GAUNTLET2_PARAMS, 2)
#
# # Pull players sorted by current cost
# try:
# params = [
# ('mlbclub', team_object['lname']), ('pos_include', 'C'), ('pos_include', '1B'), ('pos_include', '2B'),
# ('pos_include', '3B'), ('pos_include', 'SS'), ('pos_include', 'LF'), ('pos_include', 'CF'),
# ('pos_include', 'RF'), ('pos_include', 'DH'), ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 50)
# ]
# params.extend(set_params)
# p_query = await db_get(
# endpoint='players',
# params=params,
# timeout=10
# )
# all_players = p_query['players']
# except ConnectionError as e:
# raise ConnectionError(f'Error pulling batters for the {team_object["lname"]}. Cal help plz.')
#
# logging.info(f'build_lineup - eligible batter count: {len(all_players)}')
#
# # Choose starting nine & position
# # In order of cost:
# # Try to add to pos_1; if unavailable, try remaining pos; if unavailable, add to DH
# # If all pos unavailable; note player's pos_1 and check if incumbent can move; if so, check for new incumbent
# # and recurse
# # If not possible, pass player and continue
# for guy in all_players:
# placed = False
# if guy['p_name'] not in p_names and guy['p_name'] != rest_name:
# for pos in [
# guy['pos_1'], guy['pos_2'], guy['pos_3'], guy['pos_4'], guy['pos_5'], guy['pos_6'], guy['pos_7'],
# guy['pos_8']
# ]:
# if pos is None or pos in ['SP', 'RP', 'CP']:
# break
#
# if random.randint(1, 10) == 10 and rest_name is None and False:
# logging.info(f'Resting {guy["p_name"]} in game {game_id}')
# rest_name = guy['p_name']
# elif players[pos] is None:
# players[pos] = guy
# p_names.append(guy["p_name"])
# placed = True
# break
#
# if not placed and rest_name != guy['p_name']:
# if players['DH'] is None:
# players['DH'] = guy
# p_names.append(guy["p_name"])
# else:
# logging.info(f'build_lineup - could not place {guy["p_name"]} in {team_object["sname"]} lineup')
# else:
# logging.info(f'build_lineup - {guy["p_name"]} already in lineup')
#
# if None in players.values():
# bad_pos = {x for x in players if players[x] is None}
# raise ValueError(f'Could not find a {bad_pos} for the {team_object["sname"]}')
#
# logging.info(f'build_lineup - {players}')
#
# # Sort players into lineup
# # Pseudo-random? Patterns? Something to mix up lineups
# # 421356789 or [123 (rand)][456 (rand)][789 (rand)] (optional: chance to flip 3/4 and 6/7)
#
# # [ (<pos>, <player_obj>), (<pos>, <player_obj>), etc. ]
# sorted_players = sorted(players.items(), key=lambda x: x[1]['cost'], reverse=True)
build_type = 'fun'
this_game = get_one_game(game_id=game_id)
l_query = await db_get(
@ -375,8 +282,48 @@ async def build_lineup(team_object: dict, game_id: int, league_name: str, sp_nam
return lineups
async def get_starting_lineup(session: Session, team: Team, game: Game, league_name: str, sp_name: str, vs_hand: str = 'r') -> list[Lineup]:
build_type = 'fun'
l_query = await db_get(
f'teams/{team.id}/lineup/{league_name}?pitcher_name={sp_name}&build_type={build_type}{game.cardset_param_string}',
timeout=6
)
sorted_players = l_query['array']
logging.debug(f'ai_manager - get_starting_lineup - sorted_players: {sorted_players}')
grp_1 = sorted_players[:3]
grp_2 = sorted_players[3:6]
grp_3 = sorted_players[6:]
random.shuffle(grp_1)
random.shuffle(grp_2)
random.shuffle(grp_3)
lineups = []
i = 1
for x in [grp_1, grp_2, grp_3]:
logging.debug(f'ai_manager - get_starting_lineup - group: {x}')
for y in x:
logging.debug(f'ai_manager - get_starting_lineup - y: {y}')
this_player = await get_player_or_none(session, get_player_id_from_dict(y[1]['player']))
this_card = await get_or_create_ai_card(session, player=this_player, team=team)
lineups.append(iggm.Lineup(
position=y[0],
batting_order=i,
game=game,
team=team,
player=this_player,
card=this_card
))
i += 1
logging.debug(f'ai_manager - get_starting_lineup - final lineup: {lineups}')
return lineups
async def get_starting_pitcher(
this_team: Team, this_game: Game, is_home: bool, league_name: str = None) -> dict:
session: Session, this_team: Team, this_game: Game, is_home: bool, league_name: str) -> iggm.Lineup:
d_100 = random.randint(1, 100)
if is_home:
if d_100 <= 30:
@ -401,22 +348,21 @@ async def get_starting_pitcher(
else:
sp_rank = 5
starter = await db_get(
sp_query = await db_get(
f'teams/{this_team.id}/sp/{league_name}?sp_rank={sp_rank}{this_game.cardset_param_string}'
)
this_player = await get_player_or_none(session, get_player_id_from_dict(sp_query))
sp_card = await iggm.get_or_create_ai_card(session, this_player, this_team)
# get player card; create one if none found
card_id = await get_or_create_card(starter, team_object)
return {
'game_id': game_id,
'team_id': team_object['id'],
'player_id': starter['player_id'],
'card_id': card_id,
'position': 'P',
'batting_order': 10,
'after_play': 0
}
return iggm.Lineup(
team=this_team,
player=this_player,
card=sp_card,
position='P',
batting_order=10,
is_fatigued=False,
game=this_game
)
async def get_relief_pitcher(this_play: StratPlay, ai_team: dict, league_name: str = None) -> dict: