Skip to content

Commit

Permalink
Fix not opening due to typescript changes
Browse files Browse the repository at this point in the history
  • Loading branch information
Tyrannicodin committed Sep 24, 2023
1 parent 4f95c1b commit fb73666
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 50 deletions.
66 changes: 49 additions & 17 deletions exts/card.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,9 @@ def __init__(self, client: Client, dataGenerator: dataGetter) -> None:
for k, v in list(self.dataGenerator.universeData.items())
]

def getStats(self, deck: list) -> tuple[Image.Image, tuple[int, int, int], dict[str, int]]:
def getStats(
self, deck: list
) -> tuple[Image.Image, tuple[int, int, int], dict[str, int]]:
typeCounts = {
"miner": 0,
"terraform": 0,
Expand Down Expand Up @@ -111,7 +113,11 @@ def getStats(self, deck: list) -> tuple[Image.Image, tuple[int, int, int], dict[
width, height = getBestFactors(len(deck))
im = Image.new("RGBA", (width * 200, height * 200))
for i, card in enumerate(hermits + effects + items):
toPaste = self.dataGenerator.universeImage[card].resize((200, 200)).convert("RGBA")
toPaste = (
self.dataGenerator.universeImage[card]
.resize((200, 200))
.convert("RGBA")
)
im.paste(toPaste, ((i % width) * 200, (i // width) * 200), toPaste)
return im, (len(hermits), len(effects), len(items)), typeCounts

Expand All @@ -121,9 +127,11 @@ async def card_autocomplete(self, ctx: AutocompleteContext):
await ctx.send(self.namedUniverse[0:25])
return
await ctx.send(
[card for card in self.namedUniverse if ctx.input_text.lower() in card["name"].lower()][
0:25
]
[
card
for card in self.namedUniverse
if ctx.input_text.lower() in card["name"].lower()
][0:25]
)

@slash_command()
Expand Down Expand Up @@ -175,10 +183,14 @@ async def deck(

deckList = hashToDeck(deck, self.dataGenerator.universe)
if len(deckList) > 100:
await ctx.send(f"A deck of {len(deckList)} cards is too large!", ephemeral=True)
await ctx.send(
f"A deck of {len(deckList)} cards is too large!", ephemeral=True
)
return
if not deckList:
await ctx.send("Invalid deck: Perhaps you're looking for /card info ||Niko||")
await ctx.send(
"Invalid deck: Perhaps you're looking for /card info ||Niko||"
)
return
im, hic, typeCounts = self.getStats(deckList)
col = typeColors[longest(typeCounts)[0]]
Expand All @@ -194,7 +206,11 @@ async def deck(
)
.add_field(
"Token cost",
str(hashToStars(deck, self.dataGenerator.rarities, self.dataGenerator.universe)),
str(
hashToStars(
deck, self.dataGenerator.rarities, self.dataGenerator.universe
)
),
True,
)
.add_field(
Expand Down Expand Up @@ -225,12 +241,18 @@ async def deck(
label="Copy",
emoji=":clipboard:",
url=f"{site}/?deck={deck}&name={quote(name)}",
disabled=(
not (show_hash or site != "https://hc-tcg-beta.fly.dev")
), # Only on beta, as it's the only place with a fix
disabled=(not show_hash)
or site
in [
"https://hc-tcg-beta.fly.dev",
"https://hc-tcg.fly.dev",
"https://tcg.xisumavoid.com",
],
)
if not show_hash:
await ctx.send("This message handily obscures your deck hash!", ephemeral=True)
await ctx.send(
"This message handily obscures your deck hash!", ephemeral=True
)
await ctx.send(
embeds=e,
files=File(im_binary, "deck.png"),
Expand All @@ -249,7 +271,9 @@ async def handleDelete(self, ctx: ComponentContext):
await ctx.send("You can't delete this deck message!", ephemeral=True)

@card.subcommand()
@slash_option("card", "The card id to get", OptionType.STRING, True, autocomplete=True)
@slash_option(
"card", "The card id to get", OptionType.STRING, True, autocomplete=True
)
async def info(self, ctx: SlashContext, card: str):
"""Get information about a card"""
card = card.casefold() # Ensure all lowercase
Expand Down Expand Up @@ -305,7 +329,9 @@ async def info(self, ctx: SlashContext, card: str):
else rgbToInt(beige),
).add_field(
"Rarity",
"Ultra rare" if dat["rarity"] == "ultra_rare" else dat["rarity"].capitalize(),
"Ultra rare"
if dat["rarity"] == "ultra_rare"
else dat["rarity"].capitalize(),
True,
)
e.set_thumbnail(f"attachment://{dat['id']}.png")
Expand Down Expand Up @@ -344,13 +370,17 @@ async def reload(self, ctx: SlashContext):
)"""

@card.subcommand()
@slash_option("hermits", "The number of hermits in your deck", OptionType.INTEGER, True)
@slash_option(
"hermits", "The number of hermits in your deck", OptionType.INTEGER, True
)
@slash_option(
"desired_chance",
"Looks for the number of turns to get this chance of having the desired number of cards",
OptionType.INTEGER,
)
@slash_option("desired_hermits", "The number of hermits you want", OptionType.INTEGER)
@slash_option(
"desired_hermits", "The number of hermits you want", OptionType.INTEGER
)
async def twohermits(
self,
ctx: SlashContext,
Expand All @@ -365,7 +395,9 @@ async def twohermits(
plt.figure()
xs = [i for i in range(35)]
ys = [probability(hermits, i, desired_hermits) * 100 for i in xs]
surpass = next((idx[0] for idx in enumerate(ys) if idx[1] >= desired_chance), None)
surpass = next(
(idx[0] for idx in enumerate(ys) if idx[1] >= desired_chance), None
)
plt.plot(xs, [y for y in ys])
plt.xlabel("Draws")
plt.ylabel("Probability")
Expand Down
100 changes: 67 additions & 33 deletions util/datagen.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,12 @@ def jsToJson(js: str):
data = decode(res + "}")
data["palette"] = "base"
if len(js.split("getPalette() {")) > 1:
data["palette"] = js.split("getPalette() {")[0].split("return '")[1].split("'")[0]
data["palette"] = (
js.split("getPalette() {")[1].split("return '")[1].split("'")[0]
)
if data["palette"] == "FAILURE_INVALID_DATA":
print(data)
print(js.split("getPalette() {")[1].split("return '")[1])
return data
except Exception as e:
print(e)
Expand All @@ -49,7 +54,9 @@ def changeColour(im, origin: tuple[int, int, int], new: tuple[int, int, int]):
return Image.fromarray(data)


def drawNoTransition(image: Image.Image, method: str, color: tuple[int, int, int], *args, **kwargs):
def drawNoTransition(
image: Image.Image, method: str, color: tuple[int, int, int], *args, **kwargs
):
bwIm = Image.new("1", image.size)
bwImDraw = ImageDraw.Draw(bwIm)

Expand All @@ -66,7 +73,9 @@ def dropShadow(
radius: int,
color: tuple[int, int, int, 0],
):
base = Image.new("RGBA", (image.width + radius * 2, image.height + radius * 2), color)
base = Image.new(
"RGBA", (image.width + radius * 2, image.height + radius * 2), color
)
alpha = Image.new("L", (image.width + radius * 2, image.height + radius * 2))
alpha.paste(image.getchannel("A"), (radius, radius))
base.putalpha(alpha.filter(GaussianBlur(radius)))
Expand Down Expand Up @@ -139,22 +148,26 @@ def get_rarities(self) -> list[Image.Image]:
self.rarities: defaultdict = defaultdict(
int,
decode(
self.repo.get_contents("common/config/ranks.json", "beta").decoded_content.decode()
self.repo.get_contents(
"common/config/ranks.json"
).decoded_content.decode()
),
)
rarityImages: list[Image.Image] = [0 for _ in range(len(self.rarities["ranks"]))]
rarityImages: list[Image.Image] = [
0 for _ in range(len(self.rarities["ranks"]))
]
for rarity, rarityVal in self.rarities.pop("ranks").items():
rarityImages[rarityVal[0]] = self.getImage(rarity, "ranks").resize(
(70, 70), Image.Resampling.NEAREST
)
return rarityImages

def loadData(self) -> None:
for card_dir in self.repo.get_contents("common/cards", "beta"):
for card_dir in self.repo.get_contents("common/cards"):
if card_dir.type != "dir" or card_dir.name == "base":
continue # Ignore if file
cards = []
for file in self.repo.get_contents(f"common/cards/{card_dir.name}", "beta"):
for file in self.repo.get_contents(f"common/cards/{card_dir.name}"):
if file.name.startswith("_") or "index" in file.name:
continue # Ignore index and class definition
dat = jsToJson(file.decoded_content.decode())
Expand All @@ -164,8 +177,12 @@ def loadData(self) -> None:

def getImage(self, name: str, subDir: str = "") -> Image.Image:
if not subDir in self.cache.keys():
self.cache[subDir] = self.repo.get_contents(f"client/public/images/{subDir}", "beta")
foundFile = next((file for file in self.cache[subDir] if file.name == f"{name}.png"), None)
self.cache[subDir] = self.repo.get_contents(
f"client/public/images/{subDir}"
)
foundFile = next(
(file for file in self.cache[subDir] if file.name == f"{name}.png"), None
)
return (
Image.open(BytesIO(foundFile.decoded_content))
if foundFile
Expand All @@ -176,7 +193,7 @@ def getStar(self) -> Image.Image:
im = Image.new("RGBA", (1057, 995))
imDraw = ImageDraw.Draw(im)
points = (
self.repo.get_contents(f"client/public/images/star_white.svg", "beta")
self.repo.get_contents(f"client/public/images/star_white.svg")
.decoded_content.decode()
.split('points="')[1]
.split('"')[0]
Expand All @@ -193,11 +210,11 @@ def getStar(self) -> Image.Image:
return im

def reload(self) -> None:
self.get_universe()
self.tempImages["star"] = self.getStar()
self.tempImages["rarity_stars"] = self.get_rarities()
self.type_images()
self.loadData()
self.get_universe()
# Run these before to get info and base images

self.tempImages.update(
Expand All @@ -212,7 +229,9 @@ def reload(self) -> None:
x2Overlay = self.overlay_x2() # Add the overlay to x2 items
self.tempImages["base_item_x2"].paste(x2Overlay, (0, 302), x2Overlay)

for hermit in self.universes["hermits"]: # Go through each hermit and generate an image
for hermit in self.universes[
"hermits"
]: # Go through each hermit and generate an image
if not hermit.split("_")[0] in self.tempImages.keys():
self.tempImages[hermit.split("_")[0]] = self.hermitFeatureImage(
hermit.split("_")[0]
Expand Down Expand Up @@ -240,7 +259,9 @@ def reload(self) -> None:
)

for item in self.universes["items"]:
self.universeImage[item] = self.item(item.split("_")[1], item.split("_")[2] == "rare")
self.universeImage[item] = self.item(
item.split("_")[1], item.split("_")[2] == "rare"
)

self.health()

Expand All @@ -259,7 +280,9 @@ def base_hermit(self) -> Image.Image:

def base_item(
self,
) -> (Image.Image): # Generates the background for all items, the icon is pasted on top
) -> (
Image.Image
): # Generates the background for all items, the icon is pasted on top
im = Image.new("RGBA", (400, 400), colors.WHITE)
drawNoTransition(
im, "rounded_rectangle", colors.REPLACE, (10, 10, 390, 390), 15
Expand All @@ -270,7 +293,10 @@ def base_item(
.resize(
(
390,
int(self.tempImages["star"].height * (390 / self.tempImages["star"].width)),
int(
self.tempImages["star"].height
* (390 / self.tempImages["star"].width)
),
),
Image.Resampling.NEAREST,
)
Expand All @@ -289,7 +315,9 @@ def base_item(
return im

def overlay_x2(self) -> Image.Image: # Additional parts for a 2x item
im = Image.new("RGBA", (400, 100)) # Only 100 tall as it's just the two bottom circles
im = Image.new(
"RGBA", (400, 100)
) # Only 100 tall as it's just the two bottom circles
imDraw = ImageDraw.Draw(im, "RGBA")

imDraw.ellipse((0, 0, 100, 100), colors.WHITE) # Rarity star circle
Expand Down Expand Up @@ -319,7 +347,10 @@ def base_effect(
.resize(
(
390,
int(self.tempImages["star"].height * (390 / self.tempImages["star"].width)),
int(
self.tempImages["star"].height
* (390 / self.tempImages["star"].width)
),
),
Image.Resampling.NEAREST,
)
Expand All @@ -337,17 +368,23 @@ def base_effect(
return im

def type_images(self) -> None: # Gets all type images
for file in self.repo.get_contents(f"client/public/images/types", "beta"):
for file in self.repo.get_contents(f"client/public/images/types"):
file: ContentFile.ContentFile = file
self.tempImages[file.name.split(".")[0]] = Image.open(BytesIO(file.decoded_content))
self.tempImages[file.name.split(".")[0]] = Image.open(
BytesIO(file.decoded_content)
)

def hermitFeatureImage(self, hermitName: str) -> Image.Image:
bg = self.getImage(hermitName, "backgrounds").convert("RGBA")
if bg.size == (0, 0): # Alter ego
bg = self.getImage("alter_egos_background", "backgrounds").convert("RGBA")
bg = bg.resize((290, int(bg.height * (290 / bg.width))), Image.Resampling.NEAREST)
bg = bg.resize(
(290, int(bg.height * (290 / bg.width))), Image.Resampling.NEAREST
)
skin = self.getImage(hermitName, "hermits-nobg").convert("RGBA")
skin = skin.resize((290, int(skin.height * (290 / skin.width))), Image.Resampling.NEAREST)
skin = skin.resize(
(290, int(skin.height * (290 / skin.width))), Image.Resampling.NEAREST
)
shadow = dropShadow(skin, 8, colors.SHADOW)
bg.paste(shadow, (-8, -8), shadow)
bg.paste(skin, (0, 0), skin)
Expand Down Expand Up @@ -384,7 +421,9 @@ def hermit(
yCoord = 272 if i == 0 else 342

toCenter = Image.new("RGBA", (84, 28))
for a, cost in enumerate(attacks[i]["cost"]): # Generate centralised cost image
for a, cost in enumerate(
attacks[i]["cost"]
): # Generate centralised cost image
costIm = (
self.tempImages[f"type-{cost}"]
.resize((28, 28), Image.Resampling.NEAREST)
Expand Down Expand Up @@ -436,7 +475,9 @@ def effect(self, imageName: str, rarity: int):
im = self.tempImages["base_effect"].copy()
imDraw = ImageDraw.Draw(im)
if rarity > 0:
imDraw.ellipse((0, 302, 100, 402), palettes["base"].BACKGROUND) # Rarity icon
imDraw.ellipse(
(0, 302, 100, 402), palettes["base"].BACKGROUND
) # Rarity icon
im.paste(
self.tempImages["rarity_stars"][rarity],
(15, 315),
Expand Down Expand Up @@ -496,16 +537,9 @@ def health(self):
)

def get_universe(self):
universeFile: ContentFile.ContentFile = self.repo.get_contents(
"client/src/components/import-export/import-export-const.ts", "beta"
)
universeString = universeFile.decoded_content.decode().split(" = ")[1]
while "//" in universeString:
universeString = (
universeString.split("//", 1)[0]
+ universeString.split("//", 1)[1].split("\n", 1)[1]
)
self.universe = decode(universeString)
self.universe = ["" for _ in enumerate(self.universeData)]
for card_id, card_data in self.universeData.items():
self.universe[card_data["numericId"]] = card_id


if __name__ == "__main__":
Expand Down

0 comments on commit fb73666

Please sign in to comment.