1
Fork 0
mirror of https://github.com/wlinator/luminara.git synced 2024-10-02 18:03:12 +00:00

Fix blackjack command with new yaml settings

This commit is contained in:
wlinator 2024-08-27 06:27:30 -04:00
parent 4053bc9882
commit aa0b2f803a
6 changed files with 94 additions and 97 deletions

View file

@ -6,7 +6,6 @@ from discord.ext import commands
from loguru import logger
import Client
import config.parser
import services.config_service
import services.help_service
from db.database import run_migrations
@ -91,13 +90,6 @@ if __name__ == "__main__":
# Run database migrations
run_migrations()
# cache all JSON
[
config.parser.JsonCache.read_json(file[:-5])
for file in os.listdir("config/JSON")
if file.endswith(".json")
]
# load command and listener cogs
load_modules()

View file

@ -2,25 +2,21 @@ import os
from typing import Optional, Set, List, Dict
import yaml
import json
from functools import lru_cache
class _parser:
_yaml_cache = {}
_json_cache = {}
@lru_cache(maxsize=1048576) # Approximately 1MB
def read_yaml(self, path):
if path not in _parser._cache:
with open(f"settings/{path}.yaml") as file:
_parser._cache[path] = yaml.safe_load(file)
return _parser._yaml_cache[path]
return self._read_file(f"settings/{path}.yaml", yaml.safe_load)
@lru_cache(maxsize=1048576) # Approximately 1MB
def read_json(self, path):
if path not in _parser._cache:
with open(f"settings/responses/{path}.json") as file:
_parser._cache[path] = json.load(file)
return self._read_file(f"settings/{path}.json", json.load)
return _parser._json_cache[path]
def _read_file(self, file_path, load_func):
with open(file_path) as file:
return load_func(file)
class Constants:
@ -67,33 +63,35 @@ class Constants:
# economy
DAILY_REWARD: int = _settings["economy"]["daily_reward"]
BLACKJACK_MULTIPLIER: float = _settings["economy"]["blackjack_multiplier"]
BLACKJACK_HIT_EMOJI: str = _settings["economy"]["blackjack_hit_emoji"]
BLACKJACK_STAND_EMOJI: str = _settings["economy"]["blackjack_stand_emoji"]
SLOTS_MULTIPLIERS: Dict[str, float] = _settings["economy"]["slots_multipliers"]
# art from git repository
_fetch_url: str = _settings["fetch_url"]
_fetch_url: str = _settings["art"]["fetch_url"]
LOGO_OPAQUE: str = _fetch_url + _settings["logo"]["opaque"]
LOGO_TRANSPARENT: str = _fetch_url + _settings["logo"]["transparent"]
ICONS_BOOST: str = _fetch_url + _settings["icons"]["boost"]
ICONS_CHECK: str = _fetch_url + _settings["icons"]["check"]
ICONS_CROSS: str = _fetch_url + _settings["icons"]["cross"]
ICONS_EXCLAIM: str = _fetch_url + _settings["icons"]["exclaim"]
ICONS_HAMMER: str = _fetch_url + _settings["icons"]["hammer"]
ICONS_MONEY_BAG: str = _fetch_url + _settings["icons"]["money_bag"]
ICONS_MONEY_COINS: str = _fetch_url + _settings["icons"]["money_coins"]
ICONS_QUESTION: str = _fetch_url + _settings["icons"]["question"]
ICONS_STREAK: str = _fetch_url + _settings["icons"]["streak"]
ICONS_STREAK_BRONZE: str = _fetch_url + _settings["icons"]["streak_bronze"]
ICONS_STREAK_GOLD: str = _fetch_url + _settings["icons"]["streak_gold"]
ICONS_STREAK_SILVER: str = _fetch_url + _settings["icons"]["streak_silver"]
ICONS_WARNING: str = _fetch_url + _settings["icons"]["warning"]
JUICYBBLUE_FLOWERS: str = _fetch_url + _settings["juicybblue"]["flowers"]
JUICYBBLUE_TEAPOT: str = _fetch_url + _settings["juicybblue"]["teapot"]
JUICYBBLUE_MUFFIN: str = _fetch_url + _settings["juicybblue"]["muffin"]
LUMI_LOGO_OPAQUE: str = _fetch_url + _settings["art"]["logo"]["opaque"]
LUMI_LOGO_TRANSPARENT: str = _fetch_url + _settings["art"]["logo"]["transparent"]
BOOST_ICON: str = _fetch_url + _settings["art"]["icons"]["boost"]
CHECK_ICON: str = _fetch_url + _settings["art"]["icons"]["check"]
CROSS_ICON: str = _fetch_url + _settings["art"]["icons"]["cross"]
EXCLAIM_ICON: str = _fetch_url + _settings["art"]["icons"]["exclaim"]
HAMMER_ICON: str = _fetch_url + _settings["art"]["icons"]["hammer"]
MONEY_BAG_ICON: str = _fetch_url + _settings["art"]["icons"]["money_bag"]
MONEY_COINS_ICON: str = _fetch_url + _settings["art"]["icons"]["money_coins"]
QUESTION_ICON: str = _fetch_url + _settings["art"]["icons"]["question"]
STREAK_ICON: str = _fetch_url + _settings["art"]["icons"]["streak"]
STREAK_BRONZE_ICON: str = _fetch_url + _settings["art"]["icons"]["streak_bronze"]
STREAK_GOLD_ICON: str = _fetch_url + _settings["art"]["icons"]["streak_gold"]
STREAK_SILVER_ICON: str = _fetch_url + _settings["art"]["icons"]["streak_silver"]
WARNING_ICON: str = _fetch_url + _settings["art"]["icons"]["warning"]
# art from imgur
IMGUR_CLOUD: str = _settings["other"]["cloud"]
IMGUR_TROPHY: str = _settings["other"]["trophy"]
FLOWERS_ART: str = _settings["art"]["juicybblue"]["flowers"]
TEAPOT_ART: str = _settings["art"]["juicybblue"]["teapot"]
MUFFIN_ART: str = _settings["art"]["juicybblue"]["muffin"]
CLOUD_ART: str = _settings["art"]["other"]["cloud"]
TROPHY_ART: str = _settings["art"]["other"]["trophy"]
# emotes
EMOTES_SERVER_ID: int = _settings["emotes"]["guild_id"]
@ -108,11 +106,11 @@ class Constants:
# Response strings
# TODO: Implement switching between languages
STRINGS = _parser().read_json("responses/strings.en-US")
LEVEL_MESSAGES = _parser().read_json("responses/levels.en-US")
STRINGS = _p.read_json("responses/strings.en-US")
LEVEL_MESSAGES = _p.read_json("responses/levels.en-US")
# birthday messages
_bday = _parser().read_json("responses/bdays.en-US")
_bday = _p.read_json("responses/bdays.en-US")
BIRTHDAY_MESSAGES = _bday["birthday_messages"]
BIRTHDAY_MONTHS = _bday["months"]

View file

@ -2,49 +2,6 @@ import discord
from discord.ui import View
class BlackJackButtons(View):
def __init__(self, ctx):
super().__init__(timeout=180)
self.ctx = ctx
self.clickedHit = False
self.clickedStand = False
self.clickedDoubleDown = False
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(view=None)
@discord.ui.button(
label="hit",
style=discord.ButtonStyle.gray,
emoji="<:hit:1119262723285467156> ",
)
async def hit_button_callback(self, button, interaction):
self.clickedHit = True
await interaction.response.defer()
self.stop()
@discord.ui.button(
label="stand",
style=discord.ButtonStyle.gray,
emoji="<:stand:1118923298298929154>",
)
async def stand_button_callback(self, button, interaction):
self.clickedStand = True
await interaction.response.defer()
self.stop()
async def interaction_check(self, interaction) -> bool:
if interaction.user == self.ctx.author:
return True
await interaction.response.send_message(
"You can't use these buttons, they're someone else's!",
ephemeral=True,
)
return False
class ExchangeConfirmation(View):
def __init__(self, ctx):
super().__init__(timeout=180)

View file

@ -1,11 +1,12 @@
import random
from typing import List, Tuple
from loguru import logger
import discord
from discord.ui import View
import pytz
from discord.ext import commands
from lib import interaction
from lib.constants import CONST
from lib.exceptions.LumiExceptions import LumiException
from services.currency_service import Currency
@ -34,6 +35,7 @@ async def cmd(ctx: commands.Context, bet: int) -> None:
try:
await play_blackjack(ctx, currency, bet)
except Exception as e:
logger.exception(f"Error in blackjack game: {e}")
raise LumiException(CONST.STRINGS["error_blackjack_game_error"]) from e
finally:
del ACTIVE_BLACKJACK_GAMES[ctx.author.id]
@ -42,11 +44,11 @@ async def cmd(ctx: commands.Context, bet: int) -> None:
async def play_blackjack(ctx: commands.Context, currency: Currency, bet: int) -> None:
deck = get_new_deck()
player_hand, dealer_hand = initial_deal(deck)
multiplier = float(CONST.BLACKJACK["reward_multiplier"])
multiplier = CONST.BLACKJACK_MULTIPLIER
player_value = calculate_hand_value(player_hand)
status = 5 if player_value == 21 else 0
view = interaction.BlackJackButtons(ctx)
view = BlackJackButtons(ctx)
playing_embed = False
while status == 0:
@ -85,7 +87,7 @@ async def play_blackjack(ctx: commands.Context, currency: Currency, bet: int) ->
currency.push()
raise LumiException(CONST.STRINGS["error_out_of_time_economy"])
view = interaction.BlackJackButtons(ctx)
view = BlackJackButtons(ctx)
await handle_game_end(
ctx,
@ -255,8 +257,8 @@ def create_end_game_embed(
def get_new_deck() -> List[Card]:
deck = [
rank + suit
for suit in CONST.BLACKJACK["deck_suits"]
for rank in CONST.BLACKJACK["deck_ranks"]
for suit in ["", "", "", ""]
for rank in ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
]
random.shuffle(deck)
return deck
@ -277,3 +279,46 @@ def calculate_hand_value(hand: Hand) -> int:
value -= 10
aces -= 1
return value
class BlackJackButtons(View):
def __init__(self, ctx):
super().__init__(timeout=180)
self.ctx = ctx
self.clickedHit = False
self.clickedStand = False
self.clickedDoubleDown = False
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(view=None)
@discord.ui.button(
label=CONST.STRINGS["blackjack_hit"],
style=discord.ButtonStyle.gray,
emoji=CONST.BLACKJACK_HIT_EMOJI,
)
async def hit_button_callback(self, button, interaction):
self.clickedHit = True
await interaction.response.defer()
self.stop()
@discord.ui.button(
label=CONST.STRINGS["blackjack_stand"],
style=discord.ButtonStyle.gray,
emoji=CONST.BLACKJACK_STAND_EMOJI,
)
async def stand_button_callback(self, button, interaction):
self.clickedStand = True
await interaction.response.defer()
self.stop()
async def interaction_check(self, interaction) -> bool:
if interaction.user == self.ctx.author:
return True
await interaction.response.send_message(
CONST.STRINGS["error_cant_use_buttons"],
ephemeral=True,
)
return False

View file

@ -49,6 +49,8 @@
"blackjack_won_21": "You won with a score of 21!",
"blackjack_won_natural": "You won with a natural hand!",
"blackjack_won_payout": "You won **${0}**.",
"blackjack_hit": "hit",
"blackjack_stand": "stand",
"boost_default_description": "Thanks for boosting, **{0}**!!",
"boost_default_title": "New Booster",
"case_case_field": "Case:",
@ -289,5 +291,6 @@
"give_error_bot": "you can't give money to a bot.",
"give_error_invalid_amount": "invalid amount.",
"give_error_insufficient_funds": "you don't have enough cash.",
"give_success": "**{0}** gave **${1}** to {2}."
"give_success": "**{0}** gave **${1}** to {2}.",
"error_cant_use_buttons": "You can't use these buttons, they're someone else's!"
}

View file

@ -20,6 +20,8 @@ colors:
economy:
daily_reward: 500
blackjack_multiplier: 1.4
blackjack_hit_emoji: <:hit:1119262723285467156>
blackjack_stand_emoji: <:stand:1118923298298929154>
slots_multipliers:
pair: 1.5
three_of_a_kind: 4
@ -46,9 +48,9 @@ art:
streak_silver: lumi_streak_silver.png
warning: lumi_warning.png
juicybblue:
flowers: juicybblue_flowers.png
teapot: juicybblue_teapot.png
muffin: juicybblue_muffin.png
flowers: https://i.imgur.com/79XfsbS.png
teapot: https://i.imgur.com/wFsgSnr.png
muffin: https://i.imgur.com/hSauh7K.png
other:
cloud: https://i.imgur.com/rc68c43.png
trophy: https://i.imgur.com/dvIIr2G.png