Merge branch 'master' into sqlmodel-alembic-pytests-rebuild

This commit is contained in:
Cal Corum 2024-12-24 14:51:59 -06:00
commit 19cdf969d1
4 changed files with 385 additions and 96 deletions

View File

@ -2,6 +2,9 @@ import csv
import json
import db_calls_gameplay
from gauntlets import evolve_pokemon
from helpers import *
from db_calls import *
from discord import Member
from discord.ext import commands, tasks
from discord import app_commands
@ -598,5 +601,12 @@ class Admins(commands.Cog):
@commands.command(name='test_evo', help='Mod: Test pokemon evolution')
@commands.is_owner()
async def test_evolution(self, ctx, team_abbrev: str):
this_team = await get_team_by_abbrev(team_abbrev)
await evolve_pokemon(this_team, ctx.channel)
async def setup(bot):
await bot.add_cog(Admins(bot))

View File

@ -2,9 +2,11 @@ import copy
import datetime
import logging
import random
from typing import Literal
import discord
from sqlmodel import Session
from discord import SelectOption
from in_game import ai_manager
import helpers
@ -12,6 +14,8 @@ from helpers import RARITY, get_or_create_role, send_to_channel, get_channel
from api_calls import db_get, db_post, db_delete, db_patch
from in_game.gameplay_models import Team
from in_game.gameplay_queries import get_team_or_none
from db_calls import db_get, db_post, db_delete, db_patch
from utilities.dropdown import DropdownView, SelectPokemonEvolution
logger = logging.getLogger('discord_app')
@ -189,27 +193,53 @@ async def get_opponent(session: Session, this_team, this_event, this_run) -> Tea
raise KeyError(f'Hmm...I do not know who you should be playing right now.')
elif this_event['id'] == 6:
if gp == 0:
t_id = 30
t_id = 18
elif gp == 1:
t_id = 22
elif gp == 2:
t_id = 7
elif gp == 3:
t_id = 8
elif gp == 4:
t_id = 16
elif gp == 5:
t_id = 6
elif gp == 2:
t_id = 17
elif gp == 3:
t_id = 21
elif gp == 4:
t_id = 4
elif gp == 5:
t_id = 23
elif gp == 6:
t_id = 24
t_id = 5
elif gp == 7:
t_id = 15
t_id = 3
elif gp == 8:
t_id = 19
elif gp == 9:
t_id = 27
elif gp == 10:
t_id = 25
else:
raise KeyError(f'Hmm...I do not know who you should be playing right now.')
return await db_get('teams', object_id=t_id, none_okay=False)
elif this_event['id'] == 7:
if gp == 0:
t_id = 10
elif gp == 1:
t_id = 20
elif gp == 2:
t_id = 25
elif gp == 3:
t_id = 27
elif gp == 4:
t_id = 6
elif gp == 5:
t_id = 5
elif gp == 6:
t_id = 4
elif gp == 7:
t_id = 16
elif gp == 8:
t_id = 13
elif gp == 9:
t_id = 1
t_id = 30
elif gp == 10:
t_id = 29
t_id = 17
else:
raise KeyError(f'Hmm...I do not know who you should be playing right now.')
else:
@ -239,70 +269,6 @@ async def get_starting_pitcher(this_team, this_game, this_event, this_run):
'after_play': 0
}
# if this_event['id'] == 1:
# if this_team['id'] != 58:
# set_params = copy.deepcopy(ai_manager.MINOR_CARDSET_PARAMS)
# else:
# set_params = []
# params = [
# ('mlbclub', this_team['lname']), ('pos_include', 'SP'), ('pos_exclude', 'RP'),
# ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 5)
# ]
# params.extend(set_params)
# elif this_event['id'] == 2:
# set_params = copy.deepcopy(ai_manager.GAUNTLET2_PARAMS)
# params = [
# ('mlbclub', this_team['lname']), ('pos_include', 'SP'), ('pos_exclude', 'RP'),
# ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 5)
# ]
# params.extend(set_params)
# else:
# raise KeyError(f'Pitcher not found for Gauntlet {this_event["id"]}')
#
# params = [
# ('mlbclub', this_team['lname']), ('pos_include', 'SP'), ('pos_exclude', 'RP'),
# ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 5)
# ]
# counter = 0
# while True:
# counter += 1
# # Pull starters sorted by current cost
# try:
# params.extend(set_params)
# pitchers = await db_get(
# endpoint='players',
# params=params,
# timeout=10
# )
# except ConnectionError as e:
# logger.error(f'Could not get pitchers for {this_team["lname"]}: {e}')
# raise ConnectionError(f'Error pulling starting pitchers for the {this_team["lname"]}. Cal help plz.')
#
# if pitchers['count'] == 0:
# logger.info(f'pitchers is None')
# del params
# params = [
# ('mlbclub', this_team['lname']), ('pos_include', 'SP'),
# ('inc_dex', False), ('sort_by', 'cost-desc'), ('limit', 5)
# ]
# elif counter > 2:
# raise KeyError(f'Error pulling pitchers for the {this_team["lname"]}. Cal help plz.')
# else:
# break
#
# pitcher_num = games_played(this_run) % 5
# card_id = await ai_manager.get_or_create_card(pitchers['players'][pitcher_num], this_team)
#
# return {
# 'game_id': this_game.id,
# 'team_id': this_team['id'],
# 'player_id': pitchers['players'][0]['player_id'],
# 'card_id': card_id,
# 'position': 'P',
# 'batting_order': 10,
# 'after_play': 0
# }
async def run_draft(interaction: discord.Interaction, main_team: Team, this_event, draft_team: Team = None):
logger.info(f'Starting draft for {main_team.abbrev if draft_team is None else draft_team.abbrev}')
@ -335,6 +301,10 @@ async def run_draft(interaction: discord.Interaction, main_team: Team, this_even
embed_description = f'{this_event["name"]}'
base_params = [('cardset_id', 20), ('cardset_id', 21), ('cardset_id', 22), ('cardset_id', 16),
('cardset_id', 8), ('limit', 8)]
elif this_event['id'] == 7:
embed_title = f'{main_team['lname']} - {this_event['name']} Draft'
embed_description = f'{this_event["name"]}'
base_params = [('cardset_id', 5), ('cardset_id', 1), ('cardset_id', 3), ('cardset_id', 4), ('cardset_id', 23), ('cardset_id', 22), ('limit', 4)]
else:
logger.error(f'run_draft - Event ID {this_event["id"]} not recognized')
raise KeyError(f'Draft data not found for Gauntlet {this_event["id"]}')
@ -589,19 +559,30 @@ async def run_draft(interaction: discord.Interaction, main_team: Team, this_even
for z in helpers.get_all_pos(y):
all_str[z] += f'{name_string}\n'
top_embed.add_field(name=f'HoFs ({counts["Hall of Fame"]}/{max_counts["Hall of Fame"]})', value=all_str['Hall of Fame'], inline=False)
top_embed.add_field(name=f'MVPs ({counts["MVP"]}/{max_counts["MVP"]})', value=all_str['MVP'], inline=False)
top_embed.add_field(
name=f'All-Stars ({counts["All-Star"]}/{max_counts["All-Star"]})', value=all_str['All-Star'], inline=False)
top_embed.add_field(
name=f'Starters ({counts["Starter"]}/{max_counts["Starter"]})', value=all_str['Starter'], inline=False)
top_embed.add_field(
name=f'Reserves ({counts["Reserve"]}/{max_counts["Reserve"]})', value=all_str['Reserve'], inline=False)
top_embed.add_field(
name=f'Replacements ({counts["Replacement"]}/{max_counts["Replacement"]})',
value=all_str['Replacement'],
inline=False
)
if max_counts['Hall of Fame'] > 0:
top_embed.add_field(name=f'HoFs ({counts["Hall of Fame"]}/{max_counts["Hall of Fame"]})', value=all_str['Hall of Fame'], inline=False)
if max_counts['MVP'] > 0:
top_embed.add_field(name=f'MVPs ({counts["MVP"]}/{max_counts["MVP"]})', value=all_str['MVP'], inline=False)
if max_counts['All-Star'] > 0:
top_embed.add_field(
name=f'All-Stars ({counts["All-Star"]}/{max_counts["All-Star"]})', value=all_str['All-Star'], inline=False)
if max_counts['Starter'] > 0:
top_embed.add_field(
name=f'Starters ({counts["Starter"]}/{max_counts["Starter"]})', value=all_str['Starter'], inline=False)
if max_counts['Reserve'] > 0:
top_embed.add_field(
name=f'Reserves ({counts["Reserve"]}/{max_counts["Reserve"]})', value=all_str['Reserve'], inline=False)
if max_counts['Replacement'] > 0:
top_embed.add_field(
name=f'Replacements ({counts["Replacement"]}/{max_counts["Replacement"]})',
value=all_str['Replacement'],
inline=False
)
bot_embed.add_field(name=f'Catcher', value=all_str['C'], inline=False)
bot_embed.add_field(name=f'First Base', value=all_str['1B'], inline=False)
@ -1510,6 +1491,164 @@ async def run_draft(interaction: discord.Interaction, main_team: Team, this_even
await last_message.edit(content=None, embeds=get_embeds(include_links=False))
elif this_event['id'] in [5, 6]:
await draft_loop()
elif this_event['id'] == 7:
round_num = 1
counter = 0
while round_num <= 26 and counter < 50:
counter += 1
params = copy.deepcopy(base_params)
logging.info(f'gauntlets.py - run_draft - event_id {this_event["id"]} / round_num: {round_num} / counter: {counter} / counts: {counts} / max_counts: {max_counts}')
# Set rarity based on remaining counts
if counts['Hall of Fame'] < max_counts['Hall of Fame']:
params.extend([
('min_rarity', RARITY['HoF']), ('max_rarity', RARITY['HoF'])
])
elif counts['MVP'] < max_counts['MVP']:
params.extend([
('min_rarity', RARITY['MVP']), ('max_rarity', RARITY['MVP'])
])
elif counts['All-Star'] < max_counts['All-Star']:
params.extend([
('min_rarity', RARITY['All-Star']), ('max_rarity', RARITY['All-Star'])
])
elif counts['Starter'] < max_counts['Starter']:
if counts['Starter'] < 5:
params = [('cardset_id', 23), ('limit', 16)]
params.extend([
('min_rarity', RARITY['Starter']), ('max_rarity', RARITY['Starter'])
])
elif counts['Reserve'] < max_counts['Reserve']:
params.extend([
('min_rarity', RARITY['Reserve']), ('max_rarity', RARITY['Reserve'])
])
else:
params.extend([
('min_rarity', RARITY['Replacement']), ('max_rarity', RARITY['Replacement'])
])
this_batch = []
for x in ['SP', 'RP', 'IF', 'OF']:
# Slot 1 - SP
if x == 'SP':
if counts['SP'] > 5:
slot_params = [('pos_exc', 'SP')]
if counts['RP'] > 7:
slot_params = [('pos_exc', 'RP')]
else:
slot_params = [('pos_inc', 'SP')]
# if counts['SP'] > 5:
# slot_params = [('pos_exc', 'SP')]
# elif counts['RP'] < 6:
# slot_params = [('pos_inc', 'RP')]
# else:
# slot_params = [('pos_exc', 'SP'), ('pos_exc', 'RP')]
# Slot 2 - RP
elif x == 'RP':
logging.info(f'counts[RP]: {counts["RP"]}')
if counts['RP'] > 7:
slot_params = [('pos_exc', 'RP')]
if counts['SP'] > 5:
slot_params = [('pos_exc', 'SP')]
else:
slot_params = [('pos_inc', 'RP')]
# Slot 3 - IF
elif x == 'IF':
slot_params = []
for y in ['1B', '2B', '3B', 'SS', 'C']:
if (counts[y] > 1) and 0 in [
counts['C'], counts['1B'], counts['2B'], counts['3B'], counts['SS']
]:
slot_params.append(('pos_exc', y))
elif (y == 'C' and counts['C'] < 3) or (y != 'C' and counts[y] < 4):
slot_params.append(('pos_inc', y))
# if counts['C'] < 2:
# slot_params.append(('pos_inc', 'C'))
# if len(slot_params) == 0:
# slot_params = [('pos_exc', 'C'), ('pos_exc', '1B'), ('pos_exc', '2B'), ('pos_exc', '3B'),
# ('pos_exc', 'SS')]
# Slot 4 - OF
else:
slot_params = []
for y in ['LF', 'CF', 'RF']:
if counts[y] > 4:
slot_params.append(('pos_exc', y))
elif counts[y] > 1 and 0 in [counts['LF'], counts['CF'], counts['RF']]:
slot_params.append(('pos_exc', y))
elif counts[y] < 5:
slot_params.append(('pos_inc', y))
# if len(slot_params) == 0:
# slot_params = [('pos_exc', 'LF'), ('pos_exc', 'CF'), ('pos_exc', 'RF')]
logging.info(f'this_batch: {this_batch}')
logging.info(f'slot_params: {slot_params}')
logging.info(f'params: {params}')
# No position explicitly requested or denied
if len(slot_params) == 0:
if (counts['SP'] + counts['RP']) > (
counts['C'] + counts['1B'] + counts['2B'] + counts['SS'] + counts['LF'] + counts['CF'] +
counts['RF']):
pos_counts = [
('C', counts['C']), ('1B', counts['1B']), ('2B', counts['2B']), ('3B', counts['3B']),
('SS', counts['SS']), ('LF', counts['LF']), ('CF', counts['CF']), ('RF', counts['RF'])
]
pos_counts.sort(key=lambda z: z[1])
slot_params = [('pos_inc', pos_counts[0][0])]
else:
if counts['SP'] >= counts['RP']:
slot_params = [('pos_inc', 'RP')]
else:
slot_params = [('pos_inc', 'SP')]
slot_params.extend(params)
p_query = await db_get('players/random', params=slot_params)
if p_query['count'] > 0:
for i in p_query['players']:
if i['p_name'] not in p_names and i not in this_batch:
if i['cardset']['id'] == 23 and '420420' not in i['strat_code']:
pass
else:
this_batch.append(i)
break
if len(this_batch) < 4:
logging.error(f'Pulled less than 4 players in gauntlet draft')
p_query = await db_get('players/random', params=params)
for i in p_query['players']:
if i['p_name'] not in p_names and i not in this_batch:
this_batch.append(i)
if len(this_batch) >= 4:
break
if len(this_batch) < 4:
raise KeyError(f'This is embarassing, but I couldn\'t find enough players for you to draft from.')
# Present choices and capture selection
p_choice = await helpers.get_choice_from_cards(interaction, this_batch, delete_message=True)
# Add player to list and update counts
p_names.append(p_choice['p_name'])
counts[p_choice['rarity']['name']] += 1
all_players.append(p_choice)
if p_choice['pos_1'] in ['SP', 'RP']:
counts[p_choice['pos_1']] += 1
else:
for x in helpers.get_all_pos(p_choice):
if x in counts:
counts[x] += 1
# Update roster embed
round_num += 1
await last_message.edit(content=None, embeds=get_embeds(include_links=False, round_num=round_num))
else:
logger.error(f'run_draft - No draft logic for Event ID {this_event["id"]}')
raise KeyError(f'Draft data not found for Gauntlet {this_event["id"]}')
@ -1637,6 +1776,29 @@ async def end_run(this_run, this_event, this_team):
return l_message
async def evolve_pokemon(this_team, channel):
c_query = await db_get(
'cards',
params=[('team_id', this_team['id']), ('order_by', 'new'), ('limit', 26)]
)
evolvable_mons = [x for x in c_query['cards'] if x['player']['cardset']['id'] in [23] and x['player']['fangr_id'] is not None and len(x['player']['fangr_id']) > 3]
logging.info(f'evolvable_mons: {evolvable_mons}')
if len(evolvable_mons) > 0:
evo_target_options = [
SelectOption(label=f'{x["player"]["rarity"]["name"]} | {x["player"]["p_name"]}', value=x['id']) for x in evolvable_mons
]
view = DropdownView(
dropdown_objects=[SelectPokemonEvolution(options=evo_target_options, this_team=this_team)]
)
await channel.send(
content='What? One of your pokemon is ready to evolve!\n\n-# The selected pokemon will be removed from your team and replaced with its evolution',
view=view
)
else:
await channel.send('All of your Pokemon are fully evolved!')
async def post_result(run_id: int, is_win: bool, this_team, bot, channel):
this_run = await db_get('gauntletruns', object_id=run_id)
this_event = await db_get('events', object_id=this_run['gauntlet']['id'])
@ -1681,7 +1843,7 @@ async def post_result(run_id: int, is_win: bool, this_team, bot, channel):
team_id = None
if x['reward']['pack_type']['id'] == 9:
cardset_id = 18
else:
elif this_event['id'] == 6:
cardset_id = 20
team_id = None
if x['reward']['pack_type']['id'] == 9:
@ -1695,6 +1857,19 @@ async def post_result(run_id: int, is_win: bool, this_team, bot, channel):
}]}
)
reward_string += f'- 1x {x["reward"]["pack_type"]["name"]} Pack'
elif x['reward']['pack_type'] and this_event['id'] in [7]:
if this_event['id'] == 7:
cardset_id = 23
team_id = 91
await db_post(
'packs', payload={'packs': [{
'team_id': main_team['id'],
'pack_type_id': x['reward']['pack_type']['id'],
'pack_cardset_id': cardset_id if x['reward']['pack_type']['id'] != 8 else None,
'pack_team_id': team_id if x['reward']['pack_type']['id'] == 8 else None
}]}
)
reward_string += f'- 1x {x["reward"]["pack_type"]["name"]} Pack'
elif x['reward']['pack_type']:
await helpers.give_packs(main_team, 1, x['reward']['pack_type'])
reward_string += f'- 1x {x["reward"]["pack_type"]["name"]} Pack'
@ -1747,4 +1922,11 @@ async def post_result(run_id: int, is_win: bool, this_team, bot, channel):
embed=await get_embed(this_run)
)
# Evolve a card!
logging.info(f'Post-game evolution check: Gauntlet ID {this_run["id"]} / Wins: {this_run["wins"]} / Losses: {this_run["losses"]}')
if this_event['id'] == 7 and this_run['wins'] < 10 and this_run['losses'] < 2:
logging.info(f'trying to evolve now')
await evolve_pokemon(this_team, channel)

View File

@ -29,6 +29,7 @@ PD_PLAYERS = 'Paper Dynasty Players'
SBA_PLAYERS_ROLE_NAME = f'Season {SBA_SEASON} Players'
PD_PLAYERS_ROLE_NAME = f'Paper Dynasty Players'
PD_CARD_URL = 'https://sombaseball.ddns.net/cards/pd'
PKMN_REF_URL = 'https://pkmncards.com/card/'
RATINGS_BATTER_FORMULA = '=IMPORTRANGE("1zDmlOw94gTzOAjqOpNdDZsg0O6rxNWkL4-XT6-iL2IE","guide_Batters!A1:CD")'
RATINGS_PITCHER_FORMULA = '=IMPORTRANGE("1zDmlOw94gTzOAjqOpNdDZsg0O6rxNWkL4-XT6-iL2IE","guide_Pitchers!A1:BQ")'
RATINGS_SHEET_KEY = '1zDmlOw94gTzOAjqOpNdDZsg0O6rxNWkL4-XT6-iL2IE'
@ -70,6 +71,7 @@ IMAGES = {
'pack-sta': f'{PD_CARD_URL}/pack-standard.png',
'pack-pre': f'{PD_CARD_URL}/pack-premium.png',
'pack-mar': f'{PD_CARD_URL}/sluggers/mario-gauntlet.png',
'pack-pkmnbs': f'https://i.postimg.cc/635M4X52/pokemon-brilliantstars.jpg',
'mvp': {
'Arizona Diamondbacks': f'{PD_CARD_URL}/mvp/arizona-diamondbacks.gif',
'Atlanta Braves': f'{PD_CARD_URL}/mvp/atlanta-braves.gif',
@ -104,7 +106,8 @@ IMAGES = {
'Toronto Blue Jays': f'{PD_CARD_URL}/mvp/toronto-blue-jays.gif',
'Washington Nationals': f'{PD_CARD_URL}/mvp/washington-nationals.gif',
'Junior All Stars': f'{PD_CARD_URL}/mvp.png',
'Mario Super Sluggers': f'{PD_CARD_URL}/mvp.png'
'Mario Super Sluggers': f'{PD_CARD_URL}/mvp.png',
'Pokemon League': 'https://i.postimg.cc/ydzYB7BR/masterball.jpg'
},
'gauntlets': f'{PD_CARD_URL}/gauntlets.png'
}
@ -245,6 +248,7 @@ SELECT_CARDSET_OPTIONS = [
]
ACTIVE_EVENT_LITERAL = Literal['1998 Season']
DEFENSE_LITERAL = Literal['Pitcher', 'Catcher', 'First Base', 'Second Base', 'Third Base', 'Shortstop', 'Left Field', 'Center Field', 'Right Field']
ACTIVE_EVENT_LITERAL = Literal['1998 Season', 'Brilliant Stars']
class Question:
@ -852,6 +856,7 @@ class SelectBuyPacksCardset(discord.ui.Select):
def __init__(self, team: dict, quantity: int, pack_type_id: int, pack_embed: discord.Embed, cost: int):
options = [
discord.SelectOption(label='1998 Live'),
discord.SelectOption(label='Pokemon - Brilliant Stars'),
discord.SelectOption(label='2024 Season'),
discord.SelectOption(label='2023 Season'),
discord.SelectOption(label='2022 Season'),
@ -895,6 +900,9 @@ class SelectBuyPacksCardset(discord.ui.Select):
cardset_id = 17
elif self.values[0] == '1998 Live':
cardset_id = 20
elif self.values[0] == 'Pokemon - Brilliant Stars':
cardset_id = 23
self.pack_embed.set_image(url=IMAGES['pack-pkmnbs'])
self.pack_embed.description = f'{self.pack_embed.description} - {self.values[0]}'
view = Confirm(responders=[interaction.user], timeout=30)
@ -1738,7 +1746,10 @@ async def get_card_embeds(card, include_stats=False) -> list:
# embed.add_field(name='# Dupes', value=f'{count - 1} dupe{"s" if count - 1 != 1 else ""}')
# embed.add_field(name='Team', value=f'{card["player"]["mlbclub"]}')
player_pages = f'[BBRef]({get_player_url(card["player"], "bbref")})'
if card['player']['franchise'] != 'Pokemon':
player_pages = f'[BBRef]({get_player_url(card["player"], "bbref")})'
else:
player_pages = f'[Pkmn]({PKMN_REF_URL}{card["player"]["bbref_id"]})'
embed.add_field(name='Player Page', value=f'{player_pages}')
embed.set_image(url=card["player"]["image"])
@ -1747,6 +1758,28 @@ async def get_card_embeds(card, include_stats=False) -> list:
embed.set_thumbnail(url=headshot)
else:
embed.set_thumbnail(url=IMAGES['logo'])
if card['player']['franchise'] == 'Pokemon':
if card['player']['fangr_id'] is not None:
try:
evo_mon = await db_get('players', object_id=card['player']['fangr_id'], none_okay=True)
if evo_mon is not None:
embed.add_field(
name='Evolves Into',
value=f'{evo_mon["p_name"]}'
)
except Exception as e:
logging.error('could not pull evolution: {e}', exc_info=True, stack_info=True)
if '420420' not in card['player']['strat_code']:
try:
evo_mon = await db_get('players', object_id=card['player']['strat_code'], none_okay=True)
if evo_mon is not None:
embed.add_field(
name='Evolves From',
value=f'{evo_mon["p_name"]}'
)
except Exception as e:
logging.error('could not pull evolution: {e}', exc_info=True, stack_info=True)
if include_stats:
if b_query['count'] > 0:
@ -2247,6 +2280,7 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list:
if pl['count'] != counts[key]['count']:
mvp_flag = counts[key]['count'] - pl['count']
logging.info(f'Set mvp flag to {mvp_flag} / cardset_id: {all_packs[0]["pack_cardset"]["id"]}')
for x in pl['players']:
this_pack_players.append(x)
@ -2255,12 +2289,21 @@ async def roll_for_cards(all_packs: list, extra_val=None) -> list:
if x['rarity']['value'] >= 3:
pull_notifs.append(x)
if mvp_flag:
if mvp_flag and all_packs[0]['pack_cardset']['id'] not in [23]:
logging.info(f'Adding {mvp_flag} MVPs for missing cards')
pl = await db_get('players/random', params=[('min_rarity', 5), ('limit', mvp_flag)])
for x in pl['players']:
this_pack_players.append(x)
all_players.append(x)
# Add dupes of Replacement/Reserve cards
elif mvp_flag:
logging.info(f'Adding {mvp_flag} duplicate pokemon cards')
for count in range(mvp_flag):
logging.info(f'Adding {pl["players"][0]["p_name"]} to the pack')
this_pack_players.append(x)
all_players.append(pl['players'][0])
success = await db_post(
'cards',
@ -2881,7 +2924,9 @@ async def paperdex_team_embed(team: dict, mlb_team: dict) -> list[discord.Embed]
def get_pack_cover(pack):
if pack['pack_type']['name'] in ['Premium', 'MVP']:
if pack['pack_cardset'] is not None and pack['pack_cardset'] == 23:
return IMAGES['pack-pkmnbs']
elif pack['pack_type']['name'] in ['Premium', 'MVP']:
return IMAGES['pack-pre']
elif pack['pack_type']['name'] == 'Standard':
return IMAGES['pack-sta']

View File

@ -1,3 +1,5 @@
import asyncio
import datetime
from typing import List
import discord
import logging
@ -7,6 +9,7 @@ from discord.utils import MISSING
from sqlmodel import Session
from exceptions import CardNotFoundException, PlayNotFoundException, log_exception
from helpers import get_card_embeds
from in_game.game_helpers import legal_check
from in_game.gameplay_models import Game, Lineup, Play, Team
from in_game.gameplay_queries import get_one_lineup, get_position, get_card_or_none
@ -285,4 +288,53 @@ class SelectBatterSub(discord.ui.Select):
content=f'{human_batter_card.player.name_with_desc} has entered in the {self.batting_order} spot. {pos_text}',
view=view
)
class SelectPokemonEvolution(discord.ui.Select):
def __init__(self, *, placeholder = 'Evolve the selected Pokemon', min_values = 1, max_values = 1, options = List[SelectOption], this_team):
logging.info(f'Inside SelectPokemonEvolution init function')
self.team = this_team
super().__init__(placeholder=placeholder, min_values=min_values, max_values=max_values, options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
try:
card_id = self.values[0]
this_card = await db_get(
'cards',
object_id=card_id,
none_okay=False
)
evo_mon = await db_get(
'players',
object_id=this_card['player']['fangr_id'],
none_okay=False
)
p_query = await db_post(
'packs/one',
payload={
'team_id': self.team['id'],
'pack_type_id': 4,
'open_time': datetime.datetime.timestamp(datetime.datetime.now()) * 1000}
)
pack_id = p_query['id']
await db_post(
'cards',
payload={'cards': [ {'player_id': evo_mon['player_id'], 'team_id': self.team['id'], 'pack_id': pack_id}]},
timeout=10
)
await interaction.edit_original_response(
content=f'## {this_card["player"]["p_name"].upper()} is evolving!',
embeds=await get_card_embeds(this_card),
view=None
)
await db_delete('cards', object_id=card_id)
await asyncio.sleep(3)
await interaction.channel.send(
content=f'## {this_card["player"]["p_name"].upper()} evolved into {evo_mon["p_name"].upper()}!',
embeds=await get_card_embeds({'team': self.team, 'player': evo_mon})
)
except Exception as e:
logging.error(f'Failed to evolve a pokemon: {e}', exc_info=True, stack_info=True)
await interaction.edit_original_response(content=f'Oh no, the evolution failed! Go ping the shit out of Cal so he can evolve it for you!')