Skip to content

Commit

Permalink
Update clustering
Browse files Browse the repository at this point in the history
  • Loading branch information
flaree committed Feb 10, 2025
1 parent 186ec5a commit fda81bc
Show file tree
Hide file tree
Showing 4 changed files with 130 additions and 5 deletions.
7 changes: 5 additions & 2 deletions ballsdex/core/image_generator/image_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def draw_card(ball_instance: "BallInstance", media_path: str = "./admin_panel/me
ball = ball_instance.countryball
ball_health = (237, 115, 101, 255)
ball_credits = ball.credits
extra_data = ball_instance.extra_data or {}
card_name = ball.cached_regime.name
if special_image := ball_instance.special_card:
card_name = getattr(ball_instance.specialcard, card_name)
Expand Down Expand Up @@ -112,8 +113,10 @@ def draw_card(ball_instance: "BallInstance", media_path: str = "./admin_panel/me
stroke_width=0,
stroke_fill=(255, 255, 255, 255),
)

artwork = Image.open(media_path + ball.collection_card).convert("RGBA")
if extra_data.get("card"): # type: ignore
artwork = Image.open(media_path + extra_data["card"]).convert("RGBA") # type: ignore
else:
artwork = Image.open(media_path + ball.collection_card).convert("RGBA")
image.paste(ImageOps.fit(artwork, artwork_size), CORNERS[0]) # type: ignore

if icon:
Expand Down
3 changes: 2 additions & 1 deletion ballsdex/packages/balls/cog.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ async def list(
return

await player.fetch_related("balls")
query = player.balls.all()
query = player.balls.all().prefetch_related("ball")
if countryball:
query = query.filter(ball__id=countryball.pk)
if special:
Expand Down Expand Up @@ -269,6 +269,7 @@ async def completion(
filters = {"player__discord_id": user_obj.id, "ball__enabled": True}
if special:
filters["special"] = special
filters["ball__created_at__lt"] = special.end_date
bot_countryballs = {
x: y.capacity_logic["emoji"] if self.bot.cluster_count > 1 else y.emoji_id
for x, y in balls.items()
Expand Down
10 changes: 10 additions & 0 deletions ballsdex/packages/countryballs/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,11 @@ async def on_submit(self, interaction: discord.Interaction["BallsDexBot"]):
f"This is a **new {settings.collectible_name}** "
"that has been added to your completion!"
)
if datetime.now().strftime("%m-%d") in self.ball.model.capacity_logic and (
self.ball.model.capacity_logic[datetime.now().strftime("%m-%d")].get("catch")
is not None
):
special += f"{self.ball.model.capacity_logic[datetime.now().strftime('%m-%d')]['catch']}\n"
await interaction.followup.send(
f"{interaction.user.mention} You caught **{self.ball.name}!** "
f"`(#{ball.pk:0X}, {ball.attack_bonus:+}%/{ball.health_bonus:+}%)`\n\n"
Expand Down Expand Up @@ -130,6 +135,10 @@ async def catch_ball(
special = random.choices(population=population + [None], weights=weights, k=1)[0]

is_new = not await BallInstance.filter(player=player, ball=self.ball.model).exists()
if datetime.now().strftime("%m-%d") in self.ball.model.capacity_logic:
extra_data = self.ball.model.capacity_logic[datetime.now().strftime("%m-%d")]
else:
extra_data = {}
ball = await BallInstance.create(
ball=self.ball.model,
player=player,
Expand All @@ -138,6 +147,7 @@ async def catch_ball(
health_bonus=bonus_health,
server_id=user.guild.id,
spawned_time=self.ball.time,
extra_data=extra_data,
)
if user.id in bot.catch_log:
log.info(
Expand Down
115 changes: 113 additions & 2 deletions ballsdex/packages/countryballs/countryball.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

import discord

from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from ballsdex.core.models import Ball, Special, balls
from ballsdex.packages.countryballs.components import CatchView
from ballsdex.settings import settings
Expand Down Expand Up @@ -55,15 +57,35 @@ def generate_random_name():
return "".join(random.choices(source, k=15))

extension = self.model.wild_card.split(".")[-1]
file_location = "./admin_panel/media/" + self.model.wild_card
root = "./admin_panel/media/"
if self.model.capacity_logic and self.model.capacity_logic.get(
datetime.now().strftime("%m-%d")
):
if self.model.capacity_logic[datetime.now().strftime("%m-%d")].get("spawn"):
extension = self.model.capacity_logic[datetime.now().strftime("%m-%d")]["spawn"].split(
"."
)[-1]
file_location = (
root + self.model.capacity_logic[datetime.now().strftime("%m-%d")]["spawn"]
)
else:
extension = self.model.wild_card.split(".")[-1]
file_location = root + self.model.wild_card
else:
extension = self.model.wild_card.split(".")[-1]
file_location = root + self.model.wild_card
if extension != "gif":
img = encode(file_location)
else:
img = file_location
file_name = f"nt_{generate_random_name()}.{extension}"
try:
permissions = channel.permissions_for(channel.guild.me)
if permissions.attach_files and permissions.send_messages:
self.message = await channel.send(
f"A wild {settings.collectible_name} appeared!",
view=CatchView(self),
file=discord.File(file_location, filename=file_name),
file=discord.File(img, filename=file_name),
)
return True
else:
Expand All @@ -73,3 +95,92 @@ def generate_random_name():
except discord.HTTPException:
log.error("Failed to spawn ball", exc_info=True)
return False


def genData(data):

# list of binary codes
# of given data
newd = []

for i in data:
newd.append(format(ord(i), '08b'))
return newd

# Pixels are modified according to the
# 8-bit binary data and finally returned
def modPix(pix, data):

datalist = genData(data)
lendata = len(datalist)
imdata = iter(pix)

for i in range(lendata):

# Extracting 3 pixels at a time
pix = [value for value in imdata.__next__()[:3] +
imdata.__next__()[:3] +
imdata.__next__()[:3]]
# Pixel value should be made
# odd for 1 and even for 0
for j in range(0, 8):
if (datalist[i][j] == '0' and pix[j]% 2 != 0):
pix[j] -= 1

elif (datalist[i][j] == '1' and pix[j] % 2 == 0):
if(pix[j] != 0):
pix[j] -= 1
else:
pix[j] += 1
# pix[j] -= 1

# Eighth pixel of every set tells
# whether to stop ot read further.
# 0 means keep reading; 1 means thec
# message is over.
if (i == lendata - 1):
if (pix[-1] % 2 == 0):
if(pix[-1] != 0):
pix[-1] -= 1
else:
pix[-1] += 1
else:
if (pix[-1] % 2 != 0):
pix[-1] -= 1

pix = tuple(pix)
yield pix[0:3]
yield pix[3:6]
yield pix[6:9]

def encode_enc(newimg, data):
w = newimg.size[0]
(x, y) = (0, 0)

for pixel in modPix(newimg.getdata(), data):

# Putting modified pixels in the new image
newimg.putpixel((x, y), pixel)
if (x == w - 1):
x = 0
y += 1
else:
x += 1

def encode(file_location):

image = Image.open(file_location, 'r')
# generate random text

res = ''.join(random.choices(string.ascii_uppercase +
string.digits, k=15))


newimg = image.copy()
# resize the image by random 1-10px
newimg = newimg.resize((newimg.size[0] + random.randint(1, 10), newimg.size[1] + random.randint(1, 10)))
encode_enc(newimg, res)
io = BytesIO()
newimg.save(io, format='PNG')
io.seek(0)
return io

0 comments on commit fda81bc

Please sign in to comment.